#!/usr/bin/env python3
"""Build a codable, reproducible corpus of YouTube transcripts for research.

Four steps, four subcommands:

  build   fetch timestamped transcripts for a video list, channel, playlist or search,
          optionally draw a seeded random sample, and export:
            srt/<id>.srt      import into ATLAS.ti or MAXQDA next to the video
            txt/<id>.txt      plain text with [hh:mm:ss] marks (NVivo, any QDA tool)
            corpus.csv        one row per caption segment, with a link to that second
            manifest.csv      every video, its status, language, word count and SHA-256
            METHODS.md        a methods paragraph with your real counts and dates
          --pseudonymize replaces channel names and video IDs with C001/V0001 codes and
          writes the key to a separate folder, so you can store it apart from the data.
  code    run a keyword codebook over corpus.csv and write coded_segments.csv
          (keyword in context + timestamp link) and code_matrix.csv (videos x codes).
          This is a first pass for human coders, not a replacement for them.
  sample  draw a seeded sample of segments for two or more coders to double-code.
  alpha   compute Krippendorff's alpha (nominal) from the coders' columns.

Usage:
    export YTT_API_KEY=tk_live_...
    python research_corpus.py build --channel @SomeChannel --sample 200 --seed 42 --out corpus
    python research_corpus.py build --search "vaccine side effects" --search-limit 50 --dry-run
    python research_corpus.py code --corpus corpus --codebook codebook.csv
    python research_corpus.py sample --corpus corpus --n 150 --seed 7
    python research_corpus.py alpha corpus/reliability_sample.csv --coders coder_1 coder_2

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
from datetime import datetime, timezone
from pathlib import Path

BASE = os.environ.get("YT_API_BASE", "https://youtubetranscriptapi.com/api/v2")
TIMEOUT = 60
MAX_ATTEMPTS = 4
LISTING_COST = 20
SEARCH_COST = 4
ID_RE = re.compile(r"(?:v=|youtu\.be/|shorts/|embed/|live/)([A-Za-z0-9_-]{11})|^([A-Za-z0-9_-]{11})$")
MANIFEST_FIELDS = ["video", "channel", "title", "source", "status", "language_requested", "language_returned",
                   "segments", "words", "sha256", "retrieved_utc"]
CORPUS_FIELDS = ["video", "channel", "segment", "start", "end", "timestamp", "text", "url"]


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


# ---------- text helpers ----------

def clock(seconds: float, srt: bool = False) -> str:
    ms = int(round(seconds * 1000))
    h, rem = divmod(ms, 3_600_000)
    m, rem = divmod(rem, 60_000)
    s, ms = divmod(rem, 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" if srt else f"{h:02d}:{m:02d}:{s:02d}"


def segments_of(transcript) -> list[dict]:
    """Keep the caption text verbatim; only drop empty lines and exact back-to-back repeats."""
    out: list[dict] = []
    for s in transcript if isinstance(transcript, list) else []:
        text = " ".join(str(s.get("text") or "").split())
        if not text or (out and out[-1]["text"] == text):
            continue
        start = float(s.get("start") or 0)
        out.append({"text": text, "start": start, "end": start + float(s.get("duration") or 0)})
    for a, b in zip(out, out[1:]):  # rolling auto captions overlap; end each cue where the next begins
        if a["end"] > b["start"]:
            a["end"] = max(a["start"], b["start"])
    return out


def to_srt(segs: list[dict]) -> str:
    return "\n".join(f"{i}\n{clock(s['start'], True)} --> {clock(s['end'], True)}\n{s['text']}\n"
                     for i, s in enumerate(segs, 1))


# ---------- build ----------

def collect(a, key: str, api) -> tuple[dict[str, dict], int]:
    """Candidate videos from every source, in a stable order, plus credits spent on listings."""
    videos: dict[str, dict] = {}
    credits = 0
    if a.videos:
        for line in Path(a.videos).read_text(encoding="utf-8").splitlines():
            vid = video_id(line.split(",")[0]) if line.strip() and not line.startswith("#") else None
            if vid:
                videos.setdefault(vid, {"channel": "", "title": "", "source": "list"})
    jobs = [("/youtube/channel/videos", {"channel": c}, LISTING_COST, f"channel:{c}") for c in a.channel]
    jobs += [("/youtube/playlist/videos", {"playlist": p}, LISTING_COST, f"playlist:{p}") for p in a.playlist]
    jobs += [("/youtube/search", {"q": q, "type": "video", "limit": a.search_limit}, SEARCH_COST, f"search:{q}")
             for q in a.search]
    for path, params, cost, label in jobs:
        try:
            listing = api(path, params, key)
        except ApiError as e:
            print(f"{label} failed (not charged): {e}", file=sys.stderr)
            continue
        credits += cost
        for r in listing.get("results", []):
            if r.get("videoId"):
                videos.setdefault(r["videoId"], {"channel": r.get("channelTitle") or r.get("channelId") or "",
                                                 "title": r.get("title") or "", "source": label})
    return videos, credits


def build(a, api=call) -> int:
    key = os.environ.get("YTT_API_KEY", "")
    if not key or not (a.videos or a.channel or a.playlist or a.search):
        print("Set YTT_API_KEY and pass --videos, --channel, --playlist or --search.", file=sys.stderr)
        return 2
    out = Path(a.out)
    for sub in ("raw", "srt", "txt"):
        (out / sub).mkdir(parents=True, exist_ok=True)

    videos, credits = collect(a, key, api)
    pool = list(videos)
    if a.sample and a.sample < len(pool):
        chosen = sorted(random.Random(a.seed).sample(sorted(pool), a.sample))
        pool = [v for v in pool if v in set(chosen)]
    cached = sum(1 for v in pool if (out / "raw" / f"{v}.json").exists())
    print(f"{len(videos)} candidate videos; {len(pool)} in the study"
          f"{f' (seeded sample, seed {a.seed})' if len(pool) < len(videos) else ''}. "
          f"Listings cost {credits} credits; transcripts cost up to {len(pool) - cached} more.")
    if a.dry_run:
        return 0

    codes = Pseudonyms() if a.pseudonymize else None
    manifest, corpus = [], []
    for n, vid in enumerate(pool, 1):
        raw = out / "raw" / f"{vid}.json"
        info = videos[vid]
        row = {"language_requested": a.language, "source": info["source"], "status": "", "segments": 0, "words": 0}
        if raw.exists():
            data = json.loads(raw.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 == 402:
                    print(f"Out of credits after {n - 1} videos. Top up and re-run; fetched videos are cached.",
                          file=sys.stderr)
                    break
                row["status"] = "no captions (not charged)" if e.status == 404 else f"error {e.status} (not charged)"
                manifest.append(_identify(row, vid, info, {}, codes))
                continue
            data["_retrieved_utc"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
            raw.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
            credits += 1
        meta = data.get("metadata") or {}
        segs = segments_of(data.get("transcript"))
        text = " ".join(s["text"] for s in segs)
        row.update(status="ok" if segs else "empty transcript", language_returned=data.get("language") or "",
                   segments=len(segs), words=len(text.split()),
                   sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(), retrieved_utc=data.get("_retrieved_utc", ""))
        if row["language_returned"] and row["language_returned"] != a.language:
            row["status"] = f"ok, but {row['language_returned']} returned"
        m = _identify(row, vid, info, meta, codes)
        manifest.append(m)
        if not segs:
            continue
        name = m["video"]
        (out / "srt" / f"{name}.srt").write_text(to_srt(segs), encoding="utf-8")
        head = [f"Video: {name}", f"Channel: {m['channel']}"]
        if not codes:
            head += [f"Title: {m['title']}", f"URL: https://www.youtube.com/watch?v={vid}"]
        head += [f"Caption language: {row['language_returned']}", f"Retrieved (UTC): {row['retrieved_utc']}", ""]
        body = [f"[{clock(s['start'])}] {s['text']}" for s in segs]
        (out / "txt" / f"{name}.txt").write_text("\n".join(head + body) + "\n", encoding="utf-8")
        for i, s in enumerate(segs, 1):
            corpus.append({"video": name, "channel": m["channel"], "segment": i, "start": round(s["start"], 2),
                           "end": round(s["end"], 2), "timestamp": clock(s["start"]), "text": s["text"],
                           "url": "" if codes else f"https://www.youtube.com/watch?v={vid}&t={int(s['start'])}s"})

    _write_csv(out / "manifest.csv", MANIFEST_FIELDS, manifest)
    _write_csv(out / "corpus.csv", CORPUS_FIELDS, corpus)
    if codes:
        keydir = Path(a.key_dir or f"{a.out}_KEY_store_separately")
        keydir.mkdir(parents=True, exist_ok=True)
        _write_csv(keydir / "pseudonym_key.csv", ["code", "original", "kind"], codes.rows())
        print(f"Pseudonym key written to {keydir}. Keep it away from the corpus folder.")
    _write_methods(out, a, videos, pool, manifest, credits)
    ok = sum(1 for m in manifest if m["status"].startswith("ok"))
    print(f"{ok} of {len(pool)} videos have transcripts; {len(corpus)} segments. Spent {credits} credits. "
          f"See {out / 'METHODS.md'}.")
    return 0


class Pseudonyms:
    """Stable C001 / V0001 codes, kept in a key you store apart from the data (AoIR IRE 3.0)."""

    def __init__(self):
        self.map: dict[tuple[str, str], str] = {}

    def code(self, kind: str, original: str) -> str:
        if (kind, original) not in self.map:
            n = sum(1 for k in self.map if k[0] == kind) + 1
            self.map[(kind, original)] = f"C{n:03d}" if kind == "channel" else f"V{n:04d}"
        return self.map[(kind, original)]

    def rows(self) -> list[dict]:
        return [{"code": c, "original": o, "kind": k} for (k, o), c in self.map.items()]


def _identify(row: dict, vid: str, info: dict, meta: dict, codes: Pseudonyms | None) -> dict:
    channel = info["channel"] or meta.get("author_name") or meta.get("author_url") or "unknown"
    title = info["title"] or meta.get("title") or ""
    if codes:
        return {**row, "video": codes.code("video", vid), "channel": codes.code("channel", channel), "title": ""}
    return {**row, "video": vid, "channel": channel, "title": title}


def _write_csv(path: Path, fields: list[str], rows: list[dict]) -> None:
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
        w.writeheader()
        w.writerows(rows)


def _write_methods(out: Path, a, videos: dict, pool: list, manifest: list, credits: int) -> None:
    counts: dict[str, int] = {}
    for m in manifest:
        counts[m["status"]] = counts.get(m["status"], 0) + 1
    dates = sorted(m.get("retrieved_utc") or "" for m in manifest if m.get("retrieved_utc"))
    ok = [m for m in manifest if m["status"].startswith("ok")]
    words = sum(int(m["words"]) for m in ok)
    sources = sorted({videos[v]["source"] for v in pool})
    sample = (f" From {len(videos)} candidates, {len(pool)} were drawn at random (Python random.sample, seed {a.seed})."
              if len(pool) < len(videos) else "")
    span = f"between {dates[0][:10]} and {dates[-1][:10]}" if dates else "on the dates in manifest.csv"
    para = (f"We collected the caption tracks of {len(pool)} YouTube videos ({'; '.join(sources)}).{sample} "
            f"Transcripts were retrieved {span} through YouTubeTranscriptAPI, requesting language '{a.language}'. "
            f"{len(ok)} videos returned a transcript ({words:,} words); {len(pool) - len(ok)} did not "
            f"(see manifest.csv for each reason). Caption tracks may be machine-generated by YouTube and were not "
            f"corrected unless stated; each transcript's SHA-256 hash is listed in manifest.csv.")
    lines = [f"# Methods notes ({datetime.now(timezone.utc).date().isoformat()})", "", "## Draft paragraph", "", para, "",
             "## Status counts", *[f"- {k}: {v}" for k, v in sorted(counts.items())], "",
             "## Before you publish",
             "- YouTube's automatic captions can mishear names, accents and overlapping speech; spot-check against the audio.",
             "- The API does not say whether a track was uploaded by the creator or generated automatically.",
             "- Quoting a transcript verbatim can make a speaker findable by searching the quote.",
             f"- Credits spent: {credits} (failed and no-caption requests are not charged)."]
    (out / "METHODS.md").write_text("\n".join(lines) + "\n", encoding="utf-8")


# ---------- code ----------

def load_codebook(path: str) -> list[tuple[str, list[str], re.Pattern]]:
    """codebook.csv columns: code, terms. Terms are separated by |; a trailing * matches any ending."""
    book = []
    with open(path, encoding="utf-8") as f:
        for r in csv.DictReader(f):
            terms = [t.strip() for t in (r.get("terms") or "").split("|") if t.strip()]
            if not r.get("code") or not terms:
                continue
            alts = [re.escape(t[:-1]) + r"\w*" if t.endswith("*") else re.escape(t) for t in terms]
            book.append((r["code"].strip(), terms, re.compile(r"\b(?:" + "|".join(alts) + r")\b", re.I)))
    return book


def code(a) -> int:
    corpus_dir = Path(a.corpus)
    with open(corpus_dir / "corpus.csv", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    book = load_codebook(a.codebook)
    hits, matrix = [], {}
    by_video: dict[str, list[dict]] = {}
    for r in rows:
        by_video.setdefault(r["video"], []).append(r)
    for vid, segs in by_video.items():
        matrix[vid] = {c: 0 for c, _, _ in book}
        for i, s in enumerate(segs):
            for c, _, rx in book:
                found = rx.findall(s["text"])
                if not found:
                    continue
                matrix[vid][c] += 1
                ctx = " ".join(x["text"] for x in segs[max(0, i - a.context):i + a.context + 1])
                hits.append({"code": c, "video": vid, "channel": s["channel"], "segment": s["segment"],
                             "timestamp": s["timestamp"], "matched": "; ".join(sorted({x.lower() for x in found})),
                             "text": s["text"], "context": ctx, "url": s["url"]})
    _write_csv(corpus_dir / "coded_segments.csv",
               ["code", "video", "channel", "segment", "timestamp", "matched", "text", "context", "url"], hits)
    _write_csv(corpus_dir / "code_matrix.csv", ["video", *[c for c, _, _ in book]],
               [{"video": v, **counts} for v, counts in matrix.items()])
    for c, _, _ in book:
        n = sum(1 for h in hits if h["code"] == c)
        vids = sum(1 for counts in matrix.values() if counts[c])
        print(f"{c}: {n} segments in {vids} of {len(matrix)} videos")
    return 0


# ---------- sample + alpha ----------

def sample(a) -> int:
    corpus_dir = Path(a.corpus)
    src = corpus_dir / ("coded_segments.csv" if a.from_coded else "corpus.csv")
    with open(src, encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    picked = random.Random(a.seed).sample(rows, min(a.n, len(rows)))
    coders = [f"coder_{i}" for i in range(1, a.coders + 1)]
    out = [{"unit": i, "video": r["video"], "timestamp": r["timestamp"], "text": r["text"], **{c: "" for c in coders}}
           for i, r in enumerate(picked, 1)]
    _write_csv(corpus_dir / "reliability_sample.csv", ["unit", "video", "timestamp", "text", *coders], out)
    print(f"Wrote {len(out)} units for {a.coders} coders (seed {a.seed}). Each coder fills in their own column.")
    return 0


def krippendorff_alpha_nominal(units: list[list[str]]) -> float:
    """Nominal Krippendorff's alpha. Each unit is the list of values its coders gave; '' means missing."""
    o: dict[tuple[str, str], float] = {}
    for vals in units:
        v = [x for x in vals if x != ""]
        m = len(v)
        if m < 2:
            continue  # a unit only one coder coded can't show agreement
        for i, c in enumerate(v):
            for j, k in enumerate(v):
                if i != j:
                    o[(c, k)] = o.get((c, k), 0.0) + 1.0 / (m - 1)
    n_c: dict[str, float] = {}
    for (c, _), w in o.items():
        n_c[c] = n_c.get(c, 0.0) + w
    n = sum(n_c.values())
    if n <= 1:
        raise ValueError("need at least one unit coded by two or more coders")
    d_o = sum(w for (c, k), w in o.items() if c != k)
    d_e = sum(n_c[c] * n_c[k] for c in n_c for k in n_c if c != k) / (n - 1)
    return 1.0 if d_e == 0 else 1 - d_o / d_e


def alpha(a) -> int:
    with open(a.file, encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    missing = [c for c in a.coders if rows and c not in rows[0]]
    if missing:
        print(f"Columns not found: {', '.join(missing)}", file=sys.stderr)
        return 2
    units = [[(r.get(c) or "").strip().lower() for c in a.coders] for r in rows]
    paired = sum(1 for u in units if sum(1 for x in u if x) >= 2)
    value = krippendorff_alpha_nominal(units)
    print(f"Krippendorff's alpha (nominal) = {value:.3f} over {paired} units coded by 2+ coders.")
    return 0


def main(argv: list[str] | None = None, api=call) -> int:
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    sub = p.add_subparsers(dest="cmd", required=True)
    b = sub.add_parser("build", help="fetch transcripts and export the corpus")
    b.add_argument("--videos", help="file with one video ID or URL per line (CSV: first column)")
    b.add_argument("--channel", action="append", default=[], help="@handle or channel ID (newest 100 uploads, 20 credits)")
    b.add_argument("--playlist", action="append", default=[], help="playlist ID or URL (up to 100 videos, 20 credits)")
    b.add_argument("--search", action="append", default=[], help="search query (up to 50 videos, 4 credits)")
    b.add_argument("--search-limit", type=int, default=50)
    b.add_argument("--sample", type=int, help="keep a random sample of this many candidate videos")
    b.add_argument("--seed", type=int, default=42, help="random seed, so the sample can be redrawn exactly")
    b.add_argument("--language", default="en")
    b.add_argument("--pseudonymize", action="store_true", help="replace channels and videos with codes")
    b.add_argument("--key-dir", help="where to write the pseudonym key (default: <out>_KEY_store_separately)")
    b.add_argument("--out", default="corpus")
    b.add_argument("--dry-run", action="store_true", help="list and sample only; fetch no transcripts")
    c = sub.add_parser("code", help="first-pass keyword coding with a codebook")
    c.add_argument("--corpus", default="corpus")
    c.add_argument("--codebook", required=True, help="CSV with columns code,terms (terms separated by |)")
    c.add_argument("--context", type=int, default=1, help="segments of context on each side")
    s = sub.add_parser("sample", help="draw a double-coding sample")
    s.add_argument("--corpus", default="corpus")
    s.add_argument("--n", type=int, default=100)
    s.add_argument("--seed", type=int, default=7)
    s.add_argument("--coders", type=int, default=2)
    s.add_argument("--from-coded", action="store_true", help="sample from coded_segments.csv instead of corpus.csv")
    k = sub.add_parser("alpha", help="Krippendorff's alpha (nominal) from coder columns")
    k.add_argument("file")
    k.add_argument("--coders", nargs="+", default=["coder_1", "coder_2"])
    a = p.parse_args(argv)
    if a.cmd == "build":
        return build(a, api)
    return {"code": code, "sample": sample, "alpha": alpha}[a.cmd](a)


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