#!/usr/bin/env python3
"""rap_polish.py — loudness-normalise a finished film to the platform target. VERIFIED.

THE STAGE THIS REPLACES NEVER RAN. `polish` called rhyme-factory's youtube-polish.sh,
which hardcodes a master filename this lane never writes (final/videos/<slug>.mp4), dies
at the missing poster, and was swallowed by `|| warn` — so the stage list said
"-14 LUFS + poster" while NO rap master was ever loudness-normalised. The birthday film
shipped at -16.6 LUFS, found only because an operator-prompted QC pass measured it.
A stage that does nothing and exits 0 is the house disease; this one measures its own
output and refuses to pass silently.

WHY NOT REUSE youtube-polish.sh WHOLESALE: it is structurally wrong for this lane even
with its inputs present — 1280x720/24fps hardcoded (rap is 9:16), it overwrites its
input IN PLACE (a versioned master would be destroyed), and it adds a second bookend
system on top of rap's own `bookends` stage. What IS reused is its proven audio maths:
loudnorm=I=-14:TP=-1.5:LRA=11 with a limiter — the exact chain SKILL.md records as the
fix for the -0.002 dBFS clipping incident.

MEASURE THE ENCODED FILE. AAC overshoots: a clean pre-encode peak can decode above
full scale (a -3 dBFS master once decoded to +2.9). So verification runs ebur128 on the
written mp4, never on the filter graph's idea of itself.

Usage:
  rap_polish.py --film <FILM[-SUBTITLED].mp4> [--target -14] [--tolerance 1.0]
                [--max-tp -1.0] [--json-out <report.json>]

Writes <film-stem-without-FILM-suffixes>-YT.mp4 beside the input. Never in place.
Exit 0 verified · 5 the output missed the target · 2 bad input.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys

FFMPEG = os.environ.get("FFMPEG_FULL", "/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg")

# loudnorm in one-pass dynamic mode targets I and TP itself; the limiter after it is
# the safety net for inter-sample peaks the AAC encode then creates. level=disabled:
# the limiter must only catch peaks, never ride the level back up (the gate-what-can-
# break lesson: a limiter that adjusts level defeated the loudness gate entirely).
CHAIN = "loudnorm=I={target}:TP=-1.5:LRA=11,alimiter=limit=0.97:level=disabled"


def probe_duration(path: str) -> float:
    """VIDEO stream duration, not container duration. The video stream is `-c:v copy`
    so it must be byte-identical in length; the CONTAINER grows ~60ms because the AAC
    encoder pads priming samples, and comparing containers failed a correct output on
    the first real run. Compare the thing the polish is not allowed to change."""
    r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
                        "-show_entries", "stream=duration", "-of", "csv=p=0", path],
                       capture_output=True, text=True)
    try:
        return float(r.stdout.strip())
    except ValueError:
        return 0.0


def measure(path: str) -> tuple[float | None, float | None]:
    """(integrated LUFS, true peak dBTP) of the ENCODED file."""
    r = subprocess.run(
        [FFMPEG, "-hide_banner", "-i", path,
         "-af", "ebur128=peak=true", "-f", "null", "-"],
        capture_output=True, text=True)
    text = r.stderr
    tail = text[text.rfind("Summary:"):] if "Summary:" in text else text
    li = re.search(r"I:\s*(-?[\d.]+)\s*LUFS", tail)
    tp = re.search(r"Peak:\s*(-?[\d.]+)\s*dBFS", tail)
    return (float(li.group(1)) if li else None,
            float(tp.group(1)) if tp else None)


def out_path(film: str) -> str:
    stem = os.path.basename(film)
    for suffix in ("-FILM-SUBTITLED.mp4", "-FILM.mp4", ".mp4"):
        if stem.endswith(suffix):
            stem = stem[: -len(suffix)]
            break
    return os.path.join(os.path.dirname(film), f"{stem}-YT.mp4")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--film", required=True)
    ap.add_argument("--target", type=float, default=-14.0)
    ap.add_argument("--tolerance", type=float, default=1.0)
    ap.add_argument("--max-tp", type=float, default=-1.0)
    ap.add_argument("--json-out", default="")
    args = ap.parse_args()

    if not os.path.isfile(args.film):
        print(f"rap_polish: no film at {args.film}", file=sys.stderr)
        raise SystemExit(2)

    dest = out_path(args.film)
    src_dur = probe_duration(args.film)
    before_i, before_tp = measure(args.film)

    tmp = dest + ".tmp.mp4"
    r = subprocess.run(
        [FFMPEG, "-v", "error", "-y", "-i", args.film,
         "-af", CHAIN.format(target=args.target),
         "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-ar", "44100",
         "-movflags", "+faststart", tmp],
        capture_output=True, text=True)
    if r.returncode != 0:
        print(f"rap_polish: ffmpeg failed:\n{r.stderr[-800:]}", file=sys.stderr)
        raise SystemExit(2)
    os.replace(tmp, dest)

    # THE VERIFICATION IS THE POINT. The stage this replaces claimed a target it never
    # once hit; this one reads the file it just wrote and refuses to bless a miss.
    after_i, after_tp = measure(dest)

    # One measured corrective pass: one-pass loudnorm lands hot on loud, dense
    # sources (a bright hip-hop master polished to -12.6 on the anthem dry run).
    # Plain gain from the MEASURED miss + an OVERSAMPLED limiter (inter-sample
    # peaks survive a sample-domain limiter and AAC adds ~+0.5 dB on top —
    # both measured on the West Road reels, 2026-08-18).
    needs_fix = after_i is not None and (
        abs(after_i - args.target) > args.tolerance or after_tp > args.max_tp)
    if needs_fix:
        delta = args.target - after_i
        fix = dest + ".fix.mp4"
        r2 = subprocess.run(
            [FFMPEG, "-v", "error", "-y", "-i", dest,
             "-af", f"volume={delta:.2f}dB,aresample=96000,"
                    "alimiter=limit=0.79:attack=3:release=100:level=disabled,"
                    "aresample=44100",
             "-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
             "-movflags", "+faststart", fix],
            capture_output=True, text=True)
        if r2.returncode == 0:
            os.replace(fix, dest)
            after_i, after_tp = measure(dest)
            print(f"rap_polish: corrective {delta:+.1f} dB pass -> {after_i} LUFS")

    # AAC can still add an inter-sample overshoot after the corrective limiter. When
    # loudness has headroom inside the accepted band, apply the smallest measured trim
    # that clears the true-peak ceiling plus 0.3 dB encode margin. This is preferable
    # to relaxing the safety gate: on the West Road anthem the file was a healthy
    # -13.0 LUFS but decoded at -0.7 dBTP; a 0.6 dB trim lands both measurements.
    if (after_i is not None and after_tp is not None
            and after_tp > args.max_tp):
        quiet_edge = args.target - args.tolerance
        loudness_headroom = max(0.0, after_i - quiet_edge)
        needed_trim = after_tp - args.max_tp + 0.3
        trim = min(loudness_headroom, needed_trim)
        if trim > 0:
            peak_fix = dest + ".peak.mp4"
            r3 = subprocess.run(
                [FFMPEG, "-v", "error", "-y", "-i", dest,
                 "-af", f"volume=-{trim:.2f}dB",
                 "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-ar", "44100",
                 "-movflags", "+faststart", peak_fix],
                capture_output=True, text=True)
            if r3.returncode == 0:
                os.replace(peak_fix, dest)
                after_i, after_tp = measure(dest)
                print(f"rap_polish: true-peak trim -{trim:.1f} dB -> "
                      f"{after_i} LUFS, {after_tp} dBTP")
    dst_dur = probe_duration(dest)
    problems = []
    if after_i is None or after_tp is None:
        problems.append("could not measure the encoded output at all")
    else:
        if abs(after_i - args.target) > args.tolerance:
            problems.append(f"integrated {after_i:.1f} LUFS is outside "
                            f"{args.target:+.0f}±{args.tolerance:g}")
        if after_tp > args.max_tp:
            problems.append(f"true peak {after_tp:.1f} dBTP exceeds {args.max_tp:g} "
                            f"— clipping risk after AAC decode")
    if abs(dst_dur - src_dur) > 1.0 / 24:
        problems.append(f"duration changed: {src_dur:.3f}s -> {dst_dur:.3f}s")

    report = {
        "film": args.film, "out": dest,
        "before": {"lufs": before_i, "dbtp": before_tp},
        "after": {"lufs": after_i, "dbtp": after_tp},
        "target": args.target, "problems": problems,
    }
    if args.json_out:
        json.dump(report, open(args.json_out, "w", encoding="utf-8"), indent=1)

    b_i = f"{before_i:.1f}" if before_i is not None else "?"
    a_i = f"{after_i:.1f}" if after_i is not None else "?"
    a_tp = f"{after_tp:.1f}" if after_tp is not None else "?"
    print(f"rap_polish: {os.path.basename(args.film)}  {b_i} -> {a_i} LUFS  "
          f"(peak {a_tp} dBTP) -> {os.path.basename(dest)}")
    if problems:
        for p in problems:
            print(f"  FAIL: {p}", file=sys.stderr)
        raise SystemExit(5)


if __name__ == "__main__":
    main()
