#!/usr/bin/env python3
"""assemble_plan.py — build the film from a plan and its rendered clips.

THE MISSING CONSUMER. Until now nothing read plan.json to make a video: only
explore_queue.py and make_plan.py touched it, and select_cut.py derives its own
windows from the transcript and never sees the render grid. So a whole-song film
had to be concatenated by hand — and `trimStartSec`, which make_plan records when
it slides the final window back to a valid duration, would have been inert config
that no code ever read.

Each window is trimmed to exactly the span it owns, so 24 clips cannot accumulate
drift: the sources come back a few frames long (8.057s for an 8s request), and
concatenating them raw walks the picture off the song by over a second.

The picture must never end before the audio. A song that outlasts the picture is
what chops a burned caption mid-line, so the mux is NOT `-shortest`; a final window
that renders short is held on its last frame instead.

  assemble_plan.py --plan <build/plan.json> --out <film.mp4>
                   [--clips <dir>] [--song <hook.wav>] [--fps 24]
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys


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


def run(cmd: list[str]) -> None:
    p = subprocess.run(cmd, stderr=subprocess.PIPE)
    if p.returncode:
        die(f"ffmpeg failed:\n{' '.join(cmd)}\n{p.stderr.decode('utf-8', 'replace')[:500]}")


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


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--plan", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--clips", default="", help="default: <queueDir>/clips")
    ap.add_argument("--song", default="", help="default: <projectDir>/build/hook.wav")
    ap.add_argument("--fps", type=int, default=24)
    ap.add_argument("--ffmpeg", default=os.environ.get("FFMPEG_BIN", "ffmpeg"))
    ap.add_argument("--ffprobe", default=os.environ.get("FFPROBE_BIN", "ffprobe"))
    args = ap.parse_args()

    if not os.path.isfile(args.plan):
        die(f"not found: {args.plan}")
    plan = json.load(open(args.plan, encoding="utf-8"))
    jobs = plan.get("jobs", [])
    if not jobs:
        die("plan has no jobs")

    project = plan.get("projectDir", "")
    build = os.path.join(project, "build")
    clips = args.clips or os.path.join(plan.get("queueDir", ""), "clips")
    song = args.song or os.path.join(build, "hook.wav")
    for p in (clips, song):
        if not os.path.exists(p):
            die(f"not found: {p}")

    seg_dir = os.path.join(build, "segments")
    os.makedirs(seg_dir, exist_ok=True)
    lines, missing, covered = [], [], 0.0

    for job in jobs:
        src = os.path.join(clips, f"{job['id']}.mp4")
        if not os.path.isfile(src):
            missing.append(job["id"])
            continue
        trim = float(job.get("trimStartSec") or 0.0)
        want = round(float(job["seconds"]) - trim, 3)
        have = duration(src, args.ffprobe) - trim
        dst = os.path.join(seg_dir, f"{job['id']}.mp4")

        vf = []
        # A clip that came back short cannot fill its window. Hold its last frame
        # rather than let the film run out from under the song.
        if have < want - 0.02:
            vf.append(f"tpad=stop_mode=clone:stop_duration={round(want - have + 0.5, 3)}")
            print(f"  {job['id']}: short by {want - have:.2f}s — holding last frame",
                  file=sys.stderr)
        cmd = [args.ffmpeg, "-y", "-v", "error", "-nostdin"]
        if trim > 0:
            cmd += ["-ss", f"{trim:.3f}"]
        cmd += ["-i", src]
        if vf:
            cmd += ["-vf", ",".join(vf)]
        # -fps_mode cfr == the old -vsync cfr; ffmpeg 9 removed -vsync (see deliver.py)
        cmd += ["-t", f"{want:.3f}", "-an", "-c:v", "libx264", "-preset", "veryfast",
                "-crf", "18", "-pix_fmt", "yuv420p", "-r", str(args.fps), "-fps_mode", "cfr", dst]
        run(cmd)
        lines.append(f"file '{os.path.abspath(dst)}'")
        covered += want

    if missing:
        die(f"{len(missing)} window(s) have no clip: {', '.join(missing)}")

    concat = os.path.join(build, "concat.txt")
    with open(concat, "w", encoding="utf-8") as fh:
        fh.write("\n".join(lines) + "\n")

    os.makedirs(os.path.dirname(os.path.abspath(args.out)) or ".", exist_ok=True)
    # No -shortest: the picture is allowed to outlast the audio, never the reverse.
    run([args.ffmpeg, "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", concat,
         "-i", song, "-map", "0:v", "-map", "1:a", "-c:v", "copy",
         "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", args.out])

    film = duration(args.out, args.ffprobe)
    track = duration(song, args.ffprobe)
    print(f"assemble_plan: {len(lines)} segment(s), {covered:.2f}s of picture "
          f"-> {args.out} ({film:.2f}s, song {track:.2f}s)", file=sys.stderr)
    if film + 0.05 < track:
        die(f"the picture ({film:.2f}s) ends before the song ({track:.2f}s)")


if __name__ == "__main__":
    main()
