export interface TournamentClock {
  limit: number;
  increment: number;
}

export interface TournamentVariant {
  key: string;
  name: string;
}

export interface TournamentBotRef {
  id: string;
  name: string;
}

export interface TournamentResult {
  rank: number;
  points: number;
  tieBreak: number;
  bot: TournamentBotRef;
  nbGames: number;
  wins: number;
  draws: number;
  losses: number;
}

export interface TournamentStanding {
  page: number;
  players: TournamentResult[];
}

export interface Tournament {
  id: string;
  fullName: string;
  clock: TournamentClock;
  variant: TournamentVariant;
  rated: boolean;
  nbPlayers: number;
  nbRounds: number;
  createdBy: string;
  startsAt: string | null;
  status: 'created' | 'started' | 'finished';
  round: number;
  standing: TournamentStanding;
  winner: TournamentBotRef | null;
}

export interface TournamentList {
  created: Tournament[];
  started: Tournament[];
  finished: Tournament[];
}

export interface TournamentMatch {
  gameId: string;
  whiteId: string;
  winner?: 'white' | 'black' | 'draw' | null;
  status?: GameStatus;
}

export interface TournamentPairing {
  id?: string;
  round?: number;
  white: TournamentBotRef | null;
  black: TournamentBotRef;
  matches: TournamentMatch[];
  winner?: 'white' | 'black' | 'draw' | null;
}

export interface RoundPairings {
  round: number;
  pairings: TournamentPairing[];
}

export type TournamentStreamEvent =
  | { type: 'tournamentStarted' }
  | { type: 'roundStarted'; round: number }
  | { type: 'gameStart'; round: number; gameId: string; color: 'white' | 'black' }
  | { type: 'roundFinished'; round: number }
  | { type: 'tournamentFinished'; winner: TournamentBotRef | null }
  | { type: 'heartbeat' };

export interface GameClock {
  whiteTime: number;
  blackTime: number;
  increment: number;
}

export type GameStatus = 'pending' | 'ongoing' | 'checkmate' | 'stalemate' | 'draw' | 'resigned' | 'timeout';

export interface GameStateSnapshot {
  id?: string;
  tournamentId?: string;
  round?: number;
  white?: TournamentBotRef;
  black?: TournamentBotRef;
  moves: string;
  fen: string;
  status: GameStatus;
  turn: 'white' | 'black';
  winner: 'white' | 'black' | null;
  clock?: GameClock;
  startPosition?: string;
}

export type GameStreamEvent =
  | ({ type: 'gameState' } & GameStateSnapshot)
  | { type: 'move'; uci: string; fen: string; turn: 'white' | 'black'; clock?: GameClock }
  | { type: 'gameEnd'; winner: 'white' | 'black' | null; status: GameStatus }
  | { type: 'heartbeat' };
