#!/usr/bin/env node

import { createHash } from 'node:crypto';
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

export const RANKS = ['J', 'Q', 'K'];
export const DEALS = RANKS.flatMap(first => RANKS
    .filter(second => second !== first)
    .map(second => [first, second]));
export const CHECKPOINTS = [
    1, 2, 5, 10, 20, 50, 100, 200,
    500, 1_000, 2_000, 5_000, 10_000, 20_000, 50_000, 100_000,
];
export const TRACE_ITERATIONS = new Set([
    1, 2, 5, 10, 20, 50,
    ...Array.from({ length: 1_000 }, (_, index) => (index + 1) * 100),
]);
export const GAME_VALUE_P0 = -1 / 18;
export const GENERATED_UTC = '2026-09-07T07:27:16Z';

const OUTPUT_DIRECTORY = dirname(fileURLToPath(import.meta.url));
const ACTIONS_BY_HISTORY = {
    '': ['check', 'bet'],
    c: ['check', 'bet'],
    b: ['fold', 'call'],
    cb: ['fold', 'call'],
};

export const infoSetKey = (player, card, history) => (
    `P${player}|${card}|${history || 'root'}`
);

export const actingPlayer = history => (
    history === '' || history === 'cb' ? 0 : 1
);

export const terminalUtilityP0 = (cards, history) => {
    if (history === 'bf') return 1;
    if (history === 'cbf') return -1;
    if (!['cc', 'bc', 'cbc'].includes(history)) return null;
    const stake = history === 'cc' ? 1 : 2;
    return (RANKS.indexOf(cards[0]) > RANKS.indexOf(cards[1]) ? 1 : -1) * stake;
};

const allInfoSetKeys = player => RANKS.flatMap(card => (
    player === 0
        ? [infoSetKey(0, card, ''), infoSetKey(0, card, 'cb')]
        : [infoSetKey(1, card, 'c'), infoSetKey(1, card, 'b')]
));

const allKeys = [...allInfoSetKeys(0), ...allInfoSetKeys(1)];

export const regretMatchedStrategy = regrets => {
    const positive = regrets.map(value => Math.max(0, value));
    const total = positive[0] + positive[1];
    return total > 0 ? positive.map(value => value / total) : [0.5, 0.5];
};

const createTables = () => Object.fromEntries(allKeys.map(key => [key, {
    cumulativeRegret: [0, 0],
    strategySum: [0, 0],
}]));

const currentPolicy = tables => Object.fromEntries(allKeys.map(key => [
    key,
    regretMatchedStrategy(tables[key].cumulativeRegret),
]));

const averagePolicy = tables => Object.fromEntries(allKeys.map(key => {
    const sums = tables[key].strategySum;
    const total = sums[0] + sums[1];
    return [key, total > 0 ? sums.map(value => value / total) : [0.5, 0.5]];
}));

const emptyDeltas = () => Object.fromEntries(allKeys.map(key => [key, [0, 0]]));

const traverseForCfr = ({
    cards,
    history,
    reach0,
    reach1,
    policy,
    tables,
    regretDeltas,
}) => {
    const terminal = terminalUtilityP0(cards, history);
    if (terminal !== null) return terminal;

    const player = actingPlayer(history);
    const key = infoSetKey(player, cards[player], history);
    const strategy = policy[key];
    const actionCodes = history === '' || history === 'c' ? ['c', 'b'] : ['f', 'c'];
    const actionUtilities = actionCodes.map((action, actionIndex) => traverseForCfr({
        cards,
        history: history + action,
        reach0: player === 0 ? reach0 * strategy[actionIndex] : reach0,
        reach1: player === 1 ? reach1 * strategy[actionIndex] : reach1,
        policy,
        tables,
        regretDeltas,
    }));
    const nodeUtility = strategy.reduce((sum, probability, actionIndex) => (
        sum + probability * actionUtilities[actionIndex]
    ), 0);
    const chance = 1 / DEALS.length;

    if (player === 0) {
        for (let actionIndex = 0; actionIndex < 2; actionIndex += 1) {
            regretDeltas[key][actionIndex] += chance * reach1
                * (actionUtilities[actionIndex] - nodeUtility);
            tables[key].strategySum[actionIndex] += chance * reach0 * strategy[actionIndex];
        }
    } else {
        for (let actionIndex = 0; actionIndex < 2; actionIndex += 1) {
            regretDeltas[key][actionIndex] += chance * reach0
                * (nodeUtility - actionUtilities[actionIndex]);
            tables[key].strategySum[actionIndex] += chance * reach1 * strategy[actionIndex];
        }
    }
    return nodeUtility;
};

export const evaluatePolicy = (policy, responder = null, pureResponse = null) => {
    const evaluateDeal = (cards, history = '') => {
        const terminal = terminalUtilityP0(cards, history);
        if (terminal !== null) return terminal;
        const player = actingPlayer(history);
        const key = infoSetKey(player, cards[player], history);
        const actionCodes = history === '' || history === 'c' ? ['c', 'b'] : ['f', 'c'];
        if (player === responder) {
            return evaluateDeal(cards, history + actionCodes[pureResponse[key]]);
        }
        return policy[key].reduce((sum, probability, actionIndex) => (
            sum + probability * evaluateDeal(cards, history + actionCodes[actionIndex])
        ), 0);
    };
    return DEALS.reduce((sum, cards) => sum + evaluateDeal(cards), 0) / DEALS.length;
};

export const exactBestResponse = (policy, responder) => {
    const keys = allInfoSetKeys(responder);
    let bestPlayerValue = -Infinity;
    let bestUtilityP0 = null;
    let bestMask = null;
    for (let mask = 0; mask < 2 ** keys.length; mask += 1) {
        const pureResponse = Object.fromEntries(keys.map((key, index) => [
            key,
            (mask >> index) & 1,
        ]));
        const utilityP0 = evaluatePolicy(policy, responder, pureResponse);
        const playerValue = responder === 0 ? utilityP0 : -utilityP0;
        if (playerValue > bestPlayerValue + 1e-15) {
            bestPlayerValue = playerValue;
            bestUtilityP0 = utilityP0;
            bestMask = mask;
        }
    }
    return {
        responder,
        player_value: bestPlayerValue,
        utility_p0: bestUtilityP0,
        pure_strategy_mask: bestMask,
        information_set_count: keys.length,
    };
};

export const measurePolicy = policy => {
    const onPolicyP0 = evaluatePolicy(policy);
    const response0 = exactBestResponse(policy, 0);
    const response1 = exactBestResponse(policy, 1);
    const nashConv = response0.player_value + response1.player_value;
    return {
        on_policy_value_p0: onPolicyP0,
        best_response_value_p0: response0.player_value,
        best_response_value_p1: response1.player_value,
        unilateral_improvement_p0: response0.player_value - onPolicyP0,
        unilateral_improvement_p1: response1.player_value + onPolicyP0,
        nash_conv: nashConv,
        exploitability: nashConv / 2,
    };
};

const compactMetrics = metrics => Object.fromEntries(Object.entries(metrics)
    .map(([key, value]) => [key, Number(value.toFixed(15))]));

const strategyRows = (policy, label) => allKeys.map(key => {
    const [, card, historyLabel] = key.split('|');
    const history = historyLabel === 'root' ? '' : historyLabel;
    const actions = ACTIONS_BY_HISTORY[history];
    return {
        profile: label,
        information_set: key,
        acting_player: Number(key[1]),
        private_card: card,
        public_history: historyLabel,
        action_0: actions[0],
        probability_0: Number(policy[key][0].toFixed(15)),
        action_1: actions[1],
        probability_1: Number(policy[key][1].toFixed(15)),
    };
});

export const runExperiment = (maximumIterations = 100_000) => {
    const tables = createTables();
    const checkpoints = [];
    const trace = [];
    const checkpointSet = new Set(CHECKPOINTS.filter(value => value <= maximumIterations));

    for (let iteration = 1; iteration <= maximumIterations; iteration += 1) {
        const policy = currentPolicy(tables);
        const regretDeltas = emptyDeltas();
        for (const cards of DEALS) {
            traverseForCfr({
                cards,
                history: '',
                reach0: 1,
                reach1: 1,
                policy,
                tables,
                regretDeltas,
            });
        }
        for (const key of allKeys) {
            for (let actionIndex = 0; actionIndex < 2; actionIndex += 1) {
                tables[key].cumulativeRegret[actionIndex] += regretDeltas[key][actionIndex];
            }
        }

        if (checkpointSet.has(iteration) || TRACE_ITERATIONS.has(iteration)) {
            const current = currentPolicy(tables);
            const average = averagePolicy(tables);
            const row = {
                iteration,
                average: compactMetrics(measurePolicy(average)),
                current: compactMetrics(measurePolicy(current)),
            };
            if (TRACE_ITERATIONS.has(iteration)) trace.push(row);
            if (checkpointSet.has(iteration)) checkpoints.push(row);
        }
    }

    const finalCurrent = currentPolicy(tables);
    const finalAverage = averagePolicy(tables);
    return {
        schema_version: 1,
        generated_utc: GENERATED_UTC,
        experiment: {
            name: 'Deterministic full-tree vanilla CFR on two-player Kuhn Poker',
            implementation: 'JavaScript ES module; no sampling and no random seed',
            iterations: maximumIterations,
            chance_deals: DEALS.map(cards => cards.join('')),
            chance_probability_each: 1 / DEALS.length,
            ranks_low_to_high: RANKS,
            ante_per_player: 1,
            bet_size: 1,
            utility_unit: 'net antes per deal',
            game_value_p0: GAME_VALUE_P0,
            averaging: 'reach-weighted behavioral average, accumulated from iteration 1',
            update_schedule: 'simultaneous regret update after all six ordered deals',
            current_strategy_timing: 'regret-matched policy after each completed update',
            nash_conv_definition: 'sum of both information-set-consistent unilateral best-response values in this zero-sum game',
            exploitability_definition: 'NashConv divided by two, matching OpenSpiel convention for two-player constant-sum games',
            best_response_method: 'exhaustive enumeration of 64 pure behavioral plans per responder; one action per information set',
        },
        checkpoints,
        trace,
        final_strategies: [
            ...strategyRows(finalAverage, 'reach_weighted_average'),
            ...strategyRows(finalCurrent, 'current'),
        ],
    };
};

const csvEscape = value => {
    const text = String(value);
    return /[",\n]/u.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
};

export const buildConvergenceCsv = experiment => {
    const header = [
        'iteration',
        'average_value_p0',
        'average_br_value_p0',
        'average_br_value_p1',
        'average_nash_conv',
        'average_exploitability',
        'current_value_p0',
        'current_br_value_p0',
        'current_br_value_p1',
        'current_nash_conv',
        'current_exploitability',
    ];
    const rows = experiment.trace.map(row => [
        row.iteration,
        row.average.on_policy_value_p0,
        row.average.best_response_value_p0,
        row.average.best_response_value_p1,
        row.average.nash_conv,
        row.average.exploitability,
        row.current.on_policy_value_p0,
        row.current.best_response_value_p0,
        row.current.best_response_value_p1,
        row.current.nash_conv,
        row.current.exploitability,
    ]);
    return `${[header, ...rows].map(row => row.map(csvEscape).join(',')).join('\n')}\n`;
};

export const buildStrategyCsv = experiment => {
    const header = Object.keys(experiment.final_strategies[0]);
    return `${[
        header,
        ...experiment.final_strategies.map(row => header.map(key => row[key])),
    ].map(row => row.map(csvEscape).join(',')).join('\n')}\n`;
};

const logPoint = (iteration, value, width, height, margins) => {
    const x = margins.left + (Math.log10(iteration) / 5) * (width - margins.left - margins.right);
    const bounded = Math.max(1e-4, Math.min(1, value));
    const y = margins.top + ((0 - Math.log10(bounded)) / 4)
        * (height - margins.top - margins.bottom);
    return [x, y];
};

export const buildSvg = (experiment, locale = 'en') => {
    const width = 960;
    const height = 560;
    const margins = { left: 82, right: 34, top: 92, bottom: 76 };
    const isJapanese = locale === 'ja';
    const title = isJapanese
        ? 'Kuhn Poker：平均戦略と現在戦略のExploitability'
        : 'Kuhn Poker: average vs current-strategy exploitability';
    const description = isJapanese
        ? '決定論的CFRを10万反復。横軸は反復回数、縦軸はOpenSpiel方式のExploitabilityで、両方とも対数目盛。'
        : 'Deterministic CFR for 100,000 iterations. Both iteration and OpenSpiel-style exploitability use logarithmic axes.';
    const averageLabel = isJapanese ? '到達確率で重み付けした平均戦略' : 'Reach-weighted average strategy';
    const currentLabel = isJapanese ? 'その反復後の現在戦略' : 'Current strategy after that update';
    const xLabel = isJapanese ? 'CFR反復回数（対数）' : 'CFR iterations (log scale)';
    const yLabel = isJapanese ? 'Exploitability（アンティ／ハンド、対数）' : 'Exploitability (antes/hand, log scale)';
    const averagePoints = experiment.trace
        .map(row => logPoint(row.iteration, row.average.exploitability, width, height, margins).join(','))
        .join(' ');
    const currentPoints = experiment.trace
        .map(row => logPoint(row.iteration, row.current.exploitability, width, height, margins).join(','))
        .join(' ');
    const xTicks = [1, 10, 100, 1_000, 10_000, 100_000];
    const yTicks = [1, 0.1, 0.01, 0.001, 0.0001];
    const plotWidth = width - margins.left - margins.right;
    const plotHeight = height - margins.top - margins.bottom;
    return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="title desc">
  <title id="title">${title}</title>
  <desc id="desc">${description}</desc>
  <rect width="960" height="560" rx="28" fill="#081711"/>
  <text x="48" y="48" fill="#f4f7f5" font-family="system-ui,sans-serif" font-size="25" font-weight="700">${title}</text>
  <text x="48" y="75" fill="#a9bbb2" font-family="system-ui,sans-serif" font-size="14">${isJapanese ? '完全木・サンプリングなし・厳密ベストレスポンス' : 'Full tree · no sampling · exact best responses'}</text>
  <rect x="${margins.left}" y="${margins.top}" width="${plotWidth}" height="${plotHeight}" fill="#0d2118" stroke="#2c493b"/>
  ${yTicks.map(value => {
        const [, y] = logPoint(1, value, width, height, margins);
        return `<line x1="${margins.left}" y1="${y}" x2="${width - margins.right}" y2="${y}" stroke="#284338" stroke-dasharray="4 7"/><text x="${margins.left - 12}" y="${y + 5}" text-anchor="end" fill="#9db0a6" font-family="system-ui,sans-serif" font-size="13">${value}</text>`;
    }).join('\n  ')}
  ${xTicks.map(value => {
        const [x] = logPoint(value, 1, width, height, margins);
        return `<line x1="${x}" y1="${margins.top}" x2="${x}" y2="${height - margins.bottom}" stroke="#203a30"/><text x="${x}" y="${height - margins.bottom + 25}" text-anchor="middle" fill="#9db0a6" font-family="system-ui,sans-serif" font-size="13">${value.toLocaleString('en-US')}</text>`;
    }).join('\n  ')}
  <polyline points="${currentPoints}" fill="none" stroke="#b887f7" stroke-width="2" stroke-linejoin="round" opacity="0.78"/>
  <polyline points="${averagePoints}" fill="none" stroke="#b9ec69" stroke-width="4" stroke-linejoin="round"/>
  <rect x="540" y="98" width="386" height="58" rx="12" fill="#081711" fill-opacity="0.94" stroke="#355646"/>
  <line x1="556" y1="114" x2="592" y2="114" stroke="#b9ec69" stroke-width="4"/><text x="600" y="119" fill="#eaf3ed" font-family="system-ui,sans-serif" font-size="14">${averageLabel}</text>
  <line x1="556" y1="140" x2="592" y2="140" stroke="#b887f7" stroke-width="3"/><text x="600" y="145" fill="#eaf3ed" font-family="system-ui,sans-serif" font-size="14">${currentLabel}</text>
  <text x="${margins.left + plotWidth / 2}" y="538" text-anchor="middle" fill="#dbe7e1" font-family="system-ui,sans-serif" font-size="15">${xLabel}</text>
  <text x="22" y="${margins.top + plotHeight / 2}" transform="rotate(-90 22 ${margins.top + plotHeight / 2})" text-anchor="middle" fill="#dbe7e1" font-family="system-ui,sans-serif" font-size="15">${yLabel}</text>
</svg>`;
};

export const buildGameTreeSvg = (locale = 'en') => {
    const ja = locale === 'ja';
    const labels = ja ? {
        title: 'Kuhn Pokerのベッティングツリー全体',
        subtitle: '各プレイヤーは自分のカードと公開アクションだけを見る',
        root: '両者が1アンティ\nP0が行動',
        check: 'チェック',
        bet: 'ベット（1アンティ）',
        p1: 'P1が行動',
        p0: 'P0が応答',
        fold: 'フォールド',
        call: 'コール',
        showdown1: 'ショーダウン\nP0収支 ±1',
        showdown2: 'ショーダウン\nP0収支 ±2',
        win: 'P0収支 +1',
        lose: 'P0収支 −1',
        note: '符号は先手P0から見た1ハンドの純収支',
    } : {
        title: 'The complete Kuhn Poker betting tree',
        subtitle: 'Each player sees only their own card and the public actions',
        root: 'Both ante 1\nP0 acts',
        check: 'Check',
        bet: 'Bet 1',
        p1: 'P1 acts',
        p0: 'P0 responds',
        fold: 'Fold',
        call: 'Call',
        showdown1: 'Showdown\nP0 payoff ±1',
        showdown2: 'Showdown\nP0 payoff ±2',
        win: 'P0 payoff +1',
        lose: 'P0 payoff −1',
        note: 'Signs are P0 net utility per hand',
    };
    const multiline = (value, x, y, fill = '#f2f7f4', size = 15, weight = 600) => (
        `<text x="${x}" y="${y}" text-anchor="middle" fill="${fill}" font-family="system-ui,sans-serif" font-size="${size}" font-weight="${weight}">${value.split('\n').map((line, index) => `<tspan x="${x}" dy="${index === 0 ? 0 : 19}">${line}</tspan>`).join('')}</text>`
    );
    const node = (x, y, width, height, value, accent = '#2b5140') => `
  <rect x="${x}" y="${y}" width="${width}" height="${height}" rx="14" fill="#10281e" stroke="${accent}" stroke-width="2"/>
  ${multiline(value, x + width / 2, y + (value.includes('\n') ? 25 : 31))}`;
    return `<svg xmlns="http://www.w3.org/2000/svg" width="960" height="520" viewBox="0 0 960 520" role="img" aria-labelledby="tree-title tree-desc">
  <title id="tree-title">${labels.title}</title>
  <desc id="tree-desc">${ja ? `${labels.subtitle}。${labels.note}。` : `${labels.subtitle}. ${labels.note}.`}</desc>
  <rect width="960" height="520" rx="28" fill="#081711"/>
  <text x="48" y="46" fill="#f4f7f5" font-family="system-ui,sans-serif" font-size="25" font-weight="700">${labels.title}</text>
  <text x="48" y="74" fill="#a9bbb2" font-family="system-ui,sans-serif" font-size="14">${labels.subtitle}</text>
  ${node(405, 100, 150, 62, labels.root, '#9dd95f')}
  <path d="M480 162 L290 214 M480 162 L670 214" stroke="#527365" stroke-width="2" fill="none"/>
  <text x="374" y="187" fill="#b9ec69" font-family="system-ui,sans-serif" font-size="14">${labels.check}</text>
  <text x="574" y="187" fill="#d9b6ff" font-family="system-ui,sans-serif" font-size="14">${labels.bet}</text>
  ${node(215, 214, 150, 60, labels.p1)}
  ${node(595, 214, 150, 60, labels.p1)}
  <path d="M290 274 L142 334 M290 274 L430 334 M670 274 L582 334 M670 274 L818 334" stroke="#527365" stroke-width="2" fill="none"/>
  <text x="203" y="305" fill="#b9ec69" font-family="system-ui,sans-serif" font-size="14">${labels.check}</text>
  <text x="356" y="305" fill="#d9b6ff" font-family="system-ui,sans-serif" font-size="14">${labels.bet}</text>
  <text x="607" y="306" fill="#d9b6ff" font-family="system-ui,sans-serif" font-size="14">${labels.fold}</text>
  <text x="750" y="305" fill="#b9ec69" font-family="system-ui,sans-serif" font-size="14">${labels.call}</text>
  ${node(67, 334, 150, 62, labels.showdown1)}
  ${node(355, 334, 150, 60, labels.p0)}
  ${node(507, 334, 150, 62, labels.win)}
  ${node(743, 334, 150, 62, labels.showdown2)}
  <path d="M430 394 L350 442 M430 394 L510 442" stroke="#527365" stroke-width="2" fill="none"/>
  <text x="365" y="426" fill="#d9b6ff" font-family="system-ui,sans-serif" font-size="14">${labels.fold}</text>
  <text x="477" y="426" fill="#b9ec69" font-family="system-ui,sans-serif" font-size="14">${labels.call}</text>
  ${node(275, 442, 150, 56, labels.lose)}
  ${node(435, 442, 150, 56, labels.showdown2)}
  <text x="920" y="486" text-anchor="end" fill="#9db0a6" font-family="system-ui,sans-serif" font-size="13">${labels.note}</text>
</svg>`;
};

export const sha256 = value => createHash('sha256').update(value).digest('hex');

export const buildArtifacts = experiment => ({
    'experiment.json': `${JSON.stringify(experiment, null, 2)}\n`,
    'convergence.csv': buildConvergenceCsv(experiment),
    'final-strategies.csv': buildStrategyCsv(experiment),
    'convergence.svg': buildSvg(experiment, 'en'),
    'convergence-ja.svg': buildSvg(experiment, 'ja'),
    'game-tree.svg': buildGameTreeSvg('en'),
    'game-tree-ja.svg': buildGameTreeSvg('ja'),
});

const isDirectRun = process.argv[1]
    && resolve(process.argv[1]) === fileURLToPath(import.meta.url);

if (isDirectRun) {
    mkdirSync(OUTPUT_DIRECTORY, { recursive: true });
    const experiment = runExperiment();
    const artifacts = buildArtifacts(experiment);
    for (const [name, value] of Object.entries(artifacts)) {
        writeFileSync(resolve(OUTPUT_DIRECTORY, name), value, 'utf8');
    }
    console.log(`Generated ${Object.keys(artifacts).length} Kuhn Poker artifacts at ${OUTPUT_DIRECTORY}`);
}
