/**
 * Wikipedia Pageviews Fetcher
 * -----------------------------
 * Retrieves rolling 90-day pageview counts from the Wikimedia REST API.
 * Public API, no key required.
 *
 * Internal module -- vendor names permitted in code; forbidden in user-facing output.
 */

const TIMEOUT_MS = 5_000;

export interface PageviewResult {
  totalPageviews90d: number;
  avgDailyPageviews: number;
}

function yyyymmdd(date: Date): string {
  return date.toISOString().slice(0, 10).replace(/-/g, "");
}

export async function getWikipediaPageviews(
  pageTitle: string,
): Promise<PageviewResult | null> {
  const end = new Date();
  end.setDate(end.getDate() - 1); // Wikimedia lags by 1 day
  const start = new Date(end);
  start.setDate(start.getDate() - 89); // 90-day window

  const encodedTitle = encodeURIComponent(pageTitle.replace(/ /g, "_"));
  const url = `https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/${encodedTitle}/daily/${yyyymmdd(start)}/${yyyymmdd(end)}`;

  try {
    const res = await Promise.race([
      fetch(url, { headers: { "User-Agent": "meSEO-Audit-Bot/1.0 (https://meseoapp.com)" } }),
      new Promise<Response>((_, reject) => setTimeout(() => reject(new Error("timeout")), TIMEOUT_MS)),
    ]);
    if (!res.ok) return null;
    const data = await res.json() as { items?: Array<{ views: number }> };
    const items = data?.items ?? [];
    const totalPageviews90d = items.reduce((sum, item) => sum + (item.views ?? 0), 0);
    return {
      totalPageviews90d,
      avgDailyPageviews: Math.round(totalPageviews90d / 90),
    };
  } catch {
    return null;
  }
}
