#!/usr/bin/env python3
"""youtube_rag.py: ask questions about a YouTube channel with LangChain, and get
answers that cite the exact moment in the video.

  pip install "langchain>=1.0" langchain-openai langchain-anthropic
  export YTT_API_KEY=tk_live_...        # https://youtubetranscriptapi.com/dashboard/keys
  export OPENAI_API_KEY=...             # embeddings (swap with --embeddings)
  export ANTHROPIC_API_KEY=...          # answers (swap with --model)

  python youtube_rag.py index --channel @3blue1brown --limit 30 --dry-run
  python youtube_rag.py index --channel @3blue1brown --limit 30
  python youtube_rag.py ask "How does backpropagation work?"

What it does:
  YouTubeTranscriptLoader  a LangChain BaseLoader (lazy_load) that fetches transcripts
                           through YouTubeTranscriptAPI, so it works from cloud servers.
                           One Document per time window (default 90 s, 15 s overlap),
                           with title, channel, start, end and a ?t= link in metadata.
  index                    load a channel, playlist or list of videos, embed, and save an
                           InMemoryVectorStore to a JSON file. Re-runs skip videos already
                           in the store, so you never pay twice for a transcript.
  ask                      retrieve the closest windows and answer with [title, m:ss](link)
                           citations. Links the model invents are flagged.
  search_youtube_tool      the same search as a @tool for create_agent().

Cost: 1 credit per transcript, 20 per channel or playlist listing (up to 100 videos).
Videos without captions, errors and 429s are free. Needs Python 3.10+.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Callable, Iterator

from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document

API = "https://youtubetranscriptapi.com/api/v2"
VIDEO_ID = re.compile(r"(?:[?&]v=|youtu\.be/|/shorts/|/embed/|/live/)([\w-]{11})")


class ApiError(Exception):
    def __init__(self, status: int, code: str = "", detail: str = "", retry_after: float = 0):
        super().__init__(f"HTTP {status} {code} {detail}".strip())
        self.status, self.code, self.retry_after = status, code, retry_after


def call(path: str, params: dict, key: str) -> dict:
    """GET one API endpoint. Raises ApiError with the status and Retry-After."""
    url = f"{API}{path}?{urllib.parse.urlencode(params)}"
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {key}", "User-Agent": "youtube-rag/1.0"})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:  # a new video can take 10-30 s
            return json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        try:
            body = json.loads(e.read().decode("utf-8"))
        except Exception:
            body = {}
        detail = body.get("detail")
        raise ApiError(e.code, body.get("code", ""), detail if isinstance(detail, str) else json.dumps(detail),
                       float(e.headers.get("Retry-After") or 0)) from None


def video_id(s: str) -> str | None:
    m = VIDEO_ID.search(s)
    if m:
        return m.group(1)
    return s if re.fullmatch(r"[\w-]{11}", s) else None


def mmss(seconds: float) -> str:
    s = int(seconds)
    return f"{s // 3600}:{s % 3600 // 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60}:{s % 60:02d}"


def windows(segments: list[dict], seconds: float = 90, overlap: float = 15) -> Iterator[tuple[float, float, str]]:
    """Group caption segments into time windows that never cut a segment.

    Each window starts on a segment boundary; the next one starts `overlap` seconds
    before the previous end, so an answer that spans a boundary is still found."""
    segs = [s for s in segments if str(s.get("text", "")).strip()]
    i = 0
    while i < len(segs):
        start = float(segs[i].get("start", 0))
        j = i
        while j < len(segs) and float(segs[j].get("start", 0)) < start + seconds:
            j += 1
        chunk = segs[i:j]
        last = chunk[-1]
        end = float(last.get("start", 0)) + float(last.get("duration", 0) or 0)
        yield start, end, " ".join(" ".join(str(s["text"]).split()) for s in chunk)
        if j >= len(segs):
            break
        nxt = j
        while nxt - 1 > i and float(segs[nxt - 1].get("start", 0)) >= end - overlap:
            nxt -= 1
        i = max(nxt, i + 1)


class YouTubeTranscriptLoader(BaseLoader):
    """LangChain document loader for YouTube transcripts via YouTubeTranscriptAPI.

    loader = YouTubeTranscriptLoader(channel="@3blue1brown", limit=20)
    for doc in loader.lazy_load(): ...

    Videos without captions are skipped (and free). A 402 (out of credits) or 401
    (bad key) stops the run with ApiError. 429/408/503 are retried after Retry-After.
    """

    def __init__(self, videos: list[str] | None = None, channel: str | None = None, playlist: str | None = None,
                 limit: int | None = None, language: str = "en", window_seconds: float = 90, overlap_seconds: float = 15,
                 skip: set[str] | None = None, api_key: str | None = None,
                 api: Callable[[str, dict, str], dict] = call, sleep: Callable[[float], None] = time.sleep,
                 log: Callable[[str], None] = lambda m: print(m, file=sys.stderr)):
        self.videos, self.channel, self.playlist, self.limit = videos or [], channel, playlist, limit
        self.language, self.window_seconds, self.overlap_seconds = language, window_seconds, overlap_seconds
        self.skip = skip or set()
        self.api_key = api_key or os.environ.get("YTT_API_KEY", "")
        self.api, self.sleep, self.log = api, sleep, log
        self.stats = {"listed": 0, "fetched": 0, "no_captions": 0, "skipped": 0, "credits": 0}

    def _get(self, path: str, params: dict) -> dict:
        for attempt in range(4):
            try:
                return self.api(path, params, self.api_key)
            except ApiError as e:
                if e.status in (408, 429, 503) and attempt < 3:
                    self.sleep(e.retry_after or 3 * (attempt + 1))
                    continue
                raise
        raise AssertionError("unreachable")

    def video_list(self) -> list[dict]:
        """Every video to load, in order, without duplicates: [{video_id, title, channel}]."""
        out, seen = [], set()

        def add(vid: str, title: str = "", channel: str = "") -> None:
            if vid and vid not in seen:
                seen.add(vid)
                out.append({"video_id": vid, "title": title, "channel": channel})

        for s in self.videos:
            vid = video_id(s.strip())
            if vid:
                add(vid)
            else:
                self.log(f"not a video link or ID, ignored: {s}")
        for kind, value in (("channel", self.channel), ("playlist", self.playlist)):
            if value:
                path = "/youtube/channel/videos" if kind == "channel" else "/youtube/playlist/videos"
                data = self._get(path, {kind: value})
                self.stats["credits"] += 20
                for v in data.get("results") or []:
                    add(v.get("videoId", ""), v.get("title") or "", v.get("channelTitle") or "")
        self.stats["listed"] = len(out)
        return out[: self.limit] if self.limit else out

    def lazy_load(self) -> Iterator[Document]:
        if not self.api_key:
            raise ApiError(401, "missing_auth", "set YTT_API_KEY or pass api_key=")
        for v in self.video_list():
            vid = v["video_id"]
            if vid in self.skip:
                self.stats["skipped"] += 1
                continue
            try:
                data = self._get("/youtube/transcript", {"video_url": vid, "language": self.language, "format": "json",
                                                         "include_timestamp": "true", "send_metadata": "true"})
            except ApiError as e:
                if e.status in (404, 422):
                    self.stats["no_captions"] += 1
                    self.log(f"{vid}: no captions, skipped (not charged)")
                    continue
                raise
            self.stats["fetched"] += 1
            self.stats["credits"] += 1
            meta = data.get("metadata") or {}
            title = meta.get("title") or v["title"] or vid
            channel = meta.get("author_name") or v["channel"]
            lang = data.get("language", "")
            if lang and lang != self.language:
                self.log(f"{vid}: asked for {self.language}, got {lang}")
            segs = data.get("transcript") or []
            if isinstance(segs, str):  # format=text fallback
                segs = [{"text": segs, "start": 0, "duration": 0}]
            for n, (start, end, text) in enumerate(windows(segs, self.window_seconds, self.overlap_seconds)):
                yield Document(
                    page_content=f"{title}\n{text}",  # the title helps retrieval
                    metadata={"video_id": vid, "title": title, "channel": channel, "language": lang,
                              "start": round(start, 2), "end": round(end, 2), "chunk": n,
                              "source": f"https://www.youtube.com/watch?v={vid}&t={int(start)}s"},
                    id=f"{vid}:{n}",
                )


# --------------------------------------------------------------------------- store + answers

def load_store(path: Path, embeddings):
    from langchain_core.vectorstores import InMemoryVectorStore
    return InMemoryVectorStore.load(str(path), embeddings) if path.exists() else InMemoryVectorStore(embeddings)


def indexed_videos(store) -> set[str]:
    return {d["metadata"].get("video_id") for d in getattr(store, "store", {}).values()}


def cite(doc: Document) -> str:
    m = doc.metadata
    return f"[{m['title']}, {mmss(m['start'])}]({m['source']})"


def format_context(docs: list[Document]) -> str:
    return "\n\n".join(f"SOURCE {cite(d)}\n{d.page_content.split(chr(10), 1)[-1]}" for d in docs)


SYSTEM = ("You answer questions using only the YouTube transcript excerpts provided. "
          "After each claim, cite the excerpt it came from by copying its SOURCE link exactly, "
          "in the form [title, m:ss](link). If the excerpts don't answer the question, say so "
          "plainly instead of guessing. Captions can mishear names and numbers; say when a "
          "detail looks garbled.")


def answer(question: str, store, model, k: int = 6) -> dict:
    docs = store.similarity_search(question, k=k)
    if not docs:
        return {"answer": "The index is empty. Run `index` first.", "sources": [], "unknown_links": []}
    reply = model.invoke([("system", SYSTEM), ("human", f"Excerpts:\n\n{format_context(docs)}\n\nQuestion: {question}")])
    text = reply.content if isinstance(reply.content, str) else "".join(
        p.get("text", "") for p in reply.content if isinstance(p, dict))
    allowed = {d.metadata["source"] for d in docs}
    links = re.findall(r"\]\((https?://[^)\s]+)\)", text)
    return {"answer": text, "sources": [d.metadata for d in docs],
            "unknown_links": [u for u in links if u not in allowed]}


def search_youtube_tool(store, k: int = 6):
    """The same retrieval as a LangChain tool, for create_agent(model, tools=[...])."""
    from langchain.tools import tool

    @tool(response_format="content_and_artifact")
    def search_youtube(query: str):
        """Search the indexed YouTube transcripts. Returns excerpts with [title, m:ss](link) sources."""
        docs = store.similarity_search(query, k=k)
        return format_context(docs) or "No matching excerpts.", docs

    return search_youtube


# --------------------------------------------------------------------------- CLI

def main(argv: list[str] | None = None, api: Callable = call, embeddings=None, model=None) -> int:
    p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    sub = p.add_subparsers(dest="cmd", required=True)
    ix = sub.add_parser("index", help="fetch transcripts and build the vector store")
    ix.add_argument("--channel"), ix.add_argument("--playlist")
    ix.add_argument("--videos", nargs="*", default=[], help="video links or IDs")
    ix.add_argument("--limit", type=int, help="newest N videos")
    ix.add_argument("--language", default="en")
    ix.add_argument("--window", type=float, default=90, help="seconds per chunk")
    ix.add_argument("--dry-run", action="store_true", help="list videos and cost, fetch nothing")
    ask = sub.add_parser("ask", help="answer a question with timestamp citations")
    ask.add_argument("question"), ask.add_argument("-k", type=int, default=6)
    ask.add_argument("--model", default="anthropic:claude-sonnet-5-5")
    for sp in (ix, ask):
        sp.add_argument("--store", default="youtube_index.json")
        sp.add_argument("--embeddings", default="openai:text-embedding-3-small")
    a = p.parse_args(argv)

    def get_embeddings():
        if embeddings is not None:
            return embeddings
        from langchain.embeddings import init_embeddings
        return init_embeddings(a.embeddings)

    path = Path(a.store)
    try:
        if a.cmd == "index":
            if not (a.channel or a.playlist or a.videos):
                p.error("give --channel, --playlist or --videos")
            store = None if a.dry_run else load_store(path, get_embeddings())
            loader = YouTubeTranscriptLoader(a.videos, a.channel, a.playlist, a.limit, a.language, a.window,
                                             skip=indexed_videos(store) if store else set(), api=api)
            if a.dry_run:
                vids = loader.video_list()
                print(f"{len(vids)} videos to load. Listing cost {loader.stats['credits']} credits; "
                      f"transcripts cost up to {len(vids)} more (videos without captions are free).")
                for v in vids[:10]:
                    print(f"  {v['video_id']}  {v['title'][:70]}")
                return 0
            batch, added = [], 0
            for doc in loader.lazy_load():
                batch.append(doc)
                if len(batch) >= 200:  # embed in batches; save so a crash keeps the work done
                    added += len(store.add_documents(batch)); store.dump(str(path)); batch = []
            if batch:
                added += len(store.add_documents(batch))
            store.dump(str(path))
            s = loader.stats
            print(f"Indexed {s['fetched']} videos ({added} chunks); {s['no_captions']} without captions; "
                  f"{s['skipped']} already in the store. Spent {s['credits']} credits. Saved {path}.")
            return 0
        if not path.exists():
            print(f"No index at {path}. Run `index` first.", file=sys.stderr)
            return 2
        store = load_store(path, get_embeddings())
        if model is None:
            from langchain.chat_models import init_chat_model
            model = init_chat_model(a.model)
        out = answer(a.question, store, model, a.k)
        print(out["answer"])
        if out["unknown_links"]:
            print(f"\nWarning: {len(out['unknown_links'])} link(s) in the answer weren't in the retrieved excerpts.",
                  file=sys.stderr)
        return 0
    except ApiError as e:
        hint = {401: "check YTT_API_KEY", 402: "out of credits: top up, then re-run (finished videos are kept)"}
        print(f"Stopped: {e}. {hint.get(e.status, '')}".strip(), file=sys.stderr)
        if a.cmd == "index" and "store" in locals() and store is not None and "batch" in locals():
            if batch:
                store.add_documents(batch)
            store.dump(str(path))
        return 3


if __name__ == "__main__":
    sys.exit(main())
