#!/usr/bin/env python3
"""build_mv_config.py — emit a music-video assembler config for one style variant.

`vclaw video music-video` already does the hard part: it builds a vocal map,
keeps the performer time-aligned across B-roll cutaways, de-patterns the B-roll
order, cuts frame-exactly, applies one grade pass, muxes the song, and then
ASSERTS the built master matches the plan within a single frame. This script
just fills in its config (schemas/video/artifacts/music-video-config.schema.json).

Two things it gets right that are easy to get wrong:

  * The MASTER AUDIO IS THE HOOK WAV — the same file the hero lip-sync render was
    generated from. That is what makes sync structural rather than hopeful: the
    performer clip and the master track come from one source, so there is nothing
    to re-align. (This is precisely the defect in the reference skill, which muxes
    an original clip back over a render and never checks the two still line up.)
  * The transcript handed to the assembler is the whisper segments SLICED to the
    hook window and REBASED to zero. Passing the whole song's transcript against
    an 8-second master would classify the wrong sections.

Usage:
  build_mv_config.py --hook-json <hook.json> --transcript <whisper.json>
                     --hero <clip.mp4> --broll <clip.mp4> [--broll ...]
                     --out <config.json> [--output <master.mp4>]
                     [--fps 24] [--width 1920] [--height 1080] [--grade <id>]
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys


# The most audio we will ever drop off the tail to make the picture cover the
# vocal. Past this the hook window itself is wrong and should be re-picked.
MAX_TAIL_TRIM_FRAMES = 6


def die(msg: str) -> None:
    print(f"build_mv_config: {msg}", file=sys.stderr)
    raise SystemExit(2)


def choose_cut_length(total: float, fps: int, lo: float = 0.8, hi: float = 2.0,
                      ideal: float = 1.2) -> tuple[float, int]:
    """Pick a cut length that divides `total` into a WHOLE number of frame-aligned cuts.

    Load-bearing, and found the hard way: the assembler plans the cut by laying
    section-length cuts end to end, and any remainder that will not fill another
    cut is simply not covered. With the default cadence an 8.000 s hook planned to
    7.750 s — the picture ended a quarter-second before the vocal did, so the last
    words of the hook played over nothing. (That is the "song outlasts the
    picture" failure, and the delivery gate catches it, but a film should not need
    the gate to catch it.)

    A length that divides the hook exactly and lands on whole frames makes the
    plan equal the song end, so the picture always covers the vocal.

    The search runs in FRAMES, not seconds, because the planner rounds every cut
    to whole frames: a cut length of 1.6 s at 24 fps becomes 38 frames (1.5833 s),
    so five of them cover 7.917 s rather than 8.000 s. Only a whole-frame length
    that divides the hook's whole-frame length can close the gap exactly. Hook
    lengths are arbitrary — `pick_hook` snaps the window end to a word boundary,
    so 7.833 s is far more typical than 8.000 s — which is why the range widens
    before giving up.
    """
    total_frames = int(round(total * fps))
    if total_frames <= 0:
        return round(round(ideal * fps) / fps, 6), max(1, total_frames)

    def search(lo_s: float, hi_s: float) -> int | None:
        lo_f, hi_f = max(1, int(round(lo_s * fps))), max(1, int(round(hi_s * fps)))
        exact = [f for f in range(lo_f, hi_f + 1) if total_frames % f == 0]
        return min(exact, key=lambda f: abs(f / fps - ideal)) if exact else None

    # Preference order: a SHORT cadence first, and a one- or two-frame tail trim
    # is cheaper than a long cut. A long cut is not merely less musical — the
    # assembler steps its B-roll in-points to de-pattern the order, so a cut close
    # to a source clip's own length runs off the end of it and comes back short
    # (measured: a 1.958 s cut from 8 s sources built 186 frames against 188
    # planned). Trimming is safe because pick_hook snapped the window end to a
    # word boundary, so the frames given up are tail, not speech.
    for lo_s, hi_s in ((lo, 1.5), (lo, hi), (0.6, 3.0)):
        for lost in range(0, MAX_TAIL_TRIM_FRAMES + 1):
            candidate = total_frames - lost
            lo_f, hi_f = max(1, int(round(lo_s * fps))), max(1, int(round(hi_s * fps)))
            exact = [f for f in range(lo_f, hi_f + 1) if candidate % f == 0]
            if not exact:
                continue
            chosen = min(exact, key=lambda f: abs(f / fps - ideal))
            if lost:
                print(f"build_mv_config: a {total_frames}-frame hook has no exact cut cadence; "
                      f"trimming {lost} frame(s) ({lost / fps * 1000:.0f} ms) of post-word tail "
                      f"to reach {candidate} frames at {chosen}/cut.", file=sys.stderr)
            return round(chosen / fps, 6), candidate

    die(f"a {total_frames}-frame hook has no workable cut cadence within "
        f"{MAX_TAIL_TRIM_FRAMES} frames of trim. Re-pick the hook window "
        f"(pick_hook.py --duration) so it lands on a friendlier length.")
    raise AssertionError("unreachable")


def probe_duration(path: str, ffprobe: str) -> float:
    proc = subprocess.run(
        [ffprobe, "-v", "error", "-show_entries", "format=duration",
         "-of", "default=nk=1:nw=1", path],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if proc.returncode != 0:
        die(f"ffprobe failed on {path}: {proc.stderr.decode('utf-8', 'replace')[:200]}")
    try:
        return round(float(proc.stdout.decode().strip()), 3)
    except ValueError:
        die(f"ffprobe returned no duration for {path}")
        raise  # unreachable, keeps type checkers happy


def assert_pool_footage_long_enough(config: dict) -> None:
    """B-roll must be LONGER than the cut it fills. Refuse here, not in the assembler.

    `emitBroll` in vocal-sync-plan.ts steps the in-point through the clip so a repeated
    shot does not replay identically, and it reserves 0.05s in and 0.15s tail to do it.
    A pool clip therefore has to run cutLength + 0.2s or the plan throws.

    THIS LANE RENDERS EVERYTHING AT ONE LENGTH, which makes the trap structural rather
    than occasional: SCENE_SECONDS=8 gives 8.04-8.06s clips, an 8.00s cut wants 8.20s,
    and so a film's OWN B-roll can never fill its own cuts. It surfaced as
    `planVocalSync: B-roll clip "w00" is 8.06s but a 8.00s cut (+0.2s margin) is
    planned` — thrown from deep in the assembler, naming a clip but not saying where
    the pool came from or what to change. Caught here it is one line with the fix in it.

    It also names any PERFORMANCE clip that has ended up in a pool. An unpinned window
    falls back to the pool, and a lip-synced take drawn as anonymous B-roll gets its
    in-point stepped to an arbitrary offset — the mouth then moves to the wrong words,
    which is the one defect this whole lane is built to prevent.
    """
    pools = config.get("pools") or {}
    cut_lengths = config.get("cutLengths") or {}
    if not pools or not cut_lengths:
        return
    longest_cut = max(float(v) for v in cut_lengths.values())
    by_id = {c["id"]: c for c in config.get("clips", []) if isinstance(c, dict) and "id" in c}
    windows = config.get("vocalMap") or []
    pinned = {s["performerClip"] for s in windows if s.get("performerClip")}

    # WILL THE POOL ACTUALLY BE DRAWN FROM? select_cut fills all four pool roles even
    # on a fully-pinned film, deliberately: the schema requires them, and an EMPTY pool
    # makes the planner silently SKIP a cut — missing film, which is far harder to spot
    # than a visibly wrong clip. So on a fully-pinned film the pools are decorative and
    # a short clip in them costs nothing. Refusing there would be a gate crying wolf on
    # the happy path, which is how gates get clicked through.
    drawable = any(not s.get("performerClip") for s in windows) if windows else True

    too_short, performers_in_pool = [], set()
    for role, clips in pools.items():
        for cid in clips or []:
            if cid in pinned:
                performers_in_pool.add(cid)
            entry = by_id.get(cid)
            path = entry.get("path") if entry else None
            if not path or not os.path.isfile(path):
                continue
            seconds = probe_seconds(path)
            if seconds and seconds < longest_cut + 0.2:
                too_short.append((role, cid, seconds))

    # Only when the pool can actually be drawn from. On the windows path select_cut
    # fills every pool role with `clips[0]`, and that list holds ONLY performer clips —
    # so this is true of every film ever built here. Warning unconditionally would print
    # on every successful run and mean nothing; warning when a window is unpinned means
    # a lip-synced take is about to be used as anonymous scenery.
    if performers_in_pool and drawable:
        unpinned = sum(1 for s in windows if not s.get("performerClip"))
        print(f"build_mv_config: WARNING — {unpinned} window(s) have no pinned performer "
              f"and the B-roll pool holds performance clip(s): "
              f"{', '.join(sorted(performers_in_pool))}. The planner will draw one and "
              f"step its in-point to an arbitrary offset — a lip-synced take used as "
              f"anonymous scenery, mouth moving to the wrong words. Pin the window, or "
              f"give the pool real B-roll.", file=sys.stderr)
    if not too_short:
        return
    lines = "\n".join(f"    {role}: {cid} is {sec:.2f}s"
                      for role, cid, sec in sorted(set(too_short))[:8])
    detail = (f"  The longest cut is {longest_cut:.2f}s and the in-point stepper reserves "
              f"0.2s, so pool clips must run at least {longest_cut + 0.2:.2f}s.\n"
              f"  RENDER B-ROLL LONGER THAN THE WINDOWS — a lane that renders everything "
              f"at SCENE_SECONDS can never fill its own cuts. Or shorten cutLengths.")
    if not drawable:
        # Every window is pinned, so nothing is ever drawn from the pool. Say it once
        # and carry on; a film that is complete should not be blocked by scenery it
        # never uses.
        print(f"build_mv_config: NOTE — pool footage is shorter than a cut, but every "
              f"window is pinned so the pool is never drawn from.\n{lines}\n{detail}",
              file=sys.stderr)
        return
    die(f"B-roll pool footage is shorter than the cut it must fill, and "
        f"{sum(1 for s in windows if not s.get('performerClip'))} window(s) have no "
        f"pinned performer — so the pool WILL be drawn from.\n{lines}\n{detail}")


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 write_from_selection(args, song: str) -> None:
    """Windows mode — emit the config straight from the selection.

    Every field that decides WHICH picture plays over WHICH bar comes from the
    selection, unmodified. Deriving anything here would let the config drift from the
    manifest `check_sync.py` measured, and the whole point of the windows path is that
    those two describe the same cut.
    """
    sel = json.load(open(args.selection, encoding="utf-8"))
    for key in ("vocalMap", "clips", "pools", "cutLengths", "songEnd"):
        if key not in sel:
            die(f"selection is missing {key!r} — regenerate it with select_cut.py")
    for c in sel["clips"]:
        if not os.path.isfile(c["path"]):
            die(f"clip not found: {c['path']}")
    fps = int(sel.get("fps", args.fps))
    song_end = float(sel["songEnd"])
    last = max(float(s["end"]) for s in sel["vocalMap"])
    # Frame-exact or the picture stops covering the vocal at the very end.
    if abs(song_end - last) > 0.5 / fps:
        die(f"songEnd {song_end:.3f}s does not match the last window end {last:.3f}s")

    config = {
        "song": os.path.abspath(song),
        "songEnd": song_end,
        "fps": fps,
        "width": args.width,
        "height": args.height,
        "vocalMap": sel["vocalMap"],
        # Windows the cover stage turned into cutaways. They carry no vocal by design,
        # so measuring their lip sync asks whether ambient waves are on the beat.
        "lipSyncExempt": [w["performerClip"] for w in sel["vocalMap"]
                          if w.get("lipSyncExempt") and w.get("performerClip")],
        "pools": sel["pools"],
        "clips": [{**c, "path": os.path.abspath(c["path"])} for c in sel["clips"]],
        "cutLengths": sel["cutLengths"],
        "output": os.path.abspath(args.output) if args.output
        else os.path.join(os.path.dirname(os.path.abspath(args.out)), "master.mp4"),
    }
    if args.grade:
        config["grade"] = args.grade

    assert_pool_footage_long_enough(config)

    os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
    with open(args.out, "w", encoding="utf-8") as fh:
        json.dump(config, fh, indent=2)
        fh.write("\n")
    synced = sum(1 for s in sel["vocalMap"] if s.get("performerClip"))
    print(f"build_mv_config: {args.out}  master={song_end:.3f}s  "
          f"{len(sel['vocalMap'])} windows ({synced} with a pinned performer)",
          file=sys.stderr)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--hook-json", required=True)
    ap.add_argument("--transcript", default="")
    ap.add_argument("--hero", default="")
    ap.add_argument("--broll", action="append", default=[])
    # Windows mode. select_cut.py has already chosen a clip per window and authored an
    # explicit vocalMap — one section per window, each carrying its own performerClip.
    # In that mode this script is a pass-through: the cadence IS the window plan, so
    # choose_cut_length() must not run and re-derive one.
    ap.add_argument("--selection", default="",
                    help="selection JSON from select_cut.py (mutually exclusive "
                         "with --hero/--broll/--transcript)")
    ap.add_argument("--out", required=True)
    ap.add_argument("--output", default="")
    ap.add_argument("--fps", type=int, default=24)
    ap.add_argument("--width", type=int, default=1920)
    ap.add_argument("--height", type=int, default=1080)
    ap.add_argument("--grade", default="")
    ap.add_argument("--ffprobe", default=os.environ.get("FFPROBE_BIN", "ffprobe"))
    args = ap.parse_args()

    hook = json.load(open(args.hook_json, encoding="utf-8"))
    start, end = float(hook["start"]), float(hook["end"])
    song = hook["hookWav"]

    if args.selection:
        if args.hero or args.broll or args.transcript:
            die("--selection is mutually exclusive with --hero/--broll/--transcript")
        write_from_selection(args, song)
        return
    if not args.hero or not args.transcript:
        die("--hero and --transcript are required unless --selection is given")
    for p in (song, args.hero, *args.broll):
        if not os.path.isfile(p):
            die(f"clip not found: {p}")
    if not args.broll:
        die("at least one --broll clip is required (the hero shot alone is a talking head, "
            "not a music video)")

    # transcript sliced to the hook window and rebased to zero
    raw = json.load(open(args.transcript, encoding="utf-8"))
    segs = raw.get("segments") if isinstance(raw, dict) else raw
    transcript = []
    for s in segs or []:
        a, b = float(s["start"]), float(s["end"])
        if b <= start or a >= end:
            continue
        transcript.append({
            "start": round(max(a, start) - start, 3),
            "end": round(min(b, end) - start, 3),
            "text": str(s.get("text", "")).strip(),
        })
    if not transcript:
        die("no transcript segments fall inside the hook window — "
            "the hook.json and the transcript are not from the same song")

    clips = [{"id": "hero", "path": os.path.abspath(args.hero),
              "durationSec": probe_duration(args.hero, args.ffprobe)}]
    pool = []
    for i, b in enumerate(args.broll):
        cid = f"broll-{i + 1}"
        clips.append({"id": cid, "path": os.path.abspath(b),
                      "durationSec": probe_duration(b, args.ffprobe)})
        pool.append(cid)

    song_end = round(end - start, 3)
    cut, covered_frames = choose_cut_length(song_end, args.fps)
    song_end = round(covered_frames / args.fps, 6)

    config = {
        "song": os.path.abspath(song),
        "songEnd": song_end,
        "fps": args.fps,
        "width": args.width,
        "height": args.height,
        "transcript": transcript,
        # Every vocal second in a rap MV is rap; the hero shot carries all of it.
        #
        # DANGER, and the reason the windows path exists: `emitPerformer` seeks the
        # performer clip to time-WITHIN-SECTION, not within-song
        # (src/video/vocal-sync-plan.ts). So if the auto-classifier ever yields more
        # than one section here, every section after the first replays this one hero
        # clip from ~0 while the song is somewhere else — a man mouthing the wrong
        # words, produced by this file. It has survived only because a short hook
        # classifies into a single section. `--verify-plan` (select_cut.py) checks the
        # assembler's actual plan for exactly this, and the runner runs it on both
        # paths; use --selection for anything longer than a single hook.
        "performers": {"rap": "hero", "hook": "hero"},
        # the schema requires all four pool roles and forbids extras; a rap MV of
        # this length has one B-roll set, so every role draws from it
        "pools": {"action": pool, "atmo": pool, "trio": pool, "vanish": pool},
        "clips": clips,
        # a cadence that divides the hook exactly, so the picture covers the vocal
        "cutLengths": {t: cut for t in ("rap", "hook", "instrumental", "outro")},
        "output": os.path.abspath(args.output) if args.output
        else os.path.join(os.path.dirname(os.path.abspath(args.out)), "master.mp4"),
    }
    if args.grade:
        config["grade"] = args.grade

    os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
    with open(args.out, "w", encoding="utf-8") as fh:
        json.dump(config, fh, indent=2)
        fh.write("\n")
    print(f"build_mv_config: {args.out}  master={config['songEnd']:.3f}s  "
          f"cut={cut:.4f}s  hero + {len(pool)} B-roll", file=sys.stderr)


if __name__ == "__main__":
    main()
