#!/usr/bin/env python3
"""podcast_kit.py: show notes, chapters and verified quotes from a video podcast's
YouTube transcript.

  pip install anthropic
  export YTT_API_KEY=tk_live_...          # https://youtubetranscriptapi.com/dashboard/keys
  export ANTHROPIC_API_KEY=sk-ant-...

  python podcast_kit.py https://www.youtube.com/watch?v=VIDEO_ID
  python podcast_kit.py --playlist PL... --out episodes/
  python podcast_kit.py VIDEO_ID --dry-run          # transcript stats and cost, no model call

For each episode it writes, into OUT/<video_id>/:
  show_notes.md        summary, key points, chapters, quotes, names to link
  youtube_chapters.txt paste into the YouTube description (first line 00:00)
  podcast_chapters.txt paste into Apple Podcasts / Spotify episode notes (HH:MM:SS)
  chapters.json        Podcasting 2.0 JSON chapters (application/json+chapters, v1.2.0)
  report.json          what was fixed or dropped, and why

The model drafts; the script checks. Chapters are snapped to real caption times,
start at 00:00, keep a minimum gap (default 120 s) and short plain titles, so one
list passes YouTube, Spotify and Apple. Every quote is searched for word for word
in the transcript: matches get the exact wording and a timestamp link, near-misses
get the transcript's wording, and anything the guest didn't say is dropped.

Cost: 1 credit per transcript (20 per playlist listing) plus the Claude call.
Needs Python 3.10+.
"""
from __future__ import annotations

import argparse
import difflib
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import unicodedata
from pathlib import Path
from typing import Callable

API = "https://youtubetranscriptapi.com/api/v2"
MODEL = "claude-opus-5-5"
PRICES = {  # USD per million tokens (input, output), Claude API list prices, Nov 2026
    "claude-opus-5-5": (4.00, 20.00),
    "claude-sonnet-5-5": (2.00, 10.00),
    "claude-haiku-5-5": (0.10, 0.50),
}
VIDEO_ID = re.compile(r"(?:[?&]v=|youtu\.be/|/shorts/|/embed/|/live/)([\w-]{11})")


# --------------------------------------------------------------------------- transcript API

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


def call(path: str, params: dict, key: str) -> dict:
    url = f"{API}{path}?{urllib.parse.urlencode(params)}"
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {key}", "User-Agent": "podcast-kit/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:
            code = json.loads(e.read().decode("utf-8")).get("code", "")
        except Exception:
            code = ""
        raise ApiError(e.code, code) 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 fetch_episode(vid: str, key: str, api: Callable = call, language: str = "en") -> dict:
    data = api("/youtube/transcript", {"video_url": vid, "language": language, "format": "json",
                                       "include_timestamp": "true", "send_metadata": "true"}, key)
    segs = [s for s in data.get("transcript") or [] if str(s.get("text", "")).strip()]
    meta = data.get("metadata") or {}
    end = max((float(s["start"]) + float(s.get("duration") or 0) for s in segs), default=0.0)
    return {"video_id": vid, "title": meta.get("title") or vid, "channel": meta.get("author_name") or "",
            "language": data.get("language", ""), "segments": segs, "duration": end}


# --------------------------------------------------------------------------- time formats

def hhmmss(sec: float) -> str:
    s = int(sec)
    return f"{s // 3600:02d}:{s % 3600 // 60:02d}:{s % 60:02d}"


def youtube_time(sec: float, long: bool = False) -> str:
    """MM:SS, and H:MM:SS from the one-hour mark. The first chapter is always 00:00,
    which is how YouTube's help page writes it, even for episodes over an hour."""
    s = int(sec)
    return f"{s // 3600}:{s % 3600 // 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60:02d}:{s % 60:02d}"


def compact_transcript(segs: list[dict], every: float = 20.0) -> str:
    """One [h:mm:ss] marker per ~20 s keeps the prompt small but anchored in time."""
    lines, cur, start = [], [], None
    for s in segs:
        t = float(s["start"])
        if start is None:
            start = t
        if t - start >= every and cur:
            lines.append(f"[{hhmmss(start)}] {' '.join(cur)}")
            cur, start = [], t
        cur.append(" ".join(str(s["text"]).split()))
    if cur:
        lines.append(f"[{hhmmss(start)}] {' '.join(cur)}")
    return "\n".join(lines)


# --------------------------------------------------------------------------- chapters

EMOJI = re.compile("[%s-%s%s-%s%s%s]" % (chr(0x1F000), chr(0x1FAFF), chr(0x2600), chr(0x27BF), chr(0xFE0F), chr(0x200D)))  # emoji, symbols, VS16, ZWJ; built with chr() so this file stays ASCII


def clean_title(title: str, limit: int = 40) -> str:
    t = EMOJI.sub("", unicodedata.normalize("NFKC", title or ""))
    t = re.sub(r"^\s*(\d+\s*[-.:)]\s*)", "", t)        # Spotify strips "1 - " prefixes anyway
    t = re.sub(r"[<>*_#`]", "", " ".join(t.split())).strip(" -:|")
    if len(t) > limit:
        t = t[:limit].rsplit(" ", 1)[0].rstrip(" ,;:-")
    return t or "Untitled"


def fix_chapters(raw: list[dict], segs: list[dict], duration: float, min_gap: float = 120) -> tuple[list[dict], list[str]]:
    """Make one chapter list that YouTube, Spotify and Apple all accept.

    YouTube: first at 00:00, 3+ chapters, each >= 10 s. Spotify: first at 00:00, 3+,
    >= 30 s between starts. Apple: first at 00:00:00, 3+, and it recommends chapters
    of at least two minutes. Returns (chapters, notes about every change)."""
    notes, starts = [], sorted(float(s["start"]) for s in segs)
    items = []
    for c in raw:
        try:
            t = float(c.get("start_seconds", 0))
        except (TypeError, ValueError):
            notes.append(f"dropped chapter with no usable time: {c!r}")
            continue
        snapped = max((s for s in starts if s <= t + 0.5), default=0.0)  # a real caption boundary
        title = clean_title(c.get("title", ""))
        if title != " ".join(str(c.get("title", "")).split()):
            notes.append(f"title {c.get('title', '')!r} -> {title!r} (plain text, 40 characters max)")
        if abs(snapped - t) >= 1:
            notes.append(f"snapped '{title}' from {hhmmss(t)} to caption start {hhmmss(snapped)}")
        items.append({"start": snapped, "title": title})
    items.sort(key=lambda c: c["start"])
    if not items or items[0]["start"] > 0:
        if items and items[0]["start"] <= min_gap:
            notes.append(f"moved first chapter from {hhmmss(items[0]['start'])} to 00:00:00")
            items[0]["start"] = 0.0
        else:
            notes.append("added an 'Intro' chapter at 00:00:00")
            items.insert(0, {"start": 0.0, "title": "Intro"})
    out = []
    for c in items:
        if out and c["start"] - out[-1]["start"] < min_gap:
            notes.append(f"dropped '{c['title']}' at {hhmmss(c['start'])}: under {int(min_gap)} s after the previous chapter")
            continue
        if duration and duration - c["start"] < max(10, min(min_gap, 30)) and out:
            notes.append(f"dropped '{c['title']}' at {hhmmss(c['start'])}: too close to the end")
            continue
        out.append(c)
    if len(out) < 3:
        notes.append(f"only {len(out)} chapter(s) left; YouTube, Spotify and Apple need 3, so no chapter list was written")
        return [], notes
    return out, notes


def chapter_files(chapters: list[dict], duration: float, title: str) -> dict[str, str]:
    long = duration >= 3600
    yt = "\n".join(f"{youtube_time(c['start'], long)} {c['title']}" for c in chapters)
    pod = "\n".join(f"{hhmmss(c['start'])} {c['title']}" for c in chapters)
    js = json.dumps({"version": "1.2.0", "title": title,
                     "chapters": [{"startTime": round(c["start"], 2), "title": c["title"]} for c in chapters]}, indent=2)
    return {"youtube_chapters.txt": yt + "\n", "podcast_chapters.txt": pod + "\n", "chapters.json": js + "\n"}


# --------------------------------------------------------------------------- quotes

def _norm(word: str) -> str:
    return re.sub(r"[^\w']", "", unicodedata.normalize("NFKC", word).lower().replace(chr(0x2019), "'"))


def word_index(segs: list[dict]) -> list[tuple[str, str, float]]:
    """(normalized, original, segment start) for every word in the transcript."""
    out = []
    for s in segs:
        for w in str(s["text"]).split():
            n = _norm(w)
            if n:
                out.append((n, w, float(s["start"])))
    return out


def verify_quote(text: str, words: list[tuple[str, str, float]], near: float | None = None,
                 fuzzy: float = 0.9) -> dict:
    """Find a quote word for word. Returns status exact | adjusted | missing."""
    q = [n for n in (_norm(w) for w in str(text).split()) if n]
    if len(q) < 4:
        return {"status": "missing", "reason": "too short to verify"}
    norm = [w[0] for w in words]
    hits = [i for i in range(len(norm) - len(q) + 1) if norm[i] == q[0] and norm[i:i + len(q)] == q]
    status, length = "exact", len(q)
    if not hits:
        best, best_i, best_len = 0.0, -1, len(q)
        sm = difflib.SequenceMatcher(autojunk=False)
        sm.set_seq2(q)
        # windows a little shorter or longer than the quote catch an added or dropped word
        for n in range(max(4, len(q) - 2), len(q) + 3):
            for i in range(0, max(1, len(norm) - n + 1)):
                sm.set_seq1(norm[i:i + n])
                # the two cheap upper bounds rule out almost every window before the real ratio
                if sm.real_quick_ratio() <= best or sm.quick_ratio() <= best:
                    continue
                r = sm.ratio()
                if r > best:
                    best, best_i, best_len = r, i, n
        if best < fuzzy:
            return {"status": "missing", "reason": f"not in the transcript (best match {best:.0%})"}
        hits, status, length = [best_i], "adjusted", best_len
    i = min(hits, key=lambda h: abs(words[h][2] - near)) if near is not None else hits[0]
    exact = " ".join(w[1] for w in words[i:i + length])
    return {"status": status, "text": exact, "start": words[i][2]}


# --------------------------------------------------------------------------- the model call

SCHEMA = {
    "type": "object",
    "properties": {
        "summary": {"type": "string", "description": "2-3 sentence episode summary"},
        "key_points": {"type": "array", "items": {"type": "string"}},
        "chapters": {"type": "array", "items": {
            "type": "object",
            "properties": {"start_seconds": {"type": "number"}, "title": {"type": "string"}},
            "required": ["start_seconds", "title"], "additionalProperties": False}},
        "quotes": {"type": "array", "items": {
            "type": "object",
            "properties": {"text": {"type": "string"}, "speaker": {"type": "string"},
                           "approx_seconds": {"type": "number"}},
            "required": ["text", "speaker", "approx_seconds"], "additionalProperties": False}},
        "mentions": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["summary", "key_points", "chapters", "quotes", "mentions"],
    "additionalProperties": False,
}

SYSTEM = """You write podcast show notes from a timestamped transcript. Rules:
- Chapters: 4 to 12, at real topic changes, using the [h:mm:ss] marker where the topic starts.
  Titles are plain text, under 40 characters, no emojis or numbering.
- Quotes: 3 to 6 memorable lines copied word for word from the transcript, 8 to 40 words each.
  Do not fix grammar, merge sentences or paraphrase. Give the marker time nearest the quote.
- Mentions: books, tools, people, companies and sites the speakers name, so the host can add links.
- Summary and key points: only what the transcript says. Captions can mishear names; keep them as heard."""


def draft(episode: dict, client, model: str = MODEL, effort: str = "medium") -> tuple[dict, dict]:
    """One Claude call with structured output. Returns (draft, usage)."""
    prompt = (f"Episode: {episode['title']}\nChannel: {episode['channel']}\n"
              f"Length: {hhmmss(episode['duration'])}\n\nTranscript:\n{compact_transcript(episode['segments'])}")
    with client.beta.messages.stream(
        model=model,
        max_tokens=16000,
        betas=["server-side-fallback-2026-07-01"],
        fallbacks="default",  # re-run a refused request on Anthropic's recommended fallback model
        output_config={"effort": effort, "format": {"type": "json_schema", "schema": SCHEMA}},
        system=SYSTEM,
        messages=[{"role": "user", "content": prompt}],
    ) as stream:
        msg = stream.get_final_message()
    if msg.stop_reason == "refusal":
        raise RuntimeError(f"the model declined this episode ({getattr(msg.stop_details, 'category', None)})")
    if msg.stop_reason == "max_tokens":
        raise RuntimeError("the draft hit max_tokens; try a shorter episode or lower effort")
    text = next(b.text for b in msg.content if b.type == "text")
    usage = {"input_tokens": msg.usage.input_tokens, "output_tokens": msg.usage.output_tokens}
    return json.loads(text), usage


def cost(usage: dict, model: str) -> float:
    pin, pout = PRICES.get(model, PRICES[MODEL])
    return usage["input_tokens"] / 1e6 * pin + usage["output_tokens"] / 1e6 * pout


# --------------------------------------------------------------------------- one episode

def build(episode: dict, d: dict, min_gap: float = 120) -> tuple[dict[str, str], dict]:
    chapters, ch_notes = fix_chapters(d.get("chapters") or [], episode["segments"], episode["duration"], min_gap)
    words = word_index(episode["segments"])
    quotes, q_notes = [], []
    for q in d.get("quotes") or []:
        v = verify_quote(q.get("text", ""), words, q.get("approx_seconds"))
        if v["status"] == "missing":
            q_notes.append(f"dropped quote ({v['reason']}): {q.get('text', '')[:80]}")
            continue
        if v["status"] == "adjusted":
            q_notes.append(f"replaced with the transcript's wording: {q.get('text', '')[:60]} -> {v['text'][:60]}")
        quotes.append({**v, "speaker": q.get("speaker", "")})
    vid, long = episode["video_id"], episode["duration"] >= 3600
    link = lambda t: f"https://www.youtube.com/watch?v={vid}&t={int(t)}s"  # noqa: E731
    md = [f"# {episode['title']}", "", d.get("summary", "").strip(), ""]
    if d.get("key_points"):
        md += ["## In this episode", ""] + [f"- {p}" for p in d["key_points"]] + [""]
    if chapters:
        md += ["## Chapters", ""] + [f"- [{youtube_time(c['start'], long)}]({link(c['start'])}) {c['title']}" for c in chapters] + [""]
    if quotes:
        md += ["## Quotes", ""]
        for q in quotes:
            who = f" ({q['speaker']})" if q["speaker"] else ""
            md += [f"> {q['text']}", f">", f"> [{youtube_time(q['start'], long)}]({link(q['start'])}){who}", ""]
    if d.get("mentions"):
        md += ["## Mentioned (add links)", ""] + [f"- {m}" for m in d["mentions"]] + [""]
    md += [f"Watch: https://www.youtube.com/watch?v={vid}", ""]
    files = {"show_notes.md": "\n".join(md)}
    if chapters:
        files.update(chapter_files(chapters, episode["duration"], episode["title"]))
    report = {"video_id": vid, "chapters": len(chapters), "chapter_fixes": ch_notes,
              "quotes_kept": len(quotes), "quotes_exact": sum(q["status"] == "exact" for q in quotes),
              "quote_fixes": q_notes}
    return files, report


def main(argv: list[str] | None = None, api: Callable = call, client=None) -> int:
    p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    p.add_argument("videos", nargs="*", help="video links or IDs")
    p.add_argument("--playlist", help="every video in a playlist (up to 100, 20 credits)")
    p.add_argument("--out", default="podcast_kit")
    p.add_argument("--model", default=MODEL, help=f"Claude model (default {MODEL})")
    p.add_argument("--effort", default="medium", choices=["low", "medium", "high"])
    p.add_argument("--min-gap", type=float, default=120, help="seconds between chapters (Apple recommends 120; Spotify needs 30)")
    p.add_argument("--language", default="en")
    p.add_argument("--dry-run", action="store_true", help="fetch transcripts and estimate cost; no model call")
    a = p.parse_args(argv)
    key = os.environ.get("YTT_API_KEY", "")
    if not key:
        print("Set YTT_API_KEY first.", file=sys.stderr)
        return 2
    vids = [v for v in (video_id(x) for x in a.videos) if v]
    try:
        if a.playlist:
            vids += [r["videoId"] for r in api("/youtube/playlist/videos", {"playlist": a.playlist}, key).get("results") or []]
    except ApiError as e:
        print(f"Couldn't list the playlist: {e}", file=sys.stderr)
        return 3
    vids = list(dict.fromkeys(vids))
    if not vids:
        p.error("give at least one video link or ID, or --playlist")
    if client is None and not a.dry_run:
        import anthropic  # imported here so --dry-run works without it
        client = anthropic.Anthropic()
    total, failed = 0.0, 0
    for vid in vids:
        try:
            ep = fetch_episode(vid, key, api, a.language)
        except ApiError as e:
            failed += 1
            why = {404: "no captions (not charged)", 402: "out of credits", 401: "API key rejected"}.get(e.status, str(e))
            print(f"{vid}: skipped, {why}", file=sys.stderr)
            if e.status in (401, 402):
                return 3
            continue
        words = sum(len(str(s["text"]).split()) for s in ep["segments"])
        if a.dry_run:
            est = {"input_tokens": int(words * 1.45) + 600, "output_tokens": 2500}
            print(f"{vid}  {hhmmss(ep['duration'])}  {words:,} words  ~${cost(est, a.model):.3f} with {a.model}  {ep['title'][:60]}")
            continue
        try:
            d, usage = draft(ep, client, a.model, a.effort)
        except RuntimeError as e:
            failed += 1
            print(f"{vid}: {e}", file=sys.stderr)
            continue
        files, report = build(ep, d, a.min_gap)
        report["usage"], report["cost_usd"] = usage, round(cost(usage, a.model), 4)
        total += report["cost_usd"]
        folder = Path(a.out) / vid
        folder.mkdir(parents=True, exist_ok=True)
        for name, body in files.items():
            (folder / name).write_text(body, encoding="utf-8")
        (folder / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
        print(f"{vid}: {report['chapters']} chapters, {report['quotes_kept']} quotes "
              f"({report['quotes_exact']} exact), {len(report['chapter_fixes']) + len(report['quote_fixes'])} fixes, "
              f"${report['cost_usd']:.3f} -> {folder}")
    if not a.dry_run:
        print(f"Done: {len(vids) - failed} of {len(vids)} episodes, model cost ${total:.3f} plus 1 credit per transcript.")
    return 0 if failed < len(vids) else 3


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