import { cachedFetch } from './fetcher';
import {
  normalizeScoreboard,
  normalizeSummary,
  type EspnEvent,
  type EspnMatch,
  type EspnSummary,
  type RawSummary,
} from './espnNormalize';

// ESPN's hidden site API — datacenter-friendly (works from the VPS where
// SofaScore 403s), no auth, covers the World Cup (`fifa.world`). The scoreboard
// drives live scores; the summary endpoint is a rich pre-match/live blob.
const BASE = 'https://site.api.espn.com/apis/site/v2/sports/soccer/fifa.world';
const SOURCE = 'espn';

export type { EspnMatch, EspnSummary } from './espnNormalize';

export async function fetchEspnScoreboard(dateYYYYMMDD?: string): Promise<EspnMatch[]> {
  const url = `${BASE}/scoreboard${dateYYYYMMDD ? `?dates=${dateYYYYMMDD}` : ''}`;
  const body = await cachedFetch<{ events?: EspnEvent[] }>(SOURCE, `espn:sb:${dateYYYYMMDD ?? 'now'}`, url, {
    ttl: 20_000,
    minInterval: 3_000,
  });
  return normalizeScoreboard(body);
}

export async function fetchEspnSummary(eventId: string): Promise<EspnSummary> {
  const raw = await cachedFetch<RawSummary>(SOURCE, `espn:summary:${eventId}`, `${BASE}/summary?event=${eventId}`, {
    ttl: 5 * 60_000,
    minInterval: 2_000,
  });
  return normalizeSummary(raw);
}
