import { cardRank, isHandshake } from "./cards";
import { cardsOnBoard } from "./engine";
import { N_COLORS, type GameState } from "./types";

export interface ColorScore {
  color: number;
  cards: number;
  handshakes: number;
  rankSum: number;
  score: number;
}

export interface PlayerScore {
  colors: ColorScore[];
  total: number;
}

/** Per-color scoring, mirroring `score_breakdown` in
 *  `src/lost_cities_jax/human_play.py`: an opened expedition costs 20, is
 *  multiplied by 1 + handshakes, and earns 20 more at eight cards. */
export function scoreBreakdown(state: GameState, player: number): PlayerScore {
  const colors: ColorScore[] = [];
  let total = 0;
  for (let color = 0; color < N_COLORS; color += 1) {
    const cards = cardsOnBoard(state, player, color);
    const handshakes = cards.filter(isHandshake).length;
    const rankSum = cards.reduce((sum, card) => sum + cardRank(card), 0);
    const score = cards.length === 0
      ? 0
      : (rankSum - 20) * (1 + handshakes) + (cards.length >= 8 ? 20 : 0);
    total += score;
    colors.push({ color, cards: cards.length, handshakes, rankSum, score });
  }
  return { colors, total };
}
