import type { LiveMatch } from './tournament';
import type { MatchStatus } from '../../src/lib/types';

// SofaScore unofficial API — near-real-time, but undocumented and fragile.
// Gated behind ENABLE_SOFASCORE; always wrapped in try/catch by the caller, with
// football-data.org as the fallback. We only read the global live-events feed and
// filter to the World Cup, so no scraping of internal IDs is needed.
const LIVE_URL = 'https://api.sofascore.com/api/v1/sport/football/events/live';

interface SsTeam { name: string }
interface SsScore { current?: number }
interface SsEvent {
  tournament?: { name?: string; uniqueTournament?: { name?: string }; category?: { name?: string } };
  homeTeam: SsTeam;
  awayTeam: SsTeam;
  homeScore: SsScore;
  awayScore: SsScore;
  status: { type: string };
  time?: { currentPeriodStartTimestamp?: number };
  roundInfo?: { name?: string };
}

function mapStatus(type: string): MatchStatus | null {
  if (type === 'inprogress') return 'live';
  if (type === 'finished') return 'finished';
  if (type === 'notstarted') return 'scheduled';
  return null;
}

function isWorldCup(e: SsEvent): boolean {
  const names = [
    e.tournament?.uniqueTournament?.name,
    e.tournament?.name,
  ].filter(Boolean).map((s) => s!.toLowerCase());
  return names.some((n) => n.includes('world cup')) && !names.some((n) => n.includes('qualif'));
}

export async function fetchSofascore(): Promise<LiveMatch[]> {
  const res = await fetch(LIVE_URL, {
    headers: { accept: 'application/json', 'user-agent': 'Mozilla/5.0 cup26' },
    signal: AbortSignal.timeout(10_000),
  });
  if (!res.ok) throw new Error(`sofascore ${res.status}`);
  const body = (await res.json()) as { events?: SsEvent[] };
  const out: LiveMatch[] = [];
  for (const e of body.events ?? []) {
    if (!isWorldCup(e)) continue;
    const status = mapStatus(e.status.type);
    if (!status) continue;
    out.push({
      home: e.homeTeam.name,
      away: e.awayTeam.name,
      group: null, // inferred by name-matching against the seed
      stage: 'group', // hint only; the matcher resolves by team pair
      kickoff: null,
      homeScore: e.homeScore.current ?? null,
      awayScore: e.awayScore.current ?? null,
      status,
      minute: null,
    });
  }
  return out;
}
