// YouTube Data API v3 — vollständig über einen API-Key (kein OAuth nötig).
// Liefert Abonnenten, Aufrufe, Videoanzahl + Kanalbild.
import type { FetchResult, Provider } from "./types";
import { fetchJson } from "./types";

const KEY = process.env.YOUTUBE_API_KEY;

function resolve(handle: string | null, url: string | null): { id?: string; forHandle?: string; forUsername?: string } | null {
  if (url) {
    const ch = url.match(/youtube\.com\/channel\/(UC[\w-]+)/i);
    if (ch) return { id: ch[1] };
    const at = url.match(/youtube\.com\/@([^/?#]+)/i);
    if (at) return { forHandle: `@${at[1]}` };
    const cu = url.match(/youtube\.com\/(?:user|c)\/([^/?#]+)/i);
    if (cu) return { forUsername: cu[1] };
  }
  if (handle) {
    const h = handle.replace(/^@/, "").trim();
    if (/^UC[\w-]{20,}$/.test(h)) return { id: h };
    if (h) return { forHandle: `@${h}` };
  }
  return null;
}

export const youtubeProvider: Provider = {
  key: "youtube",
  label: "YouTube",
  configured: () => Boolean(KEY),
  async fetchStats({ handle, url }): Promise<FetchResult> {
    if (!KEY) return { ok: false, reason: "YouTube-API-Key fehlt" };
    const q = resolve(handle, url);
    if (!q) return { ok: false, reason: "Kein YouTube-Handle" };
    const param = q.id ? `id=${q.id}` : q.forHandle ? `forHandle=${encodeURIComponent(q.forHandle)}` : `forUsername=${encodeURIComponent(q.forUsername!)}`;
    const res = await fetchJson(`https://www.googleapis.com/youtube/v3/channels?part=snippet,statistics&${param}&key=${KEY}`);
    if (!res || res.status !== 200) return { ok: false, reason: "YouTube-API nicht erreichbar" };
    const item = (res.json as { items?: { snippet: { title: string; thumbnails?: { high?: { url: string }; default?: { url: string } } }; statistics: { subscriberCount?: string; viewCount?: string; videoCount?: string } }[] }).items?.[0];
    if (!item) return { ok: false, reason: "Kanal nicht gefunden" };

    const s = item.statistics;
    const subs = Number(s.subscriberCount ?? 0);
    const views = Number(s.viewCount ?? 0);
    const videos = Number(s.videoCount ?? 0);
    const metrics: Record<string, number> = {};
    if (views) metrics.views = views;
    if (videos) metrics.videos = videos;
    if (videos > 0 && views > 0) metrics.avgViews = Math.round(views / videos);

    return {
      ok: true,
      source: "YouTube API",
      data: {
        followers: subs,
        displayName: item.snippet.title,
        avatarUrl: item.snippet.thumbnails?.high?.url ?? item.snippet.thumbnails?.default?.url,
        metrics,
      },
    };
  },
};
