import type { SourceMeta } from "./types";

function extractVideoId(url: string): string | null {
  try {
    const u = new URL(url);
    if (u.hostname.includes("youtu.be")) {
      return u.pathname.split("/").filter(Boolean)[0] ?? null;
    }
    if (u.searchParams.has("v")) return u.searchParams.get("v");
    const shortsMatch = u.pathname.match(/\/shorts\/([^/?]+)/);
    if (shortsMatch) return shortsMatch[1];
    return null;
  } catch {
    return null;
  }
}

// Uses the official YouTube Data API v3 (public read of a video's
// title/description/tags) — no video/audio download involved.
export async function fetchYouTubeMetadata(url: string): Promise<SourceMeta> {
  const apiKey = process.env.YOUTUBE_API_KEY;
  if (!apiKey) {
    throw new Error("YOUTUBE_API_KEY is not set — add it to .env to fetch real video metadata.");
  }

  const videoId = extractVideoId(url);
  if (!videoId) {
    throw new Error(`Could not extract a video ID from URL: ${url}`);
  }

  const apiUrl = new URL("https://www.googleapis.com/youtube/v3/videos");
  apiUrl.searchParams.set("part", "snippet");
  apiUrl.searchParams.set("id", videoId);
  apiUrl.searchParams.set("key", apiKey);

  const res = await fetch(apiUrl.toString());
  if (!res.ok) {
    throw new Error(`YouTube Data API request failed: ${res.status} ${res.statusText}`);
  }

  const data = await res.json();
  const snippet = data.items?.[0]?.snippet;
  if (!snippet) {
    throw new Error("Video not found or is private/unavailable.");
  }

  return {
    title: snippet.title,
    description: snippet.description,
    tags: snippet.tags ?? [],
  };
}
