#!/usr/bin/env python3
"""join_cuts.py — let every take finish its last word before the cut (AUDIO_MODE=vocal-swap).

Each cut sits where the RECORD's next line starts, but a take sings its line its own way
— ~10 % slow on the free lane — so at the cut the singer is still finishing his last word
and both his mouth and (under vocal-swap) his voice are chopped: 8 of 9 cuts on New Era,
0.4–1.4 s over (operator, 2026-08-31 09:00: "some transitions are ok, some are not").

The fix moves the cut LATER by the overrun and trims the same amount off the NEXT clip's
head — its head pad is silent, closed-mouth lead-in — so the next take's first word lands
at exactly the same film time as before. Nothing else moves; the film keeps its length.
The assembler plays a clip from frame 0, so the trimmed clip is written as a copy (the
slide stage's pattern) and the selection is rewritten onto it.

    shift = min(overrun + guard, previous clip's slack past its window,
                next take's first-word onset − guard   (∞ for a B-roll gap),
                next clip's slack, SHIFT_MAX)

Usage:
  join_cuts.py --selection build/selection-<sid>.json --plan build/plan.json \
               --store artifacts/clip-transcripts.json --out-dir build/joined-<sid> \
               --out-selection build/selection-<sid>.json [--json build/joins-<sid>.json] [--fps 24]
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys

LAST_WORD_S = 0.40   # a word's length past its onset (the store holds onsets only)
GUARD_S = 0.10       # air after the last word / before the next first word
SHIFT_MAX_S = 1.5
SLACK_MARGIN_S = 0.08  # never borrow a neighbour's slack to the last frame: the assembler refuses a
                       # clip even 0.02 s short of its cut (synthetic dry run, 2026-08-31)


def probe_seconds(path: str) -> float:
    r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
                       capture_output=True, text=True)
    try:
        return float(r.stdout.strip())
    except ValueError:
        return 0.0


def plan_joins(vocal_map: list[dict], clips: dict, clip_words: dict, durations: dict,
               *, last_word_s: float = LAST_WORD_S, guard: float = GUARD_S, shift_max: float = SHIFT_MAX_S) -> list[dict]:
    """Pure. vocal_map = the selection's windows in film order ({start,end,performerClip,lipSyncExempt});
    clips = performerClip id -> clip path; clip_words = clip path -> [{t,w}] (clip time; empty for
    B-roll); durations = clip path -> seconds. Returns one row per cut: {cut, from, to, overrun, shift, why}."""
    rows = []
    for i in range(len(vocal_map) - 1):
        a, b = vocal_map[i], vocal_map[i + 1]
        pa, pb = clips.get(a.get("performerClip") or ""), clips.get(b.get("performerClip") or "")
        if not pa or not pb:
            continue
        win_a = float(a["end"]) - float(a["start"])
        words_a = clip_words.get(pa) or []
        last_end = (float(words_a[-1]["t"]) + last_word_s) if words_a else 0.0
        overrun = round(max(0.0, last_end - win_a), 3)
        row = {"cut": round(float(a["end"]), 3), "from": os.path.basename(pa), "to": os.path.basename(pb),
               "overrun": overrun, "shift": 0.0, "why": ""}
        if overrun <= 0.05:
            row["why"] = "the take finishes before the cut"
            rows.append(row)
            continue
        limits = {"overrun": overrun + guard,
                  "previous clip's slack": round(float(durations.get(pa, 0.0)) - win_a - SLACK_MARGIN_S, 3),
                  "next clip's slack": round(float(durations.get(pb, 0.0)) - (float(b["end"]) - float(b["start"])) - SLACK_MARGIN_S, 3),
                  "cap": shift_max}
        words_b = clip_words.get(pb) or []
        sung_b = [float(w["t"]) for w in words_b[1:]] if len(words_b) > 1 else []   # whisper pins word 0 to t=0
        if sung_b:
            limits["next take's first word"] = round(sung_b[0] - guard, 3)
        shift = max(0.0, min(limits.values()))
        shift = round(shift, 3)
        bound = min(limits, key=limits.get)
        row["shift"] = shift
        row["why"] = f"bounded by {bound} ({limits[bound]:.2f}s)" + (
            f" — {overrun - shift + guard:.2f}s of the word still lost" if shift < overrun else "")
        rows.append(row)
    return rows


def apply_joins(sel: dict, rows: list[dict], out_dir: str, fps: int) -> dict:
    """Rewrite the selection: cut i moves later by shift; the next clip is written trimmed by
    shift from its head into out_dir (same basename, so the clip's job id survives) and the
    window points at the copy. Idempotent: a clip already under out_dir is trimmed from its
    ORIGINAL (recorded in the selection as `joinedFrom`)."""
    vm = sel["vocalMap"]
    by_id = {c["id"]: c for c in sel["clips"]}
    os.makedirs(out_dir, exist_ok=True)
    for i, row in enumerate(rows):
        shift = float(row.get("shift") or 0.0)
        if shift <= 0:
            continue
        a, b = vm[i], vm[i + 1]
        a["end"] = round(float(a["end"]) + shift, 6)
        b["start"] = round(float(b["start"]) + shift, 6)
        c = by_id[b["performerClip"]]
        src = c.get("joinedFrom") or c["path"]
        dst = os.path.join(out_dir, os.path.basename(src))
        cmd = ["ffmpeg", "-v", "error", "-y", "-ss", f"{shift:.3f}", "-i", src, "-r", str(fps),
               "-c:v", "libx264", "-preset", "veryfast", "-crf", "17", "-pix_fmt", "yuv420p",
               "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", dst]
        if subprocess.run(cmd, capture_output=True, text=True).returncode:
            raise SystemExit(f"join_cuts: ffmpeg failed trimming {src} by {shift}s")
        c["joinedFrom"] = src
        c["joinedShift"] = shift
        c["path"] = dst
        # the copy is `shift` shorter: the assembler's coverage check reads durationSec,
        # and a stale one let the last cut run out of frames (dry run, 2026-08-31)
        c["durationSec"] = round(probe_seconds(dst), 3)
        a["joinShift"] = shift
        b["headSec"] = round(max(0.0, float(b.get("headSec") or 0.0) - shift), 3)   # the trimmed copy has that much less head
    return sel


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--selection", required=True)
    ap.add_argument("--plan", required=True)
    ap.add_argument("--store", required=True, help="artifacts/clip-transcripts.json")
    ap.add_argument("--out-dir", required=True)
    ap.add_argument("--out-selection", required=True)
    ap.add_argument("--json", default="")
    ap.add_argument("--fps", type=int, default=24)
    ap.add_argument("--extra-words", default="", help="path -> [{t,w}] for fitted copies (fit_takes' words.json)")
    a = ap.parse_args()
    sel = json.load(open(a.selection, encoding="utf-8"))
    store = json.load(open(a.store, encoding="utf-8")).get("clips") or {}
    clips = {c["id"]: (c.get("joinedFrom") or c["path"]) for c in sel["clips"]}   # a fitted copy IS the source here
    words = {}
    for entry in store.values():
        if isinstance(entry, dict) and entry.get("path"):
            words[entry["path"]] = entry.get("words") or []
    if a.extra_words and os.path.isfile(a.extra_words):
        words.update(json.load(open(a.extra_words, encoding="utf-8")))
    durations = {p: probe_seconds(p) for p in set(clips.values())}
    # plan against the ORIGINAL clips and the original window geometry, so a re-run is a no-op
    vm0 = json.loads(json.dumps(sel["vocalMap"]))
    for w in vm0:
        if w.get("joinShift"):
            w["end"] = round(float(w["end"]) - float(w["joinShift"]), 6)
    for i in range(1, len(vm0)):
        if vm0[i - 1].get("joinShift"):
            vm0[i]["start"] = round(float(vm0[i]["start"]) - float(vm0[i - 1]["joinShift"]), 6)
    for w in vm0:
        w.pop("joinShift", None)
    sel["vocalMap"] = vm0
    rows = plan_joins(vm0, clips, words, durations)
    sel = apply_joins(sel, rows, a.out_dir, a.fps)
    json.dump(sel, open(a.out_selection, "w", encoding="utf-8"), indent=1)
    if a.json:
        json.dump({"joins": rows, "outDir": a.out_dir}, open(a.json, "w", encoding="utf-8"), indent=1)
    for r in rows:
        print(f"  cut {r['cut']:6.2f}s {r['from']:<9} -> {r['to']:<9} overrun {r['overrun']:+.2f}s  shift {r['shift']:+.2f}s  {r['why']}", file=sys.stderr)
    moved = sum(1 for r in rows if r["shift"] > 0)
    print(f"join_cuts: {moved} cut(s) moved to let the take finish -> {a.out_selection}", file=sys.stderr)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
