#!/usr/bin/env python3
"""Build a permission-checked YouTube transcript dataset (JSONL) for fine-tuning, RAG or evals.

Pipeline: collect video IDs -> check permission -> fetch transcripts -> clean -> filter
-> de-duplicate (exact + near) -> chunk -> split train/validation by channel -> data card.

Permission comes first, and it's free. A video is used only if at least one of these holds:
  * trainability: YouTube's Third-Party Trainability API says "all", or lists the company you pass
    with --company (no key, no quota)
  * creative-commons: YouTube Data API status.license is "creativeCommon" (needs YT_DATA_API_KEY;
    videos.list costs 1 quota unit per 50 videos)
  * allowlist: the video or channel ID is in --allowlist (your own channel, licensed content)
Nothing else is fetched, so no credits are spent on videos you can't use.

Usage:
    export YTT_API_KEY=tk_live_...
    python build_transcript_dataset.py --channel @YourChannel --permission allowlist --allowlist mine.txt
    python build_transcript_dataset.py --videos ids.txt --permission trainability creative-commons --dry-run
    python build_transcript_dataset.py --playlist PLxxxx --permission trainability --company "Acme AI"

Python 3.9+, standard library only. Docs: https://youtubetranscriptapi.com/docs/api/transcript
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import json
import os
import random
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import zlib
from datetime import date
from pathlib import Path

BASE = os.environ.get("YT_API_BASE", "https://youtubetranscriptapi.com/api/v2")
TRAINABILITY = "https://youtube.googleapis.com/youtube/v3/videoTrainability"
DATA_API = "https://www.googleapis.com/youtube/v3/videos"
TIMEOUT = 60
MAX_ATTEMPTS = 4
LISTING_COST = 20
ID_RE = re.compile(r"(?:v=|youtu\.be/|shorts/|embed/|live/)([A-Za-z0-9_-]{11})|^([A-Za-z0-9_-]{11})$")
TAG_RE = re.compile(r"\[(?:music|applause|laughter|laughs|inaudible|silence|cheering|noise|foreign)\]|♪+", re.I)
MANIFEST_FIELDS = ["videoId", "channel", "status", "permission", "language", "words", "chunks", "split", "title"]


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


def http_json(url: str, headers: dict | None = None) -> dict:
    """GET JSON. Retries 408/429/503 and network errors, honoring Retry-After."""
    req = urllib.request.Request(url, headers={"Accept": "application/json", **(headers or {})})
    for attempt in range(1, MAX_ATTEMPTS + 1):
        try:
            with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
                return json.loads(resp.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            try:
                body = json.loads(e.read().decode("utf-8") or "{}")
            except ValueError:
                body = {}
            if e.code in (408, 429, 503) and attempt < MAX_ATTEMPTS:
                try:
                    wait = max(1.0, min(float(e.headers.get("Retry-After")), 120.0))
                except (TypeError, ValueError):
                    wait = float(2 ** attempt)
                time.sleep(wait)
                continue
            err = body.get("error")
            code = body.get("code") or (err.get("status") if isinstance(err, dict) else err) or "error"
            raise ApiError(e.code, str(code), body.get("detail")) from None
        except (urllib.error.URLError, TimeoutError):
            if attempt < MAX_ATTEMPTS:
                time.sleep(2 ** attempt)
                continue
            raise
    raise RuntimeError("unreachable")


def call(path: str, params: dict, key: str) -> dict:
    return http_json(f"{BASE}{path}?{urllib.parse.urlencode(params)}", {"Authorization": f"Bearer {key}"})


def video_id(text: str) -> str | None:
    m = ID_RE.search(text.strip())
    return (m.group(1) or m.group(2)) if m else None


# ---------- permission ----------

def trainability(vid: str, company: str | None, fetch=http_json) -> str | None:
    """Return a reason string if YouTube's Trainability API allows training, else None."""
    permitted = fetch(f"{TRAINABILITY}?id={vid}").get("permitted") or []
    lowered = [p.strip().lower() for p in permitted]  # the live API returns "None", the docs say "none"
    if lowered == ["all"]:
        return "trainability:all"
    if company and company.strip().lower() in lowered:
        return f"trainability:{company}"
    return None


def creative_commons(ids: list[str], data_key: str, fetch=http_json) -> set[str]:
    """IDs whose YouTube license is Creative Commons (videos.list, 1 quota unit per 50 IDs)."""
    found = set()
    for i in range(0, len(ids), 50):
        q = urllib.parse.urlencode({"part": "status", "id": ",".join(ids[i:i + 50]), "key": data_key})
        for item in fetch(f"{DATA_API}?{q}").get("items", []):
            if (item.get("status") or {}).get("license") == "creativeCommon":
                found.add(item["id"])
    return found


# ---------- text ----------

def clean_segments(transcript) -> list[dict]:
    """Drop sound tags and the repeated lines that rolling auto captions produce."""
    out: list[dict] = []
    for s in transcript if isinstance(transcript, list) else []:
        text = " ".join(TAG_RE.sub(" ", str(s.get("text") or "")).split())
        if not text:
            continue
        seg = {"text": text, "start": float(s.get("start") or 0), "duration": float(s.get("duration") or 0)}
        if out and (text == out[-1]["text"] or out[-1]["text"].endswith(text)):
            continue
        out.append(seg)
    return out


def repetition_ratio(words: list[str], n: int = 3) -> float:
    """Share of word trigrams that repeat an earlier trigram. Looping ASR output scores high."""
    grams = [tuple(words[i:i + n]) for i in range(len(words) - n + 1)]
    return 0.0 if not grams else 1 - len(set(grams)) / len(grams)


def shingles(words: list[str], k: int = 5) -> set[int]:
    """Stable 32-bit hashes of k-word shingles (zlib.crc32, so runs are repeatable)."""
    return {zlib.crc32(" ".join(words[i:i + k]).encode("utf-8")) for i in range(max(1, len(words) - k + 1))}


class MinHash:
    """Tiny MinHash for near-duplicate detection (Jaccard estimate over 5-word shingles)."""

    def __init__(self, num_perm: int = 64, seed: int = 7):
        rnd = random.Random(seed)
        self.prime = (1 << 61) - 1
        self.ab = [(rnd.randrange(1, self.prime), rnd.randrange(0, self.prime)) for _ in range(num_perm)]

    def signature(self, sh: set[int]) -> tuple[int, ...]:
        return tuple(min(((a * x + b) % self.prime) for x in sh) for a, b in self.ab)

    @staticmethod
    def similarity(s1: tuple[int, ...], s2: tuple[int, ...]) -> float:
        return sum(x == y for x, y in zip(s1, s2)) / len(s1)


def chunk(segments: list[dict], max_words: int, overlap: int) -> list[dict]:
    """Word-window chunks that keep the start and end time of the speech they cover."""
    words: list[tuple[str, float, float]] = []
    for s in segments:
        for w in s["text"].split():
            words.append((w, s["start"], s["start"] + s["duration"]))
    out, step, i = [], max(1, max_words - overlap), 0
    while i < len(words):
        part = words[i:i + max_words]
        out.append({"text": " ".join(w for w, _, _ in part), "start": round(part[0][1], 2), "end": round(part[-1][2], 2)})
        if i + max_words >= len(words):
            break
        i += step
    return out


def split_of(channel: str, val_pct: float) -> str:
    """Whole channels go to one split, so the same speaker never sits on both sides."""
    bucket = int(hashlib.sha256(channel.encode("utf-8")).hexdigest()[:8], 16) / 0xFFFFFFFF
    return "validation" if bucket < val_pct else "train"


# ---------- main ----------

def main(argv: list[str] | None = None, fetch=http_json, api=call) -> int:
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    p.add_argument("--videos", help="text file with one video ID or URL per line")
    p.add_argument("--playlist", action="append", default=[], help="playlist ID or URL (up to 100 videos, 20 credits)")
    p.add_argument("--channel", action="append", default=[], help="@handle or channel ID (newest 100 uploads, 20 credits)")
    p.add_argument("--permission", nargs="+", default=["trainability"],
                   choices=["trainability", "creative-commons", "allowlist"], help="accepted permission sources")
    p.add_argument("--company", help="your company name as it appears in YouTube's trainability list")
    p.add_argument("--allowlist", help="file of video or channel IDs you have rights to")
    p.add_argument("--language", default="en")
    p.add_argument("--min-words", type=int, default=200)
    p.add_argument("--max-repetition", type=float, default=0.3)
    p.add_argument("--near-dup", type=float, default=0.8, help="MinHash similarity treated as a duplicate")
    p.add_argument("--chunk-words", type=int, default=512)
    p.add_argument("--overlap", type=int, default=64)
    p.add_argument("--val", type=float, default=0.1, help="share of channels held out for validation")
    p.add_argument("--out", default="dataset")
    p.add_argument("--dry-run", action="store_true", help="check permission, report cost, fetch no transcripts")
    a = p.parse_args(argv)

    key = os.environ.get("YTT_API_KEY", "")
    if not key or not (a.videos or a.playlist or a.channel):
        p.error("set YTT_API_KEY and pass --videos, --playlist or --channel")
    if "allowlist" in a.permission and not a.allowlist:
        p.error("--permission allowlist needs --allowlist FILE")
    data_key = os.environ.get("YT_DATA_API_KEY", "")
    if "creative-commons" in a.permission and not data_key:
        p.error("--permission creative-commons needs YT_DATA_API_KEY (YouTube Data API key)")

    out = Path(a.out)
    (out / "raw").mkdir(parents=True, exist_ok=True)
    videos: dict[str, dict] = {}
    if a.videos:
        for line in Path(a.videos).read_text(encoding="utf-8").splitlines():
            vid = video_id(line) if line.strip() and not line.startswith("#") else None
            if vid:
                videos.setdefault(vid, {"channel": "", "title": ""})
    credits = 0
    for kind, values in (("playlist", a.playlist), ("channel", a.channel)):
        for value in values:
            path = "/youtube/playlist/videos" if kind == "playlist" else "/youtube/channel/videos"
            try:
                listing = api(path, {kind: value}, key)
            except ApiError as e:
                print(f"Listing {value} failed (not charged): {e}", file=sys.stderr)
                continue
            credits += LISTING_COST
            for r in listing.get("results", []):
                if r.get("videoId"):
                    videos.setdefault(r["videoId"], {"channel": r.get("channelId") or value, "title": r.get("title") or ""})

    allowed = set()
    if a.allowlist:
        allowed = {x.strip() for x in Path(a.allowlist).read_text(encoding="utf-8").split() if x.strip()}
    cc = creative_commons(list(videos), data_key, fetch) if "creative-commons" in a.permission else set()

    manifest: dict[str, dict] = {}
    permitted: list[str] = []
    for vid, info in videos.items():
        reason = None
        if "allowlist" in a.permission and (vid in allowed or info["channel"] in allowed):
            reason = "allowlist"
        if not reason and vid in cc:
            reason = "creative-commons"
        if not reason and "trainability" in a.permission:
            try:
                reason = trainability(vid, a.company, fetch)
            except (ApiError, urllib.error.URLError) as e:
                print(f"{vid}: trainability check failed ({e}); skipping", file=sys.stderr)
        manifest[vid] = {"videoId": vid, "channel": info["channel"], "title": info["title"],
                         "status": "permitted" if reason else "no permission", "permission": reason or ""}
        if reason:
            permitted.append(vid)

    cached = [v for v in permitted if (out / "raw" / f"{v}.json").exists()]
    print(f"{len(videos)} videos, {len(permitted)} with permission ({len(videos) - len(permitted)} skipped). "
          f"Listings cost {credits} credits; transcripts cost up to {len(permitted) - len(cached)} more.")
    if a.dry_run:
        _write_manifest(out, manifest)
        return 0

    mh = MinHash()
    seen_exact: set[str] = set()
    signatures: list[tuple[str, tuple[int, ...]]] = []
    rows = {"train": [], "validation": []}
    for n, vid in enumerate(permitted, 1):
        raw_path = out / "raw" / f"{vid}.json"
        if raw_path.exists():
            data = json.loads(raw_path.read_text(encoding="utf-8"))
        else:
            try:
                data = api("/youtube/transcript", {"video_url": vid, "include_timestamp": "true",
                                                   "send_metadata": "true", "language": a.language}, key)
            except ApiError as e:
                if e.status == 404:
                    manifest[vid]["status"] = "no captions (free)"
                    continue
                if e.status == 402:
                    print(f"Out of credits after {n - 1} videos. Top up and re-run; finished videos are cached.", file=sys.stderr)
                    break
                manifest[vid]["status"] = f"error {e.status}"
                continue
            credits += 1
            raw_path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
        meta = data.get("metadata") or {}
        m = manifest[vid]
        m["title"] = m["title"] or meta.get("title") or ""
        m["channel"] = m["channel"] or meta.get("author_url") or meta.get("author_name") or "unknown"
        m["language"] = data.get("language") or ""
        segs = clean_segments(data.get("transcript"))
        words = " ".join(s["text"] for s in segs).split()
        m["words"] = len(words)
        if len(words) < a.min_words:
            m["status"] = "too short"
            continue
        if repetition_ratio(words) > a.max_repetition:
            m["status"] = "repetitive"
            continue
        digest = hashlib.sha256(" ".join(words).lower().encode("utf-8")).hexdigest()
        sig = mh.signature(shingles([w.lower() for w in words]))
        twin = next((o for o, s in signatures if MinHash.similarity(sig, s) >= a.near_dup), None)
        if digest in seen_exact or twin:
            m["status"] = f"duplicate of {twin or 'an earlier video'}"
            continue
        seen_exact.add(digest)
        signatures.append((vid, sig))
        split = split_of(m["channel"], a.val)
        pieces = chunk(segs, a.chunk_words, a.overlap)
        for i, c in enumerate(pieces):
            rows[split].append({"id": f"{vid}-{i:04d}", "video_id": vid, "url": f"https://www.youtube.com/watch?v={vid}&t={int(c['start'])}s",
                                "title": m["title"], "channel": m["channel"], "language": m["language"],
                                "permission": m["permission"], "start": c["start"], "end": c["end"], "text": c["text"]})
        m.update(status="kept", chunks=len(pieces), split=split)

    for split, items in rows.items():
        with open(out / f"{split}.jsonl", "w", encoding="utf-8") as f:
            for r in items:
                f.write(json.dumps(r, ensure_ascii=False) + "\n")
    _write_manifest(out, manifest)
    _write_card(out, manifest, rows, a, credits)
    kept = sum(1 for m in manifest.values() if m["status"] == "kept")
    print(f"Kept {kept} videos: {len(rows['train'])} train and {len(rows['validation'])} validation chunks. "
          f"Spent {credits} credits. See {out / 'DATACARD.md'}.")
    return 0


def _write_manifest(out: Path, manifest: dict) -> None:
    with open(out / "manifest.csv", "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=MANIFEST_FIELDS, extrasaction="ignore")
        w.writeheader()
        w.writerows(manifest.values())


def _write_card(out: Path, manifest: dict, rows: dict, a, credits: int) -> None:
    counts: dict[str, int] = {}
    for m in manifest.values():
        key = m["status"] if not m["status"].startswith("duplicate") else "duplicate"
        counts[key] = counts.get(key, 0) + 1
    perms: dict[str, int] = {}
    for m in manifest.values():
        if m["status"] == "kept":
            perms[m["permission"]] = perms.get(m["permission"], 0) + 1
    words = sum(len(r["text"].split()) for items in rows.values() for r in items)
    lines = [f"# Data card: YouTube transcript dataset ({date.today().isoformat()})", "",
             "## Videos", *[f"- {k}: {v}" for k, v in sorted(counts.items())], "",
             "## Permission behind every kept video", *[f"- {k}: {v}" for k, v in sorted(perms.items())], "",
             "## Splits",
             f"- train: {len(rows['train'])} chunks; validation: {len(rows['validation'])} chunks ({words:,} words incl. overlap)",
             f"- split by channel, {a.val:.0%} of channels held out", "",
             "## Processing",
             f"- language requested: {a.language}; sound tags and rolling-caption repeats removed",
             f"- dropped under {a.min_words} words or over {a.max_repetition:.0%} repeated trigrams",
             f"- exact and near-duplicate removal (MinHash, similarity >= {a.near_dup})",
             f"- chunks of {a.chunk_words} words with {a.overlap} words of overlap; start/end seconds kept", "",
             "## Source", f"- transcripts: YouTube caption tracks via YouTubeTranscriptAPI; credits spent: {credits}",
             "- every row links back to its video and timestamp; check each permission source before redistributing"]
    (out / "DATACARD.md").write_text("\n".join(lines) + "\n", encoding="utf-8")


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