#!/usr/bin/env python3
"""translate_subtitles.py: translate a YouTube video's captions into another language
and keep the timing, so the result plays in sync and can be uploaded to YouTube Studio.

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

  python translate_subtitles.py VIDEO_ID --to de
  python translate_subtitles.py VIDEO_ID --to es --to pt --out subs/
  python translate_subtitles.py --playlist PL... --to fr
  python translate_subtitles.py VIDEO_ID --to de --dry-run    # sentence count and cost, no model call

For each video and language it writes, into OUT/<video_id>/:
  <video_id>.<lang>.srt   plain UTF-8 SubRip, the format YouTube Studio recommends
  <video_id>.<lang>.vtt   WebVTT, for web players
  <video_id>.<lang>.json  report: sentences, cues, reading-speed fixes, cues still too fast, cost

Why it doesn't translate caption lines one by one: YouTube's auto captions break lines
mid-sentence and overlap each other, and other languages need a different word order.
So the script rebuilds whole sentences with word timings, translates sentences in
numbered batches (and checks the count comes back the same), then cuts each translated
sentence into cues inside that sentence's original time span. Timing never comes from
the model.

Reading speed is planned, not hoped for. Each sentence goes to the model with a
character budget: the time until the next sentence starts times the language's limit
(characters per second, spaces and punctuation counted). After layout, a cue that is
still too fast borrows time from the pause after it; if that isn't enough, the model is
asked again for a shorter wording. Anything still too fast is listed in the report so a
person can fix it.

If the video already has a caption track in the target language, that track is saved
as-is and no model call is made (use --force to translate anyway).

Cost: 1 credit per video and language (20 per playlist listing) plus the Claude calls.
Needs Python 3.10+.
"""
from __future__ import annotations

import argparse
import json
import math
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
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),
}
# Reading-speed limits for translated subtitles, adult programs, from Netflix's
# per-language Timed Text Style Guides (Dec 2026). Others default to 17.
CPS = {"en": 20, "de": 17, "es": 17, "pt": 17, "it": 17, "nl": 17, "zh": 9, "ja": 4}
LINE = {"zh": 16, "ja": 13}  # characters per line; 42 for Latin-script languages
CJK = {"zh", "ja", "ko"}
MIN_CUE, MAX_CUE, GAP = 5 / 6, 7.0, 0.083  # seconds: Netflix minimum and maximum event, 2-frame gap
VIDEO_ID = re.compile(r"(?:[?&]v=|youtu\.be/|/shorts/|/embed/|/live/)([\w-]{11})")
TAGS = re.compile(r"\[(?:music|applause|laughter|laughs|inaudible|foreign)\]|>>|&gt;&gt;", re.I)
END = re.compile(r"[.?!][\"')\]]*$")


# --------------------------------------------------------------------------- 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": "translate-subtitles/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(vid: str, key: str, language: str, api: Callable = call) -> dict:
    """One call. Asks for `language`; if the video has no such track, another comes back
    and the response's language field says which."""
    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 {}
    return {"video_id": vid, "title": meta.get("title") or vid, "language": str(data.get("language", "")),
            "segments": segs}


def base(lang: str) -> str:
    return lang.lower().replace("_", "-").split("-")[0]


# --------------------------------------------------------------------------- sentences

def words_with_times(segs: list[dict]) -> list[tuple[str, float, float]]:
    """Every word with an estimated start and end. Overlapping auto-caption lines are cut
    at the next line's start; time inside a line is shared out by character count."""
    out: list[tuple[str, float, float]] = []
    for i, s in enumerate(segs):
        text = re.sub(r"\s+", " ", TAGS.sub(" ", str(s["text"]))).strip()
        if not text:
            continue
        start = float(s["start"])
        end = start + float(s.get("duration") or 0)
        if i + 1 < len(segs):
            end = min(end, float(segs[i + 1]["start"]))
        end = max(end, start + 0.2)
        words = text.split(" ")
        total = sum(len(w) + 1 for w in words)
        t = start
        for w in words:
            d = (end - start) * (len(w) + 1) / total
            out.append((w, t, t + d))
            t += d
    return out


def sentences(segs: list[dict], max_words: int = 40, pause: float = 1.5) -> list[dict]:
    """Join words into sentences: end at . ? !, at a pause longer than `pause` seconds,
    or after `max_words` words (auto captions without punctuation)."""
    out, cur = [], []
    words = words_with_times(segs)
    for i, (w, s, e) in enumerate(words):
        cur.append((w, s, e))
        nxt = words[i + 1][1] if i + 1 < len(words) else None
        if END.search(w) or len(cur) >= max_words or nxt is None or nxt - e > pause:
            out.append({"text": " ".join(x[0] for x in cur), "start": round(cur[0][1], 3), "end": round(cur[-1][2], 3)})
            cur = []
    return out


# --------------------------------------------------------------------------- translation

SCHEMA = {
    "type": "object",
    "properties": {"translations": {"type": "array", "items": {"type": "string"}}},
    "required": ["translations"],
    "additionalProperties": False,
}


def system_prompt(target: str) -> str:
    return (f"You translate video subtitles into {target}. You get numbered sentences from one video, in order. "
            "Return exactly one translation per numbered sentence, in the same order: never merge, split, skip or "
            "renumber. Write natural spoken subtitles, not literal glosses, and keep them as short as the meaning "
            "allows, because viewers read them in a few seconds. Keep names, brands and code as they are. Captions "
            "may mishear words; translate what was most likely said. Lines marked as context are already done: use "
            "them for meaning only.")


class Claude:
    """Calls Claude with structured output. Swap in any object with the same two methods."""

    def __init__(self, client, model: str = MODEL, effort: str = "medium"):
        self.client, self.model, self.effort = client, model, effort
        self.usage = {"input_tokens": 0, "output_tokens": 0}

    def _ask(self, system: str, prompt: str) -> list[str]:
        with self.client.beta.messages.stream(
            model=self.model,
            max_tokens=32000,
            betas=["server-side-fallback-2026-07-01"],
            fallbacks="default",  # re-run a refused request on Anthropic's recommended fallback model
            output_config={"effort": self.effort, "format": {"type": "json_schema", "schema": SCHEMA}},
            system=system,
            messages=[{"role": "user", "content": prompt}],
        ) as stream:
            msg = stream.get_final_message()
        self.usage["input_tokens"] += msg.usage.input_tokens
        self.usage["output_tokens"] += msg.usage.output_tokens
        if msg.stop_reason == "refusal":
            raise RuntimeError(f"the model declined this text ({getattr(msg.stop_details, 'category', None)})")
        if msg.stop_reason == "max_tokens":
            return []  # treated as a count mismatch: the batch is split and retried
        return json.loads(next(b.text for b in msg.content if b.type == "text"))["translations"]

    def translate(self, items: list[str], target: str, context: list[tuple[str, str]],
                  budgets: list[int] | None = None) -> list[str]:
        ctx = "".join(f"(context) {s}\n  -> {t}\n" for s, t in context)
        budgets = budgets or [0] * len(items)
        nums = "".join(f"{i + 1}. " + (f"[max {b} characters] " if b else "") + f"{s}\n"
                       for i, (s, b) in enumerate(zip(items, budgets)))
        return self._ask(system_prompt(target),
                         f"{ctx}\nTranslate these {len(items)} sentences. Where a sentence has a character budget, "
                         f"it is how much a viewer can read in the time it is on screen: stay within it, condensing "
                         f"if you must, but keep the meaning.\n{nums}")

    def condense(self, items: list[tuple[str, str, int]], target: str) -> list[str]:
        rows = "".join(f"{i + 1}. source: {s}\n   current: {t}\n   budget: {n} characters\n"
                       for i, (s, t, n) in enumerate(items))
        return self._ask(system_prompt(target),
                         f"These {target} subtitles are too long to read in the time they are on screen. Rewrite "
                         f"each one in {target} to fit its character budget (spaces and punctuation count), keeping "
                         f"the meaning; drop filler first. Return {len(items)} lines in order.\n{rows}")


def budgets(sents: list[dict], cps: float) -> list[int]:
    """Characters a viewer can read for each sentence: the time until the next sentence
    starts (at most 7 s per cue the sentence needs) times the reading-speed limit."""
    out = []
    for i, s in enumerate(sents):
        nxt = sents[i + 1]["start"] if i + 1 < len(sents) else s["end"] + MAX_CUE
        span = s["end"] - s["start"]
        avail = min(nxt - GAP, s["start"] + MAX_CUE * max(1, math.ceil(span / MAX_CUE))) - s["start"]
        out.append(max(8, int(max(avail, MIN_CUE) * cps)))
    return out


def translate_all(sents: list[dict], target: str, tr, batch: int = 40, log: list | None = None,
                  cps: float | None = None) -> list[str]:
    """Numbered batches with 3 sentences of context and a character budget per sentence.
    If the count that comes back is wrong, the batch is halved and retried, down to one."""
    out: list[str] = []
    room = budgets(sents, cps) if cps else [0] * len(sents)
    queue = [list(range(i, min(i + batch, len(sents)))) for i in range(0, len(sents), batch)]
    while queue:
        idx = queue.pop(0)
        start = len(out)
        ctx = [(sents[j]["text"], out[j]) for j in range(max(0, start - 3), start)]
        got = tr.translate([sents[j]["text"] for j in idx], target, ctx, [room[j] for j in idx])
        if len(got) == len(idx) and all(str(g).strip() for g in got):
            out.extend(str(g).strip() for g in got)
            continue
        if log is not None:
            log.append(f"batch of {len(idx)} came back with {len(got)}; retrying smaller")
        if len(idx) == 1:
            raise RuntimeError(f"sentence {idx[0] + 1} did not translate")
        half = len(idx) // 2
        queue[:0] = [idx[:half], idx[half:]]
    return out


# --------------------------------------------------------------------------- cues

def length(text: str, lang: str) -> float:
    """Reading-speed length: spaces and punctuation count. In Chinese and Japanese,
    half-width characters count as half (Netflix's rule)."""
    t = text.replace("\n", " ")
    if base(lang) in {"zh", "ja"}:
        return sum(0.5 if ord(c) < 0x2E80 else 1.0 for c in t)
    return float(len(t))


def chunks(text: str, max_len: int, lang: str) -> list[str]:
    """Split a sentence into pieces of at most max_len, at word boundaries (characters
    for Chinese and Japanese), preferring breaks after punctuation."""
    if length(text, lang) <= max_len:
        return [text]
    if base(lang) in CJK and " " not in text.strip():
        n = math.ceil(length(text, lang) / max_len)
        size = math.ceil(len(text) / n)
        return [text[i:i + size] for i in range(0, len(text), size)]
    words, out, cur = text.split(), [], ""
    n = math.ceil(len(text) / max_len)
    target = len(text) / n
    for w in words:
        cand = f"{cur} {w}".strip()
        if cur and (len(cand) > max_len or (len(cur) >= target * 0.8 and re.search(r"[,;:]$", cur))):
            out.append(cur)
            cur = w
        else:
            cur = cand
    if cur:
        out.append(cur)
    return out


def wrap(text: str, line: int, lang: str) -> str:
    """At most two lines, broken as evenly as the words allow."""
    if length(text, lang) <= line:
        return text
    if base(lang) in CJK and " " not in text:
        mid = math.ceil(len(text) / 2)
        return text[:mid] + "\n" + text[mid:]
    words = text.split()
    best, best_score = text, 1e9
    for i in range(1, len(words)):
        a, b = " ".join(words[:i]), " ".join(words[i:])
        if len(a) <= line and len(b) <= line:
            score = abs(len(a) - len(b))
            if score < best_score:
                best, best_score = a + "\n" + b, score
    return best


def fits(text: str, line: int, lang: str) -> bool:
    return all(length(x, lang) <= line for x in wrap(text, line, lang).split("\n"))


def split_to_fit(text: str, line: int, lang: str) -> list[str]:
    """Split until every piece wraps onto two lines of `line` characters."""
    if fits(text, line, lang):
        return [text]
    parts = chunks(text, max(8, math.ceil(length(text, lang) / 2)), lang)
    if len(parts) == 1:
        return parts  # a single word longer than a line (a URL); leave it
    return [q for p in parts for q in split_to_fit(p, line, lang)]


def layout(sents: list[dict], texts: list[str], lang: str) -> list[dict]:
    """Cut each translated sentence into cues inside its own time span, shared by length."""
    line = LINE.get(base(lang), 42)
    cues = []
    for k, (s, t) in enumerate(zip(sents, texts)):
        span = max(s["end"] - s["start"], MIN_CUE)
        n_dur = math.ceil(span / MAX_CUE)
        pieces = chunks(t, 2 * line, lang)
        if len(pieces) < n_dur:
            pieces = chunks(t, max(8, math.ceil(length(t, lang) / n_dur)), lang)
        pieces = [q for p in pieces for q in split_to_fit(p, line, lang)]
        total = sum(length(p, lang) for p in pieces) or 1
        at = s["start"]
        for p in pieces:
            d = span * length(p, lang) / total
            cues.append({"sentence": k, "text": wrap(p, line, lang), "start": at, "end": at + d})
            at += d
    return cues


def _join(a: str, b: str, lang: str) -> str:
    a, b = a.replace("\n", " "), b.replace("\n", " ")
    return a + b if base(lang) in CJK and " " not in a + b else f"{a} {b}"


def merge_short(cues: list[dict], lang: str) -> None:
    """A cue with under 5/6 s before the next one starts is merged into a neighbour when
    the text still fits on two lines and the result stays under 7 s."""
    line = LINE.get(base(lang), 42)
    i = 0
    while i < len(cues) - 1:
        a, b = cues[i], cues[i + 1]
        if b["start"] - GAP - a["start"] >= MIN_CUE:
            i += 1
            continue
        joined = _join(a["text"], b["text"], lang)
        if fits(joined, line, lang) and b["end"] - a["start"] <= MAX_CUE:
            a["text"], a["end"] = wrap(joined, line, lang), max(a["end"], b["end"])
            del cues[i + 1]
            continue
        if i > 0:
            p = cues[i - 1]
            joined = _join(p["text"], a["text"], lang)
            if fits(joined, line, lang) and a["end"] - p["start"] <= MAX_CUE:
                p["text"], p["end"] = wrap(joined, line, lang), max(p["end"], a["end"])
                del cues[i]
                i -= 1
                continue
        if b["start"] - GAP - a["start"] < 0.3:  # rare: nudge the next cue so nothing overlaps
            b["start"] = a["start"] + 0.3 + GAP
            b["end"] = max(b["end"], b["start"] + 0.3)
        i += 1


def fit_times(cues: list[dict], lang: str, cps: float) -> None:
    """Keep cues in order and within limits: no overlap, at least 5/6 s where there is room,
    at most 7 s. A cue that reads too fast borrows time from the gap before the next cue."""
    merge_short(cues, lang)
    for i, c in enumerate(cues):
        nxt = cues[i + 1]["start"] - GAP if i + 1 < len(cues) else c["end"] + MAX_CUE
        want = c["start"] + max(MIN_CUE, length(c["text"], lang) / cps)
        if c["end"] < want:
            c["end"] = min(want, nxt, c["start"] + MAX_CUE)
        c["end"] = max(min(c["end"], c["start"] + MAX_CUE), c["start"] + 0.3)
        if i + 1 < len(cues):
            c["end"] = min(c["end"], cues[i + 1]["start"] - GAP)


def too_fast(cues: list[dict], lang: str, cps: float) -> list[int]:
    return [i for i, c in enumerate(cues) if length(c["text"], lang) / max(c["end"] - c["start"], 0.01) > cps + 0.05]


def build(sents: list[dict], texts: list[str], lang: str, cps: float, tr=None, target: str = "",
          rounds: int = 2) -> tuple[list[dict], list[str], dict]:
    """Lay out cues, fix reading speed, and ask for shorter wording where time runs out."""
    texts = list(texts)
    stats = {"condensed": 0}
    cues = layout(sents, texts, lang)
    stats["too_fast_before_fix"] = len(too_fast(cues, lang, cps))
    fit_times(cues, lang, cps)
    for _ in range(rounds if tr else 0):
        bad = sorted({cues[i]["sentence"] for i in too_fast(cues, lang, cps)})
        if not bad:
            break
        items = []
        for k in bad:
            room = [c for c in cues if c["sentence"] == k]
            nxt = next((c["start"] for c in cues if c["sentence"] > k), room[-1]["end"] + MAX_CUE)
            avail = min(nxt - GAP, room[0]["start"] + MAX_CUE * len(room)) - room[0]["start"]
            items.append((sents[k]["text"], texts[k], max(8, int(avail * cps))))
        for n in range(0, len(items), 40):  # batches of 40; a batch that comes back wrong is skipped
            short = tr.condense(items[n:n + 40], target)
            if len(short) != len(items[n:n + 40]):
                continue
            for k, new in zip(bad[n:n + 40], short):
                if str(new).strip() and length(new, lang) < length(texts[k], lang):
                    texts[k] = str(new).strip()
                    stats["condensed"] += 1
        cues = layout(sents, texts, lang)
        fit_times(cues, lang, cps)
    stats["too_fast_after_fix"] = len(too_fast(cues, lang, cps))
    return cues, texts, stats


# --------------------------------------------------------------------------- files

def stamp(sec: float, sep: str) -> str:
    ms = int(round(max(sec, 0) * 1000))
    h, ms = divmod(ms, 3600000)
    m, ms = divmod(ms, 60000)
    s, ms = divmod(ms, 1000)
    return f"{h:02d}:{m:02d}:{s:02d}{sep}{ms:03d}"


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


def to_vtt(cues: list[dict]) -> str:
    return "WEBVTT\n\n" + "".join(f"{stamp(c['start'], '.')} --> {stamp(c['end'], '.')}\n{c['text']}\n\n" for c in cues)


def segments_to_cues(segs: list[dict], lang: str) -> list[dict]:
    """An existing track saved as-is (overlaps trimmed, two lines at most)."""
    line, cues = LINE.get(base(lang), 42), []
    for i, s in enumerate(segs):
        start = float(s["start"])
        end = start + float(s.get("duration") or 0)
        if i + 1 < len(segs):
            end = min(end, float(segs[i + 1]["start"]) - GAP)
        text = re.sub(r"\s+", " ", str(s["text"])).strip()
        if text and end > start:
            cues.append({"text": wrap(text, line, lang), "start": start, "end": end})
    return cues


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 video

def run_video(vid: str, targets: list[str], key: str, a, api: Callable, tr) -> list[dict]:
    reports = []
    folder = Path(a.out) / vid
    source = None
    for target in targets:
        lang = base(target)
        cps = a.cps or CPS.get(lang, 17)
        if a.force:
            source = source or fetch(vid, key, a.source, api)
        else:
            got = fetch(vid, key, target, api)  # 1 credit; also tells us if a target track exists
            if base(got["language"]) == lang:
                cues = segments_to_cues(got["segments"], lang)
                folder.mkdir(parents=True, exist_ok=True)
                (folder / f"{vid}.{lang}.srt").write_text(to_srt(cues), encoding="utf-8")
                (folder / f"{vid}.{lang}.vtt").write_text(to_vtt(cues), encoding="utf-8")
                reports.append({"video_id": vid, "target": lang, "existing_track": True, "cues": len(cues)})
                print(f"{vid} [{lang}]: the video already has a {lang} track; saved it as-is (no model call)")
                continue
            source = got
        sents = sentences(source["segments"])
        words = sum(len(s["text"].split()) for s in sents)
        if a.dry_run:
            # Rough: ~1.6 input tokens per source word (sentences, context, prompt) and ~2 output
            # tokens per word; thinking tokens and the shortening pass come on top.
            batches = math.ceil(len(sents) / a.batch)
            est = {"input_tokens": int(words * 1.6) + 300 * batches, "output_tokens": int(words * 2.0)}
            print(f"{vid} [{source['language']}->{lang}]: {len(source['segments'])} caption lines -> {len(sents)} sentences, "
                  f"{words:,} words, roughly ${cost(est, a.model):.2f} with {a.model} before thinking tokens  "
                  f"{source['title'][:50]}")
            reports.append({"video_id": vid, "target": lang, "dry_run": True, "sentences": len(sents)})
            continue
        log: list[str] = []
        before = dict(tr.usage) if hasattr(tr, "usage") else {"input_tokens": 0, "output_tokens": 0}
        texts = translate_all(sents, target, tr, a.batch, log, cps)
        cues, texts, stats = build(sents, texts, lang, cps, tr, target)
        used = {k: (tr.usage[k] - before[k]) if hasattr(tr, "usage") else 0 for k in before}
        slow = [{"at": stamp(c["start"], "."), "text": c["text"].replace("\n", " "),
                 "cps": round(length(c["text"], lang) / max(c["end"] - c["start"], 0.01), 1)}
                for c in (cues[i] for i in too_fast(cues, lang, cps))]
        report = {"video_id": vid, "title": source["title"], "source_language": source["language"], "target": lang,
                  "cps_limit": cps, "caption_lines": len(source["segments"]), "sentences": len(sents),
                  "cues": len(cues), **stats, "still_too_fast": slow, "retries": log,
                  "usage": used, "cost_usd": round(cost(used, a.model), 4)}
        folder.mkdir(parents=True, exist_ok=True)
        (folder / f"{vid}.{lang}.srt").write_text(to_srt(cues), encoding="utf-8")
        (folder / f"{vid}.{lang}.vtt").write_text(to_vtt(cues), encoding="utf-8")
        (folder / f"{vid}.{lang}.json").write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
        print(f"{vid} [{source['language']}->{lang}]: {len(sents)} sentences -> {len(cues)} cues, "
              f"{stats['condensed']} shortened, {len(slow)} still over {cps} chars/s, ${report['cost_usd']:.3f} -> {folder}")
        reports.append(report)
    return reports


def main(argv: list[str] | None = None, api: Callable = call, tr=None) -> int:
    p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    p.add_argument("videos", nargs="*", help="video links or IDs")
    p.add_argument("--to", action="append", required=True, help="target language code, e.g. de, es, pt-BR (repeatable)")
    p.add_argument("--playlist", help="every video in a playlist (up to 100, 20 credits)")
    p.add_argument("--source", default="en", help="source caption language to ask for with --force (default en)")
    p.add_argument("--force", action="store_true", help="translate even if a track in the target language exists")
    p.add_argument("--out", default="translated")
    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("--batch", type=int, default=40, help="sentences per request (default 40)")
    p.add_argument("--cps", type=float, help="reading-speed limit in characters per second (default per language)")
    p.add_argument("--dry-run", action="store_true", help="fetch captions 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 tr is None and not a.dry_run:
        import anthropic  # imported here so --dry-run works without it
        tr = Claude(anthropic.Anthropic(), a.model, a.effort)
    failed, total = 0, 0.0
    for vid in vids:
        try:
            for r in run_video(vid, a.to, key, a, api, tr):
                total += r.get("cost_usd", 0.0)
        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
        except RuntimeError as e:
            failed += 1
            print(f"{vid}: {e}", file=sys.stderr)
    if not a.dry_run:
        print(f"Done: {len(vids) - failed} of {len(vids)} videos, model cost ${total:.3f} plus 1 credit per transcript.")
    return 0 if failed < len(vids) else 3


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