import type { Chess } from 'chess.js'; import { gameResult, verifyPgnExtends } from '$lib/game-logic'; import type { GameResult, ResultReason } from '$lib/types'; /** * Verify an opponent's claimed result against the game we actually have. * Returns null when the claim cannot be trusted, in which case the caller must * not write it: believing one persists a result into our own repo. */ export function verifyOpponentResult( opponentRecord: Record, opponentColor: 'white' | 'black', current: Chess ): { result: GameResult; resultReason: ResultReason } | null { const pgn = opponentRecord.pgn as string | undefined; if (pgn) { // A fabricated game that does not continue ours proves nothing. const verified = verifyPgnExtends(current, pgn); if (!verified.ok) return null; const outcome = gameResult(verified.chess); if (outcome) return { result: outcome.result, resultReason: outcome.reason }; } // Resignation leaves no trace on the board, so it is only credible when the // opponent is the one giving up. const reason = opponentRecord.resultReason as ResultReason | undefined; const result = opponentRecord.result as GameResult | undefined; if (reason === 'resignation' && result) { const opponentLost = (opponentColor === 'white' && result === '0-1') || (opponentColor === 'black' && result === '1-0'); if (opponentLost) return { result, resultReason: reason }; } return null; }