// Proper scoring rules — ONE implementation shared by the offline backtest and
// the live Model-vs-Market scoreboard, so the numbers are always comparable.

import type { MatchProbs } from '../types';

export type Outcome3 = 'home' | 'draw' | 'away';

export const outcomeOfScore = (hs: number, as: number): Outcome3 =>
  hs > as ? 'home' : hs < as ? 'away' : 'draw';

/** Multiclass Brier (sum of squared errors over the 3 outcomes; 0 best, 2 worst). */
export function brierScore(p: MatchProbs, o: Outcome3): number {
  return (
    (p.home - (o === 'home' ? 1 : 0)) ** 2 +
    (p.draw - (o === 'draw' ? 1 : 0)) ** 2 +
    (p.away - (o === 'away' ? 1 : 0)) ** 2
  );
}

/** Ranked Probability Score for the ordered outcomes home > draw > away (0 best). */
export function rpsScore(p: MatchProbs, o: Outcome3): number {
  const y1 = o === 'home' ? 1 : 0;
  const y2 = o === 'away' ? 0 : 1; // cumulative: home+draw
  return ((p.home - y1) ** 2 + (p.home + p.draw - y2) ** 2) / 2;
}

export function logLoss(p: MatchProbs, o: Outcome3): number {
  return -Math.log(Math.max(1e-12, p[o]));
}
