// MovieMeter blocks direct requests; read pages via a text proxy and find films via DuckDuckGo.
async function readText(url: string) {
  const res = await fetch(`https://r.jina.ai/${url}`, {
    headers: { Accept: "text/plain", "X-Return-Format": "markdown" },
    signal: AbortSignal.timeout(20000),
  });
  if (!res.ok) throw new Error("MovieMeter is momenteel niet bereikbaar.");
  return res.text();
}

async function findFilmId(titel: string, jaar: number | null) {
  const q = encodeURIComponent(`site:moviemeter.nl/film ${titel} ${jaar ?? ""}`.trim());
  const text = await readText(`https://html.duckduckgo.com/html/?q=${q}`);
  const decoded = decodeURIComponent(text);
  const m = decoded.match(/moviemeter\.nl\/film\/(\d+)/);
  return m?.[1] ?? null;
}

export async function fetchMovieMeterActors(titel: string, jaar: number | null): Promise<string[]> {
  const id = await findFilmId(titel, jaar);
  if (!id) return [];
  const text = await readText(`https://www.moviemeter.nl/film/${id}/cast`);
  const start = text.indexOf("## Acteurs & actrices");
  if (start < 0) return [];
  const rest = text.slice(start + 21);
  const end = rest.search(/\n## /);
  const section = end < 0 ? rest : rest.slice(0, end);
  const names = Array.from(section.matchAll(/####\s+(.+?)\s+_[^_]*_\]\(https:\/\/www\.moviemeter\.nl\/personen\//g), (m) => (m[1] ?? "").trim()).filter(Boolean);
  return Array.from(new Set(names)).slice(0, 15);
}
