// FotMob (unofficial, www.fotmob.com/api/data) — as of June 2026 it serves
// full match details from the VPS with no signed header: per-shot xG/xGOT
// with pitch coordinates, team xG splits, player ratings, player of the
// match, momentum, attacking zones, lineups. Unofficial means it can lock
// again any day — so capture early, store generously, degrade gracefully.
import { cachedFetch } from './fetcher';
import { canonicalTeam } from '../../../src/lib/teams';

const BASE = 'https://www.fotmob.com/api/data';
const SOURCE = 'fotmob';
const WC_LEAGUE_ID = 77;

export interface FotmobMatchRef {
  matchId: string;
  home: string;
  away: string;
  utcTime: string;
}

interface RawMatches {
  leagues?: {
    primaryId?: number;
    matches?: {
      id?: number | string;
      home?: { name?: string };
      away?: { name?: string };
      status?: { utcTime?: string };
    }[];
  }[];
}

/** World Cup matches on a given UTC date (id map source). */
export async function fetchFotmobMatches(dateYYYYMMDD: string): Promise<FotmobMatchRef[]> {
  const raw = await cachedFetch<RawMatches>(SOURCE, `fotmob:matches:${dateYYYYMMDD}`, `${BASE}/matches?date=${dateYYYYMMDD}`, {
    ttl: 10 * 60_000,
    minInterval: 2_500,
  });
  const out: FotmobMatchRef[] = [];
  for (const lg of raw.leagues ?? []) {
    if (lg.primaryId !== WC_LEAGUE_ID) continue;
    for (const m of lg.matches ?? []) {
      if (!m.id || !m.home?.name || !m.away?.name) continue;
      out.push({
        matchId: String(m.id),
        home: canonicalTeam(m.home.name),
        away: canonicalTeam(m.away.name),
        utcTime: m.status?.utcTime ?? '',
      });
    }
  }
  return out;
}

/** Trimmed matchDetails: everything analytic, minus the bulky redundant tabs
 *  (liveticker/buzz/h2h/table/seo) we already cover via other sources. */
export interface FotmobDetails {
  v: 2;
  fetchedAt: number;
  matchId: string;
  finished: boolean;
  homeTeamId: number | null;
  awayTeamId: number | null;
  shots: unknown[];
  stats: unknown;
  matchFacts: unknown;
  lineup: unknown;
  momentum: unknown;
  attackingZones: unknown;
  weather: unknown;
}

interface RawDetails {
  general?: {
    matchId?: string;
    finished?: boolean;
    homeTeam?: { id?: number };
    awayTeam?: { id?: number };
  };
  content?: {
    shotmap?: { shots?: unknown[] };
    stats?: unknown;
    matchFacts?: Record<string, unknown>;
    lineup?: unknown;
    momentum?: unknown;
    attackingZones?: unknown;
    weather?: unknown;
  };
}

export async function fetchFotmobDetails(matchId: string, live = false): Promise<FotmobDetails> {
  const raw = await cachedFetch<RawDetails>(SOURCE, `fotmob:details:${matchId}`, `${BASE}/matchDetails?matchId=${matchId}`, {
    ttl: live ? 60_000 : 60 * 60_000,
    minInterval: 2_500,
  });
  const c = raw.content ?? {};
  const mf = { ...(c.matchFacts ?? {}) } as Record<string, unknown>;
  delete mf.QAData; // SEO filler
  delete mf.postReview;
  delete mf.preReview;
  delete mf.poll;
  return {
    v: 2,
    fetchedAt: Date.now(),
    matchId: raw.general?.matchId ?? matchId,
    finished: raw.general?.finished ?? false,
    homeTeamId: raw.general?.homeTeam?.id ?? null,
    awayTeamId: raw.general?.awayTeam?.id ?? null,
    shots: c.shotmap?.shots ?? [],
    stats: c.stats ?? null,
    matchFacts: mf,
    lineup: c.lineup ?? null,
    momentum: c.momentum ?? null,
    attackingZones: c.attackingZones ?? null,
    weather: c.weather ?? null,
  };
}
