// Match system — first-to-N points, Crawford rule
import { WHITE, BLACK, createGame, getGameScore } from './rules.js';
import { createCube } from './doubling.js';

export function createMatch(matchLength = 5, variant = 'sheshbesh') {
  return {
    length: matchLength,
    variant,
    scores: [0, 0], // [WHITE, BLACK]
    gameNumber: 0,
    currentGame: null,
    cube: null,
    crawford: false,
    crawfordUsed: false,
    isOver: false,
    winner: null,
    postCrawford: false
  };
}

export function startNewGame(match) {
  match.gameNumber++;
  match.currentGame = createGame(match.variant);

  // Crawford rule: no doubling in the game immediately after someone reaches match-point - 1
  const atMatchPoint = match.scores[WHITE] === match.length - 1 || match.scores[BLACK] === match.length - 1;
  if (atMatchPoint && !match.crawfordUsed) {
    match.crawford = true;
    match.crawfordUsed = true;
    match.cube = null;
  } else {
    match.crawford = false;
    if (match.crawfordUsed) match.postCrawford = true;
    match.cube = createCube();
  }

  // Alternate who goes first each game (simplified — real backgammon uses highest die)
  if (match.gameNumber > 1) {
    match.currentGame.turn = match.gameNumber % 2 === 0 ? BLACK : WHITE;
  }

  return match.currentGame;
}

export function endGame(match, winner, gameScore) {
  const stake = match.cube ? match.cube.value * gameScore : gameScore;
  match.scores[winner] += stake;

  if (match.scores[winner] >= match.length) {
    match.isOver = true;
    match.winner = winner;
  }

  return {
    winner,
    gameScore,
    stake,
    scores: [...match.scores],
    matchOver: match.isOver
  };
}

export function canUseCube(match) {
  return !match.crawford && match.cube !== null;
}

export function getMatchState(match) {
  return {
    length: match.length,
    scores: [...match.scores],
    gameNumber: match.gameNumber,
    crawford: match.crawford,
    isOver: match.isOver,
    winner: match.winner
  };
}
