// Full game analyzer — analyzes every move and produces classifications + accuracy
import { classifyMove, calculateAccuracy, getMoveClassSummary } from './classifier.js';

export async function analyzeGame(moves, fetchAnalysis) {
  const results = [];
  const chess = new Chess();
  let prevEval = 0;

  for (let i = 0; i < moves.length; i++) {
    const fen = chess.fen();
    const isWhite = chess.turn() === 'w';
    const move = moves[i];

    // Apply the move
    chess.move({ from: move.from, to: move.to, promotion: move.promotion });
    const fenAfter = chess.fen();

    // Request engine analysis for the position BEFORE the move
    let analysis = null;
    try {
      analysis = await fetchAnalysis(fen, 15, 1);
    } catch (e) {}

    const bestEval = analysis?.lines?.[0]?.evaluation ?? prevEval;
    const bestMove = analysis?.lines?.[0]?.move ?? null;

    // Request eval of the position AFTER the move
    let evalAfter = prevEval;
    try {
      const postAnalysis = await fetchAnalysis(fenAfter, 12, 1);
      evalAfter = postAnalysis?.lines?.[0]?.evaluation ?? prevEval;
      // Flip sign because it's now from the other player's perspective
      evalAfter = -evalAfter;
    } catch (e) {}

    const moveNum = Math.floor(i / 2) + 1;
    const classification = classifyMove(prevEval, evalAfter, bestEval, isWhite, moveNum);

    results.push({
      moveIndex: i,
      san: move.san,
      from: move.from,
      to: move.to,
      fen: fen,
      fenAfter: fenAfter,
      evalBefore: prevEval,
      evalAfter: evalAfter,
      bestMove: bestMove,
      bestEval: bestEval,
      classification: classification,
      isPlayerMove: isWhite // adjust based on player color
    });

    prevEval = evalAfter;
  }

  const accuracy = calculateAccuracy(results.map(r => r.classification));
  const summary = getMoveClassSummary(results.map(r => r.classification));

  return { moves: results, accuracy, summary };
}

export function getMoveDiff(moveResult) {
  if (!moveResult) return null;
  const diff = Math.abs(moveResult.evalAfter - moveResult.bestEval);
  return {
    played: moveResult.san,
    best: moveResult.bestMove,
    evalPlayed: moveResult.evalAfter,
    evalBest: moveResult.bestEval,
    loss: diff,
    classification: moveResult.classification
  };
}
