import { createServerFn } from "@tanstack/react-start";

const source = "https://www.moviemeter.nl/toplijst/film/1/top-250-beste-films-aller-tijden";

type Entry = { rank: number; title: string };

function parse(text: string): Entry[] {
  return Array.from(
    text.matchAll(/\[(\d{1,3})\]\(https:\/\/www\.moviemeter\.nl\/film\/\d+\)\[!\[Image \d+: ([^\]]+)\]/g),
    ([, rank, title]) => ({ rank: Number(rank), title: title ?? "" }),
  );
}

// MovieMeter sits behind a bot check; the text proxy with a real browser engine gets past it.
// Attempts escalate from the fast (cached) read to a fresh browser render.
const attempts: Record<string, string>[] = [
  {},
  { "X-Engine": "browser", "X-Timeout": "20" },
  { "X-Engine": "browser", "X-Timeout": "30", "X-No-Cache": "true" },
];

export const getMovieMeterTop250 = createServerFn({ method: "GET" }).handler(async () => {
  for (const extra of attempts) {
    try {
      const response = await fetch(`https://r.jina.ai/${source}`, {
        headers: { Accept: "text/plain", "X-Return-Format": "markdown", ...extra },
        signal: AbortSignal.timeout(40000),
      });
      if (!response.ok) continue;
      const entries = parse(await response.text());
      if (entries.length >= 200) return { entries, source };
    } catch {
      // try the next, more robust attempt
    }
  }
  throw new Error("MovieMeter is momenteel niet bereikbaar.");
});
