import {
  JACKPOT_ACCUM,
  aiAction,
  applyAction,
  applyHeroSplit,
  createGame,
  startHand,
} from './engine';
import { bestSplit } from './handEval';
import type { GameState } from './types';

// 含奖池：爆奖派奖在玩家筹码与奖池之间转移，奖池每局额外累积 JACKPOT_ACCUM
function totalChips(g: GameState): number {
  return (
    g.seats.reduce((sum, s) => sum + s.chips, 0) +
    g.pot +
    g.mangoPool +
    g.piPool +
    g.jackpot.total
  );
}

let g = createGame();
const initial = totalChips(g);
let hands = 0;
let guard = 0;

while (hands < 500 && guard < 2000000) {
  guard++;
  if (g.phase === 'betting') {
    const idx = g.actorIndex;
    if (idx < 0) throw new Error('betting but no actor');
    // 全部由 AI 决策（包含 hero 座位，用于压测）
    const d = aiAction(g);
    g = applyAction(g, d.action, d.amount);
  } else if (g.phase === 'split') {
    // 本人手动分牌阶段：压测中用最优分墩代替
    const hero = g.seats.find((s) => s.isHero)!;
    const sh = bestSplit(hero.cards);
    g = applyHeroSplit(g, [sh.head[0].id, sh.head[1].id]);
  } else if (g.phase === 'settle') {
    hands++;
    const t = totalChips(g);
    const expected = initial + hands * JACKPOT_ACCUM;
    if (Math.abs(t - expected) > 1e-6) {
      console.error(`筹码不守恒！局 ${hands}: ${t} vs ${expected}`);
      process.exit(1);
    }
    g = startHand(g, (g.dealerIndex + 1) % g.seats.length);
  } else {
    throw new Error(`意外阶段 ${g.phase}`);
  }
}

console.log(`迭代 ${guard} 次, 模拟 ${hands} 局完成，筹码守恒 (总额 ${initial})`);
console.log('末局消息:', g.message);
