// Twitch Helix. App-Access-Token (client_credentials) reicht für Profil, Live-
// Status und aktuelle Zuschauerzahl. Follower-Gesamtzahl ist bei Twitch seit
// 2023 nur mit User-Token des Kanals abrufbar → bleibt manuell/über Creator-OAuth.
import type { FetchResult, Provider } from "./types";
import { fetchJson } from "./types";

const CLIENT_ID = process.env.TWITCH_CLIENT_ID;
const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET;

let cachedToken: { value: string; exp: number } | null = null;

async function appToken(): Promise<string | null> {
  if (cachedToken && cachedToken.exp > Date.now() + 30_000) return cachedToken.value;
  if (!CLIENT_ID || !CLIENT_SECRET) return null;
  const res = await fetchJson(
    `https://id.twitch.tv/oauth2/token?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&grant_type=client_credentials`,
    { method: "POST" },
  );
  if (!res || res.status !== 200) return null;
  const j = res.json as { access_token?: string; expires_in?: number };
  if (!j.access_token) return null;
  cachedToken = { value: j.access_token, exp: Date.now() + (j.expires_in ?? 3600) * 1000 };
  return cachedToken.value;
}

function login(handle: string | null, url: string | null): string | null {
  if (url) {
    const m = url.match(/twitch\.tv\/([^/?#]+)/i);
    if (m) return m[1].toLowerCase();
  }
  if (handle) return handle.replace(/^@/, "").trim().toLowerCase();
  return null;
}

export const twitchProvider: Provider = {
  key: "twitch",
  label: "Twitch",
  configured: () => Boolean(CLIENT_ID && CLIENT_SECRET),
  async fetchStats({ handle, url }): Promise<FetchResult> {
    const name = login(handle, url);
    if (!name) return { ok: false, reason: "Kein Twitch-Handle" };
    const token = await appToken();
    if (!token) return { ok: false, reason: "Twitch-Zugangsdaten fehlen/ungültig" };
    const headers = { "Client-Id": CLIENT_ID!, Authorization: `Bearer ${token}` };

    const userRes = await fetchJson(`https://api.twitch.tv/helix/users?login=${encodeURIComponent(name)}`, { headers });
    if (!userRes || userRes.status !== 200) return { ok: false, reason: "Twitch-API nicht erreichbar" };
    const user = (userRes.json as { data?: { id: string; display_name: string; profile_image_url: string }[] }).data?.[0];
    if (!user) return { ok: false, reason: `Kanal „${name}" nicht gefunden` };

    const streamRes = await fetchJson(`https://api.twitch.tv/helix/streams?user_id=${user.id}`, { headers });
    const stream = (streamRes?.json as { data?: { viewer_count: number; game_name: string }[] } | undefined)?.data?.[0];

    const metrics: Record<string, number> = {};
    if (stream) metrics.liveViewers = stream.viewer_count;

    return {
      ok: true,
      source: "Twitch API",
      data: {
        avatarUrl: user.profile_image_url,
        displayName: user.display_name,
        liveStatus: Boolean(stream),
        metrics,
      },
    };
  },
};
