#!/usr/bin/env python3
"""chat_clips.py - find the best moments of a Twitch stream from chat spikes
and cut them as vertical 9:16 clips.

Usage:
    python chat_clips.py chat.json stream.mp4
    python chat_clips.py chat.json stream.mp4 -n 8 --length 60 -o my_clips

chat.json is the JSON chat export from TwitchDownloader.
Needs only the Python standard library plus ffmpeg/ffprobe on PATH.
"""

import argparse
import json
import re
import shutil
import subprocess
import sys
from collections import Counter
from pathlib import Path

# Words too common to say anything about a moment.
STOPWORDS = set("""
a an and are as at be but by for from had has have he her him his i if im in is it its
just me my no not of on or our she so that the their them they this to up us was we
were what when who will with you your u ur dont cant thats too do did does can get got
all out about how why there here then than been would could should one like yes yeah
""".split())

WORD_RE = re.compile(r"[^\W_]+(?:'[^\W_]+)?", re.UNICODE)


def fail(msg):
    print(f"ERROR: {msg}", file=sys.stderr)
    sys.exit(1)


def fmt_time(seconds):
    """3725 -> '1:02:05' (for people)."""
    s = int(seconds)
    return f"{s // 3600}:{s % 3600 // 60:02d}:{s % 60:02d}"


def fmt_name(seconds):
    """3725 -> '01h02m05s' (for file names)."""
    s = int(seconds)
    return f"{s // 3600:02d}h{s % 3600 // 60:02d}m{s % 60:02d}s"


def load_chat(path):
    """Return a sorted list of (offset_seconds, message_text)."""
    try:
        with open(path, "r", encoding="utf-8-sig") as f:
            data = json.load(f)
    except (OSError, json.JSONDecodeError) as e:
        fail(f"cannot read chat file {path}: {e}")

    comments = data.get("comments") if isinstance(data, dict) else None
    if not isinstance(comments, list):
        fail("chat file has no 'comments' list - is it a TwitchDownloader JSON export?")

    messages = []
    for c in comments:
        if not isinstance(c, dict):
            continue
        offset = c.get("content_offset_seconds")
        if not isinstance(offset, (int, float)) or offset < 0:
            continue
        msg = c.get("message") or {}
        body = msg.get("body")
        if not isinstance(body, str):  # fall back to the fragment texts
            frags = msg.get("fragments") or []
            body = "".join(fr.get("text") or "" for fr in frags if isinstance(fr, dict))
        messages.append((float(offset), body))
    if not messages:
        fail("no chat messages found in the chat file")
    messages.sort(key=lambda m: m[0])
    return messages


def probe_duration(video):
    """Video length in seconds (None if ffprobe cannot tell)."""
    try:
        out = subprocess.run(
            ["ffprobe", "-v", "error", "-show_entries", "format=duration",
             "-of", "default=noprint_wrappers=1:nokey=1", str(video)],
            capture_output=True, text=True, check=True).stdout.strip()
        return float(out)
    except (subprocess.CalledProcessError, ValueError):
        return None


def find_spikes(messages, window, top_n, pre, length, duration, chat_offset):
    """Pick the top_n busiest windows whose clips do not overlap.

    Times returned are positions in the video file (chat time + chat_offset).
    """
    counts = Counter(int(t // window) for t, _ in messages)
    chosen = []
    # Busiest first; ties go to the earlier moment.
    for idx, count in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
        spike = idx * window + chat_offset          # spike start, in video time
        start = max(0.0, spike - pre)
        end = start + length
        if spike < 0:
            continue
        if duration is not None:
            if spike >= duration:
                continue                             # chat goes past the video
            end = min(end, duration)
            if end - start < length:                 # near the end: slide back
                start = max(0.0, end - length)
        if any(start < c["end"] and c["start"] < end for c in chosen):
            continue                                 # overlaps a better clip
        chosen.append({"idx": idx, "count": count, "spike": spike,
                       "start": start, "end": end})
        if len(chosen) == top_n:
            break
    return chosen


def top_words(messages, lo, hi, n=8):
    """Most used words in chat between lo and hi (chat time)."""
    words = Counter()
    for t, body in messages:
        if t < lo:
            continue
        if t >= hi:
            break
        seen = set()
        for w in WORD_RE.findall(body):
            key = w if (w.isupper() and len(w) > 1) else w.lower()  # keep emote-style caps
            if len(key) < 2 or key.lower() in STOPWORDS or key in seen:
                continue
            seen.add(key)                            # one vote per message (anti-spam)
            words[key] += 1
    return words.most_common(n)


def cut_clip(video, out_path, start, length, width, height, crf, preset):
    """Cut one clip, center-cropped to fill a width x height vertical frame."""
    vf = (f"scale={width}:{height}:force_original_aspect_ratio=increase,"
          f"crop={width}:{height},setsar=1")
    cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
           "-ss", f"{start:.3f}", "-i", str(video), "-t", f"{length:.3f}",
           "-vf", vf,
           "-c:v", "libx264", "-preset", preset, "-crf", str(crf), "-pix_fmt", "yuv420p",
           "-c:a", "aac", "-b:a", "160k",
           "-movflags", "+faststart", str(out_path)]
    r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
    if r.returncode != 0:
        return (r.stderr or "").strip().splitlines()[-1:] or ["ffmpeg failed"]
    return None


def main():
    for stream in (sys.stdout, sys.stderr):          # chat is full of emoji/unicode
        try:
            stream.reconfigure(encoding="utf-8", errors="replace")
        except (AttributeError, ValueError):
            pass

    ap = argparse.ArgumentParser(
        description="Cut vertical 9:16 clips at the biggest chat spikes of a Twitch stream.")
    ap.add_argument("chat", help="chat JSON downloaded with TwitchDownloader")
    ap.add_argument("video", help="stream video file")
    ap.add_argument("-n", "--top", type=int, default=5, help="number of clips (default 5)")
    ap.add_argument("--length", type=float, default=45, help="clip length in seconds (default 45)")
    ap.add_argument("--pre", type=float, default=20,
                    help="seconds before the spike where the clip starts (default 20)")
    ap.add_argument("--window", type=int, default=10, help="chat window in seconds (default 10)")
    ap.add_argument("-o", "--out", help="output folder (default: <video name>_clips next to the video)")
    ap.add_argument("--size", default="1080x1920", help="output size WxH (default 1080x1920)")
    ap.add_argument("--chat-offset", type=float, default=0,
                    help="seconds to add to chat times if the video file does not start at "
                         "the start of the stream (e.g. -600 if you trimmed the first 10 min)")
    ap.add_argument("--crf", type=int, default=20, help="x264 quality, lower = better (default 20)")
    ap.add_argument("--preset", default="veryfast", help="x264 speed preset (default veryfast)")
    ap.add_argument("--dry-run", action="store_true", help="only find spikes, do not cut clips")
    args = ap.parse_args()

    if args.top < 1 or args.length <= 0 or args.window < 1 or args.pre < 0:
        fail("--top, --length and --window must be positive; --pre cannot be negative")
    m = re.fullmatch(r"(\d+)[xX](\d+)", args.size)
    if not m:
        fail("--size must look like 1080x1920")
    width, height = int(m.group(1)) // 2 * 2, int(m.group(2)) // 2 * 2

    chat_path, video = Path(args.chat), Path(args.video)
    if not chat_path.is_file():
        fail(f"chat file not found: {chat_path}")
    if not video.is_file():
        fail(f"video file not found: {video}")
    for exe in ("ffmpeg", "ffprobe"):
        if not shutil.which(exe):
            fail(f"{exe} not found on PATH")

    messages = load_chat(chat_path)
    duration = probe_duration(video)
    if duration is None:
        print("WARNING: could not read the video length; clips near the end may be short.")

    spikes = find_spikes(messages, args.window, args.top, args.pre, args.length,
                         duration, args.chat_offset)
    if not spikes:
        fail("no chat spikes fall inside the video (check --chat-offset)")

    out_dir = Path(args.out) if args.out else video.with_name(video.stem + "_clips")
    out_dir.mkdir(parents=True, exist_ok=True)

    avg = len(messages) / max(1, len({int(t // args.window) for t, _ in messages}))
    lines = [
        f"Chat spikes for {video.name}",
        f"chat: {chat_path.name} | {len(messages)} messages | "
        f"{args.window}s windows | average {avg:.1f} msgs per active window",
        "",
    ]
    made, failed = 0, 0
    for rank, s in enumerate(spikes, 1):
        chat_lo = s["idx"] * args.window
        words = top_words(messages, chat_lo, chat_lo + args.window)
        word_str = ", ".join(f"{w} ({c})" for w, c in words) or "-"
        name = f"{rank:02d}_{fmt_name(s['spike'])}.mp4"
        clip_len = s["end"] - s["start"]
        status = "dry run - not cut"
        if not args.dry_run:
            print(f"[{rank}/{len(spikes)}] cutting {name} "
                  f"({fmt_time(s['start'])} - {fmt_time(s['end'])}) ...", flush=True)
            err = cut_clip(video, out_dir / name, s["start"], clip_len,
                           width, height, args.crf, args.preset)
            if err:
                failed += 1
                status = "FAILED: " + err[0]
                print("   " + status)
            else:
                made += 1
                status = "ok"
        s.update(name=name, words=word_str, status=status)
        lines += [
            f"#{rank}  {name}",
            f"  spike time : {fmt_time(s['spike'])}  ({s['count']} messages in {args.window}s)",
            f"  clip       : {fmt_time(s['start'])} - {fmt_time(s['end'])}  ({clip_len:.0f}s)",
            f"  top words  : {word_str}",
            f"  status     : {status}",
            "",
        ]

    report = out_dir / "spikes.txt"
    report.write_text("\n".join(lines), encoding="utf-8")

    print()
    print(f"Summary: {len(messages)} chat messages, {len(spikes)} spikes found"
          + ("" if args.dry_run else f", {made} clips cut" + (f", {failed} failed" if failed else "")))
    for rank, s in enumerate(spikes, 1):
        print(f"  #{rank}  {fmt_time(s['spike'])}  {s['count']:>4} msgs  {s['name']}  [{s['words']}]")
    if len(spikes) < args.top:
        print(f"  (only {len(spikes)} non-overlapping spikes fit; asked for {args.top})")
    print(f"Folder: {out_dir.resolve()}")
    print(f"List:   {report.resolve()}")
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()
