#!/usr/bin/env python3
"""Dub an .srt file or a dialogue sheet with the VieNeu API, one job per line.

Use this instead of POST /v1/srt when you need a cloned voice (clone_...) or a
different voice per line. Standard library only, plus ffmpeg on PATH.

    export VIENEU_API_KEY=vn_sk_...
    python dub_with_api.py episode.srt --voice "clone_..." -o episode.wav
    python dub_with_api.py sheet.csv -o episode.wav

A dialogue sheet is a UTF-8 CSV with the header  start,end,voice,text  where
start/end are timecodes (00:01:02.500) or seconds (62.5). An SRT-style
timecode with a comma (00:01:02,500) must be quoted, or CSV splits it in two.

Re-running the same file is safe: every line is sent with an Idempotency-Key
derived from the file and the line, so a line that was already submitted is
answered with its existing job instead of being charged again.
"""

import argparse
import array
import csv
import hashlib
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request
import uuid
import wave

BASE_URL = os.environ.get("VIENEU_BASE_URL", "https://api.vieneu.io/api/v1").rstrip("/")
API_KEY = os.environ.get("VIENEU_API_KEY", "")
RATE = 48000              # every clip is decoded to 48 kHz mono 16-bit
MAX_IN_FLIGHT = 20        # the account-wide cap is 30 queued+processing jobs; leave room
POLL_EVERY_S = 3
POLL_BATCH = 50           # GET /v1/tts?ids= takes at most 50 ids
TRIES = 2                 # a failed job is refunded; send it once more under a new key

TIME_RE = re.compile(r"(\d+):(\d{2}):(\d{2})[,.](\d{1,3})")


def to_ms(value: str) -> int:
    value = value.strip()
    m = TIME_RE.fullmatch(value)
    if m:
        h, mi, s, frac = m.groups()
        return ((int(h) * 60 + int(mi)) * 60 + int(s)) * 1000 + int(frac.ljust(3, "0"))
    return round(float(value) * 1000)


def read_srt(path: str, voice: str) -> list[dict]:
    text = open(path, encoding="utf-8-sig").read().replace("\r\n", "\n")
    lines = []
    for block in re.split(r"\n\s*\n", text.strip()):
        rows = block.split("\n")
        for i, row in enumerate(rows):
            if "-->" in row:
                start, end = (to_ms(t.split()[0]) for t in row.split("-->"))
                spoken = " ".join(r.strip() for r in rows[i + 1:] if r.strip())
                spoken = re.sub(r"<[^>]+>|\{[^}]+\}", "", spoken).strip()
                if spoken:
                    lines.append({"start": start, "end": end, "voice": voice, "text": spoken})
                break
    return lines


def read_sheet(path: str, default_voice: str | None) -> list[dict]:
    lines = []
    with open(path, encoding="utf-8-sig", newline="") as f:
        for row in csv.DictReader(f):
            voice = (row.get("voice") or "").strip() or default_voice
            text = (row.get("text") or "").strip()
            if not text:
                continue
            if not voice:
                sys.exit(f"row {len(lines) + 2}: no voice (add a voice column or --voice)")
            lines.append({"start": to_ms(row["start"]), "end": to_ms(row["end"]),
                          "voice": voice, "text": text})
    return lines


def api(method: str, path: str, body: dict | None = None, headers: dict | None = None):
    """One call to the API. Returns (status, json, headers); never raises on HTTP errors."""
    req = urllib.request.Request(
        BASE_URL + path, method=method,
        data=json.dumps(body).encode() if body is not None else None,
        headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json",
                 "User-Agent": "vieneu-dub-recipe/1.0", **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return r.status, json.loads(r.read() or b"{}"), r.headers
    except urllib.error.HTTPError as e:
        raw = e.read()
        try:
            data = json.loads(raw)
        except ValueError:
            data = {"message": raw[:200].decode("utf-8", "replace")}
        return e.code, data, e.headers


def wait_hint(headers, data, default: float) -> float:
    try:
        return float(headers.get("Retry-After") or data.get("retryAfterSeconds") or default)
    except (TypeError, ValueError, AttributeError):
        return default


def submit(line: dict, key: str) -> dict:
    """POST /v1/tts with retries. Every retry reuses the SAME Idempotency-Key."""
    body = {"text": line["text"], "voiceId": line["voice"]}
    for attempt in range(8):
        try:
            status, data, headers = api("POST", "/tts", body, {"Idempotency-Key": key})
        except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
            status, data, headers = 0, {"message": str(e)}, {}
        if status in (200, 201, 202):
            return data
        if status == 429 or status == 409 or status >= 500 or status == 0:
            # 429: queue full (USER_QUEUE_FULL) or rate limit. 409: the same key
            # is still being processed. 5xx / network: unknown, so retry the key.
            time.sleep(wait_hint(headers, data, min(2 ** attempt, 30)))
            continue
        err = data.get("error") if isinstance(data.get("error"), dict) else data
        sys.exit(f"line {line['n']}: HTTP {status}: {err.get('message', data)}")
    sys.exit(f"line {line['n']}: still refused after 8 tries; re-run later (nothing is charged twice)")


def download(url: str, dest: str) -> None:
    # A presigned storage URL: no Authorization header, the key must not travel there.
    with urllib.request.urlopen(url, timeout=120) as r, open(dest, "wb") as f:
        f.write(r.read())


def synthesize(lines: list[dict], run_id: str, workdir: str) -> None:
    waiting = list(lines)            # not yet submitted
    in_flight: dict[str, dict] = {}  # jobId -> line
    while waiting or in_flight:
        while waiting and len(in_flight) < MAX_IN_FLIGHT:
            line = waiting.pop(0)
            # Same file + same line + same try -> same key, so a re-run replays the
            # jobs it already paid for. The try number gives a failed line a new key:
            # replaying a key returns the job it made, failed or not.
            seed = f"{run_id}|{line['n']}|{line['voice']}|{line['text']}|{line['try']}"
            key = "dub-" + hashlib.sha256(seed.encode()).hexdigest()[:40]
            job = submit(line, key)
            if job.get("status") == "completed" and job.get("audioUrl"):
                finish(line, job["audioUrl"], workdir)  # served from cache, nothing to poll
            else:
                in_flight[job["jobId"]] = line
        ids = list(in_flight)
        for i in range(0, len(ids), POLL_BATCH):
            chunk = ids[i:i + POLL_BATCH]
            status, data, _ = api("GET", "/tts?ids=" + ",".join(chunk))
            if status != 200:
                continue  # try again on the next round
            for job in data.get("jobs", []):
                line = in_flight.get(job["jobId"])
                if not line:
                    continue
                if job["status"] == "completed":
                    finish(line, job["audioUrl"], workdir)
                    del in_flight[job["jobId"]]
                elif job["status"] == "failed":
                    del in_flight[job["jobId"]]
                    line["try"] += 1
                    if line["try"] < TRIES:
                        waiting.append(line)
                    else:
                        line["error"] = job.get("error") or "failed"
        done = sum(1 for l in lines if "pcm" in l or "error" in l)
        print(f"\r{done}/{len(lines)} lines ready, {len(in_flight)} in flight", end="", flush=True)
        if in_flight:
            time.sleep(POLL_EVERY_S)
    print()


def decode(src: str, tempo: float = 1.0) -> bytes:
    """Any audio file -> raw 48 kHz mono s16le, optionally sped up with atempo."""
    cmd = ["ffmpeg", "-v", "error", "-i", src]
    if tempo > 1.0:
        cmd += ["-filter:a", f"atempo={tempo:.4f}"]
    cmd += ["-ac", "1", "-ar", str(RATE), "-f", "s16le", "-"]
    return subprocess.run(cmd, check=True, capture_output=True).stdout


def finish(line: dict, url: str, workdir: str) -> None:
    path = os.path.join(workdir, f"{line['n']:04d}.audio")
    download(url, path)
    line["file"] = path
    line["pcm"] = decode(path)


def fit_and_place(lines: list[dict], max_speed: float) -> tuple[array.array, list[dict]]:
    """Speed each clip up (at most max_speed) to fit its window, then lay it on the
    timeline at its start. A clip that still overruns pushes the next one later,
    the same rule POST /v1/srt applies; the report says where that happened."""
    track = array.array("h")
    report = []
    cursor_ms = 0
    for line in lines:
        if "pcm" not in line:
            report.append({"index": line["n"], "error": line.get("error", "no audio")})
            continue
        window = max(1, line["end"] - line["start"])
        length = len(line["pcm"]) // 2 * 1000 // RATE
        speed = 1.0
        if length > window and max_speed > 1.0:
            speed = min(length / window, max_speed)
            line["pcm"] = decode(line["file"], speed)
            length = len(line["pcm"]) // 2 * 1000 // RATE
        actual = max(line["start"], cursor_ms)
        offset = actual * RATE // 1000
        if len(track) < offset:
            track.extend(array.array("h", bytes(2 * (offset - len(track)))))
        clip = array.array("h")
        clip.frombytes(line["pcm"])
        del track[offset:]
        track.extend(clip)
        cursor_ms = actual + length
        report.append({"index": line["n"], "scheduledStartMs": line["start"],
                       "actualStartMs": actual, "windowMs": window, "durationMs": length,
                       "speed": round(speed, 3), "overflowed": actual > line["start"]})
    return track, report


def main() -> None:
    p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    p.add_argument("input", help=".srt file or .csv dialogue sheet (start,end,voice,text)")
    p.add_argument("--voice", help="voice for every line of an .srt (a clone_... id works)")
    p.add_argument("-o", "--output", default="dub.wav")
    p.add_argument("--max-speed", type=float, default=1.25,
                   help="fastest a line may be sped up to fit its window (default 1.25)")
    p.add_argument("--workdir", default="dub_parts")
    args = p.parse_args()

    if not API_KEY:
        sys.exit("Set VIENEU_API_KEY first.")
    if args.input.lower().endswith(".srt"):
        if not args.voice:
            sys.exit("An .srt has no voice column: pass --voice.")
        lines = read_srt(args.input, args.voice)
    else:
        lines = read_sheet(args.input, args.voice)
    if not lines:
        sys.exit("No lines with text found.")
    lines.sort(key=lambda l: l["start"])
    for n, line in enumerate(lines, 1):
        line["n"] = n
        line["try"] = 0

    os.makedirs(args.workdir, exist_ok=True)
    run_id = hashlib.sha256(open(args.input, "rb").read()).hexdigest()[:16]
    synthesize(lines, run_id, args.workdir)
    track, report = fit_and_place(lines, args.max_speed)

    with wave.open(args.output, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(RATE)
        w.writeframes(track.tobytes())
    report_path = os.path.splitext(args.output)[0] + ".report.json"
    with open(report_path, "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)

    failed = [r for r in report if "error" in r]
    drifted = [r for r in report if r.get("overflowed")]
    print(f"{args.output}: {len(track) / RATE:.1f} s, {len(lines) - len(failed)} lines placed")
    print(f"{len(drifted)} line(s) started late, {len(failed)} failed - see {report_path}")
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()
