#!/usr/bin/env python3
"""caption.py - burn word-timed captions onto a vertical Short.

usage: caption.py INPUT OUTPUT --style {clean,karaoke,pop,boxed} [--start S] [--end E]
                  [--words words.json] [--hook TEXT] [--model small.en] [--keep-ass]
Transcribes with faster-whisper (venv in tools/whisper-venv) unless --words is given.
Captions sit ~62-72% down, inside the left 82% of the frame (clear of the right 18%
and bottom 15%). Never writes over INPUT.
"""
import argparse, json, os, re, subprocess, sys, tempfile, wave
TOOLS = os.path.dirname(os.path.abspath(__file__))
VENV_PY = os.path.join(TOOLS, "whisper-venv", "bin", "python")
FF_DIRS = ["/opt/homebrew/bin", "/usr/local/bin", "/Applications/Jellyfin.app/Contents/MacOS"]
FONTS = "/System/Library/Fonts/Supplemental"
# obvious Whisper slips: (lowercase token sequence) -> replacement tokens
FIXES = [(["was", "posted", "the"], ["was", "posting", "the"]),
         (["whatever", "it", "social"], ["whatever.", "Social"]),
         (["you're", "you", "making"], ["you're", "making"])]

def tool(n):
    from shutil import which
    if which(n): return which(n)
    for d in FF_DIRS:
        if os.path.exists(os.path.join(d, n)): return os.path.join(d, n)
    sys.exit(f"{n} not found")

def transcribe(ff, src, model):
    with tempfile.TemporaryDirectory() as td:
        wav, js = os.path.join(td, "a.wav"), os.path.join(td, "w.json")
        subprocess.run([ff, "-v", "error", "-y", "-i", src, "-vn", "-ac", "1", "-ar", "16000", wav], check=True)
        code = f"""
import json,wave,numpy as np
from faster_whisper import WhisperModel
w=wave.open({wav!r});A=np.frombuffer(w.readframes(w.getnframes()),np.int16).astype(np.float32)/32768
segs,_=WhisperModel({model!r},device="cpu",compute_type="int8").transcribe(A,word_timestamps=True,vad_filter=True)
json.dump([dict(w=x.word.strip(),s=x.start,e=x.end) for s in segs for x in s.words],open({js!r},"w"))"""
        subprocess.run([VENV_PY, "-c", code], check=True)
        return json.load(open(js))

def fix(words):
    out, i = [], 0
    while i < len(words):
        for pat, rep in FIXES:
            seg = [re.sub(r"[^\w']", "", w["w"].lower()) for w in words[i:i+len(pat)]]
            if seg == pat:
                ws = words[i:i+len(pat)]
                for k, r in enumerate(rep):
                    b = ws[min(k, len(ws)-1)]
                    out.append(dict(w=r, s=b["s"], e=ws[-1]["e"] if k == len(rep)-1 else b["e"]))
                i += len(pat); break
        else:
            out.append(words[i]); i += 1
    return out

def group(words, maxw, maxc):
    gs, cur = [], []
    for w in words:
        if cur and (len(cur) >= maxw or len(" ".join(x["w"] for x in cur + [w])) > maxc
                    or w["s"] - cur[-1]["e"] > 0.45):
            gs.append(cur); cur = []
        cur.append(w)
        if re.search(r"[.?!,]$", w["w"]) and len(cur) >= (1 if maxw <= 2 else 2):
            gs.append(cur); cur = []
    if cur: gs.append(cur)
    return gs

def t(x):
    x = max(0, x); h = int(x // 3600); m = int(x % 3600 // 60); s = x % 60
    return f"{h}:{m:02d}:{s:05.2f}"

def esc(s): return s.replace("{", "(").replace("}", ")").replace("\\", "")

def build_ass(words, W, H, style, hook):
    x, y = int(W * 0.41), int(H * 0.67)   # centre of the left 82%
    fs = int(H * 0.042); ol = max(4, int(fs * 0.07))
    sty = {
      "clean":   f"Cap,Impact,{fs},&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,1,0,1,{ol},0,5,0,0,0,1",
      "karaoke": f"Cap,Impact,{fs},&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,1,0,1,{ol},0,5,0,0,0,1",
      "pop":     f"Cap,Impact,{int(fs*1.55)},&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,1,0,1,{int(ol*1.4)},0,5,0,0,0,1",
      "boxed":   f"Cap,Helvetica,{int(fs*0.85)},&H00FFFFFF,&H00FFFFFF,&H70000000,&H70000000,-1,0,0,0,100,100,0,0,3,{int(fs*0.25)},0,5,0,0,0,1",
    }[style]
    head = f"""[Script Info]
ScriptType: v4.00+
PlayResX: {W}
PlayResY: {H}
WrapStyle: 2
ScaledBorderAndShadow: yes

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: {sty}
Style: Hook,Impact,{int(H*0.05)},&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,1,0,1,{ol},0,8,{int(W*0.05)},{int(W*0.18)},{int(H*0.14 - H*0.025)},1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
"""
    up = style != "boxed"
    cap = (lambda s: s.upper()) if up else (lambda s: s)
    maxw, maxc = {"clean": (4, 16), "karaoke": (4, 16), "pop": (2, 10), "boxed": (4, 22)}[style]
    gs = group(words, maxw, maxc)
    ev, pos = [], f"{{\\an5\\pos({x},{y})}}"
    for i, g in enumerate(gs):
        st = g[0]["s"]; nxt = gs[i+1][0]["s"] if i + 1 < len(gs) else g[-1]["e"] + 0.4
        en = min(nxt, g[-1]["e"] + 0.6)
        txt = [esc(cap(w["w"])) for w in g]
        if style == "karaoke":
            for k, w in enumerate(g):
                ws = w["s"] if k else st
                we = g[k+1]["s"] if k + 1 < len(g) else en
                line = " ".join((r"{\c&H00FFFF&}" + s + r"{\c&HFFFFFF&}") if j == k else s for j, s in enumerate(txt))
                ev.append(f"Dialogue: 0,{t(ws)},{t(we)},Cap,,0,0,0,,{pos}{line}")
        elif style == "pop":
            ev.append(f"Dialogue: 0,{t(st)},{t(en)},Cap,,0,0,0,,{pos}{{\\fscx80\\fscy80\\t(0,90,\\fscx112\\fscy112)\\t(90,170,\\fscx100\\fscy100)}}{' '.join(txt)}")
        else:
            ev.append(f"Dialogue: 0,{t(st)},{t(en)},Cap,,0,0,0,,{pos}{' '.join(txt)}")
    if hook:
        end = max(w["e"] for w in words) + 1 if words else 60
        ev.append(f"Dialogue: 1,{t(0)},{t(end)},Hook,,0,0,0,,{esc(hook.upper())}")
    return head + "\n".join(ev) + "\n"

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("input"); ap.add_argument("output")
    ap.add_argument("--style", required=True, choices=["clean", "karaoke", "pop", "boxed"])
    ap.add_argument("--start", type=float, default=0); ap.add_argument("--end", type=float)
    ap.add_argument("--words", help="cached word-timestamp JSON (times relative to full INPUT)")
    ap.add_argument("--hook", help="optionally preview the top hook text too")
    ap.add_argument("--model", default="small.en"); ap.add_argument("--keep-ass", action="store_true")
    a = ap.parse_args()
    if os.path.abspath(a.input) == os.path.abspath(a.output): sys.exit("refusing to overwrite input")
    ff, fp = tool("ffmpeg"), tool("ffprobe")
    v = json.loads(subprocess.run([fp, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
                                   "-of", "json", a.input], capture_output=True, text=True, check=True).stdout)["streams"][0]
    W, H = v["width"], v["height"]
    words = json.load(open(a.words)) if a.words else transcribe(ff, a.input, a.model)
    words = fix(words)
    end = a.end if a.end is not None else 1e9
    words = [dict(w, s=w["s"] - a.start, e=min(w["e"], end) - a.start) for w in words if w["s"] >= a.start and w["s"] < end]
    ass = os.path.splitext(a.output)[0] + ".ass"
    open(ass, "w").write(build_ass(words, W, H, a.style, a.hook))
    cmd = [ff, "-hide_banner", "-loglevel", "error", "-stats", "-y", "-ss", str(a.start)]
    if a.end is not None: cmd += ["-t", str(a.end - a.start)]
    vf = "ass=" + ass.replace(":", r"\:").replace("'", r"\'").replace(" ", r"\ ") + ":fontsdir=" + FONTS
    cmd += ["-i", a.input, "-vf", vf, "-c:v", "libx264", "-preset", "fast", "-crf", "20", "-pix_fmt", "yuv420p",
            "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", a.output]
    subprocess.run(cmd, check=True)
    if not a.keep_ass: os.remove(ass)
    print("wrote", a.output)

if __name__ == "__main__": main()
