#!/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

from fit_takes import MEASURED_END_SOURCES, finite_number
from sync_evidence import file_hash

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:
    """Budget picture frames only; a longer audio stream cannot supply coverage."""
    from timing_edits import video_seconds
    seconds, _ = video_seconds(path)
    return seconds if seconds is not None else 0.0


def plan_joins(vocal_map: list[dict], clips: dict, clip_words: dict, durations: dict,
               *, 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"])
        head_a, head_b = float(a.get("headSec") or 0), float(b.get("headSec") or 0)
        words_a, words_b = clip_words.get(pa) or [], clip_words.get(pb) or []
        row = {"cut": round(float(a["end"]), 3), "from": os.path.basename(pa), "to": os.path.basename(pb),
               "fromWindow": a.get("performerClip"), "toWindow": b.get("performerClip"),
               "overrun": None, "shift": 0.0, "status": "unmeasured", "nextAction": "verify", "why": ""}
        rows.append(row)
        gap_a = a.get("lipSyncExempt") and a.get("lipSyncExemptBy") != "cover"
        gap_b = b.get("lipSyncExempt") and b.get("lipSyncExemptBy") != "cover"
        last_end = finite_number(words_a[-1].get("e")) if words_a else None
        last_onset = finite_number(words_a[-1].get("t")) if words_a else None
        if not words_a and gap_a:
            last_end = 0.0
        elif (last_end is None or last_onset is None or last_end <= last_onset
              or words_a[-1].get("eFrom") not in MEASURED_END_SOURCES):
            row["why"] = "verify the outgoing take's measured final note ending before moving its cut"
            continue
        source_length = finite_number(durations.get(pa))
        if source_length is None or source_length <= 0 or last_end > source_length:
            row["why"] = "verify the outgoing take's duration and measured ending"
            continue
        overrun = round(max(0.0, last_end - head_a - win_a), 3)
        row["overrun"] = overrun
        if overrun <= 0.05:
            row.update({"status": "ready", "nextAction": "none", "why": "the take finishes before the cut"})
            continue
        onsets = [finite_number(word.get("t")) for word in words_b]
        if (not onsets and not gap_b) or any(t is None or t < 0 for t in onsets):
            row["why"] = "verify the next take's first onset before trimming its head"
            continue
        next_length = finite_number(durations.get(pb))
        if next_length is None or next_length <= 0 or any(t > next_length for t in onsets):
            row["why"] = "verify the next take's duration and onsets"
            continue
        limits = {"overrun": overrun + guard,
                  "previous clip's slack": round(source_length - head_a - win_a - SLACK_MARGIN_S, 3),
                  "next clip's slack": round(next_length - head_b - (float(b["end"]) - float(b["start"])) - SLACK_MARGIN_S, 3),
                  "cap": shift_max}
        if onsets:
            # Include word zero. A word already starting at the cut leaves no safe
            # head to borrow, even if the following word is much later.
            limits["next take's first word"] = round(min(onsets) - head_b - guard, 3)
        shift = round(max(0.0, min(limits.values())), 3)
        bound = min(limits, key=limits.get)
        remaining = max(0.0, overrun - shift)
        row.update({"shift": shift, "status": "constrained" if remaining > 0 else "ready",
                    "nextAction": "verify" if remaining > 0 else "join", "remainingOverrun": round(remaining, 3),
                    "why": f"bounded by {bound} ({limits[bound]:.2f}s)" + (
                        f" — {remaining:.2f}s of the word still lost" if remaining else "")})
    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 row in rows:
        shift = float(row.get("shift") or 0.0)
        if shift <= 0:
            continue
        i = next((i for i in range(len(vm) - 1)
                  if vm[i].get("performerClip") == row.get("fromWindow")
                  and vm[i + 1].get("performerClip") == row.get("toWindow")), None)
        if i is None:
            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")
        from clip_vocals import derive_vocal
        derive_vocal(src, dst, shift)
        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
    from clip_vocals import transcript_entries_for_paths, separated_vocal
    entries = transcript_entries_for_paths(store, clips.values())
    words = {path: entry.get("words") or [] for path, entry in entries.items()}
    vocal_cache = os.path.join(os.path.dirname(os.path.abspath(a.out_dir)), "vocal-swap-demucs")
    for path, entry in entries.items():
        origin = entry.get("path")
        if origin and file_hash(origin) == file_hash(path):
            separated_vocal('', origin, vocal_cache, cached_only=True)
        separated_vocal('', path, vocal_cache, cached_only=True)
    if a.extra_words and os.path.isfile(a.extra_words):
        extra = json.load(open(a.extra_words, encoding="utf-8"))
        extra_by_sha = {digest: (path, ws) for path, ws in extra.items() if (digest := file_hash(path))}
        for c in sel["clips"]:
            path = c.get("joinedFrom") or c["path"]
            digest = file_hash(path)
            if c.get("fitOutputSha256") and c["fitOutputSha256"] == digest and digest in extra_by_sha:
                origin, words[path] = extra_by_sha[digest]
                separated_vocal('', origin, vocal_cache, cached_only=True)
                separated_vocal('', path, vocal_cache, cached_only=True)
    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
    previous_vm = sel["vocalMap"]
    vm0 = json.loads(json.dumps(previous_vm))
    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)
    moving = {(r["fromWindow"], r["toWindow"]) for r in rows if r["shift"] > 0}
    for i in range(len(vm0) - 1):
        if (vm0[i].get("performerClip"), vm0[i + 1].get("performerClip")) not in moving:
            vm0[i]["end"] = previous_vm[i]["end"]
            vm0[i + 1]["start"] = previous_vm[i + 1]["start"]
            if previous_vm[i].get("joinShift"):
                vm0[i]["joinShift"] = previous_vm[i]["joinShift"]
    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:
        overrun = f"{r['overrun']:+.2f}s" if r["overrun"] is not None else "unmeasured"
        print(f"  cut {r['cut']:6.2f}s {r['from']:<9} -> {r['to']:<9} overrun {overrun}  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())
