import { cachedFetch } from './fetcher';

// ESPN's core API exposes real bookmaker odds (DraftKings et al.) per event —
// free and reachable from the VPS. Captured into odds_history as the public
// BENCHMARK for the Model-vs-Market scoreboard. Never fed into the model.
const CORE = 'https://sports.core.api.espn.com/v2/sports/soccer/leagues/fifa.world';
const SOURCE = 'espn-odds';

interface RawOddsItem {
  /** The core API sometimes returns pointer items instead of inline objects. */
  $ref?: string;
  provider?: { name?: string };
  overUnder?: number;
  spread?: number;
  homeTeamOdds?: { moneyLine?: number };
  awayTeamOdds?: { moneyLine?: number };
  drawOdds?: { moneyLine?: number };
}

export interface CapturedOdds {
  provider: string;
  homeMl: number | null;
  drawMl: number | null;
  awayMl: number | null;
  overUnder: number | null;
  spread: number | null;
}

export async function fetchEspnOdds(eventId: string): Promise<CapturedOdds[]> {
  const body = await cachedFetch<{ items?: RawOddsItem[] }>(
    SOURCE,
    `espn:odds:${eventId}`,
    `${CORE}/events/${eventId}/competitions/${eventId}/odds`,
    { ttl: 30 * 60_000, minInterval: 1_500 },
  );
  const out: CapturedOdds[] = [];
  for (let it of body.items ?? []) {
    // Pointer item → dereference (force https; ESPN refs come back as http).
    if (it.$ref && !it.provider) {
      const url = it.$ref.replace(/^http:/, 'https:');
      try {
        it = await cachedFetch<RawOddsItem>(SOURCE, `espn:oddsref:${eventId}:${url.slice(-40)}`, url, {
          ttl: 30 * 60_000,
          minInterval: 1_500,
        });
      } catch {
        continue;
      }
    }
    out.push({
      provider: it.provider?.name ?? 'unknown',
      homeMl: it.homeTeamOdds?.moneyLine ?? null,
      drawMl: it.drawOdds?.moneyLine ?? null,
      awayMl: it.awayTeamOdds?.moneyLine ?? null,
      overUnder: it.overUnder ?? null,
      spread: it.spread ?? null,
    });
  }
  return out;
}
