"""Cut clips from a stream VOD where chat spikes. Chat JSON comes from TwitchDownloader (chatdownload).
Usage: python chat_clips.py chat.json vod.mp4 [--bin 10] [--lead 20] [--len 45] [--k 3] [--top 10]"""
import argparse, json, os, statistics, subprocess

p = argparse.ArgumentParser()
p.add_argument("chat"); p.add_argument("vod")
p.add_argument("--bin", type=int, default=10); p.add_argument("--lead", type=int, default=20)
p.add_argument("--len", type=int, default=45); p.add_argument("--k", type=float, default=3)
p.add_argument("--top", type=int, default=10); p.add_argument("--out", default="clips")
a = p.parse_args()

times = [c["content_offset_seconds"] for c in json.load(open(a.chat, encoding="utf-8"))["comments"]]
counts = [0] * (int(max(times)) // a.bin + 1)
for t in times: counts[int(t) // a.bin] += 1
normal = statistics.median(counts) or 1
spikes = sorted((i for i, c in enumerate(counts) if c >= a.k * normal), key=lambda i: -counts[i])
picked = []
for i in spikes:  # keep the biggest spike in each window, skip overlaps
    if all(abs(i - j) * a.bin >= a.len for j in picked): picked.append(i)
picked = sorted(picked[: a.top])
print(f"{len(times)} chat messages, normal {normal:g} per {a.bin}s, {len(picked)} spikes")
os.makedirs(a.out, exist_ok=True)
for n, i in enumerate(picked, 1):
    start = max(0, i * a.bin - a.lead)  # chat reacts after the moment, so start early
    out = f"{a.out}/clip_{n:02d}.mp4"
    vf = "crop=ih*9/16:ih,scale=1080:1920"
    srt = out[:-4] + ".srt"
    subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", str(start), "-t", str(a.len), "-i", a.vod,
                    "-vf", vf, "-c:a", "aac", out], check=True)
    # captions: whisper.cpp if available, burned in
    has_audio = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0", out],
                               capture_output=True, text=True).stdout.strip()
    if has_audio and os.environ.get("WHISPER_MODEL"):
        subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", out, "-ar", "16000", "-ac", "1", out + ".wav"], check=True)
        subprocess.run(["whisper-cli", "-m", os.environ["WHISPER_MODEL"], "-f", out + ".wav", "-osrt", "-of", out[:-4], "-np"], capture_output=True)
        os.remove(out + ".wav")
        if os.path.exists(srt):
            tmp = out[:-4] + "_cc.mp4"
            subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", out, "-vf", f"subtitles={srt}:force_style='FontSize=14,Outline=2,MarginV=60'", "-c:a", "copy", tmp], check=True)
            os.replace(tmp, out)
    print(f"#{n}  {start//3600}:{start%3600//60:02d}:{start%60:02d}  {counts[i]} msgs/{a.bin}s  {counts[i]/normal:.1f}x  -> {out}")
