import type { SimulationProbabilities, SimulationResult } from "./types";

export const SIMULATION_PROBABILITY_KEYS = [
  "probFirst",
  "probSecond",
  "probThird",
  "probFourth",
  "probFifth",
  "probSixth",
  "probSeventh",
  "probEighth",
] as const satisfies ReadonlyArray<keyof SimulationProbabilities>;

/**
 * Normalize each placement-probability column so every finishing position sums
 * to exactly 1.0 across all participants after Monte Carlo floating-point math.
 */
export function normalizeSimulationResultColumns(results: SimulationResult[]): void {
  if (results.length === 0) return;

  for (const key of SIMULATION_PROBABILITY_KEYS) {
    const colSum = results.reduce((sum, result) => sum + result.probabilities[key], 0);
    const residual = 1.0 - colSum;
    if (residual !== 0) {
      const maxResult = results.reduce((best, result) =>
        result.probabilities[key] > best.probabilities[key] ? result : best
      );
      maxResult.probabilities[key] += residual;
    }
  }
}
