#!/usr/bin/env python3
"""check_delivery.py — is the thing in final/ actually deliverable?

The last gate. Everything upstream checks the PLAN or the RENDER; this checks
the file a person would be sent, because that is the only artefact that matters
by the time you get here.

Five things, each of which has shipped wrong on a real film somewhere in this
repo:

  * an audio stream EXISTS. A silent master passes every duration and codec
    check ever written, and looks perfect until someone presses play.
  * the true peak is not clipping. A loudness-only pass happily ships files
    that clip — loudness and peak are different measurements, and normalising
    UP is exactly when peak breaks.
  * a poster frame exists and is not blank. Frame 0 is the feed thumbnail.
  * a SILENT film is actually silent (--silent). "The Sun Mango" was delivered
    as a wordless devotional short in which a character says "I am flying
    towards the sun!". Nothing caught it, because nothing listened: the pack
    said DIALOGUE_MODE=none, the storyboard said silent:true, the execution
    profile said generateAudio:false — and veo-useapi honours none of them
    (Veo 3.x is audio-native and the Flow API has no audio-off parameter).
    Every upstream check was reading a field. This one plays the file.
  * the delivered length matches the plan (--expect-seconds). Nothing else in
    the pipeline ever compares the finished film to the pack's SHORT_DURATION;
    the shot table is checked before anything renders and never again.

Usage:
  check_delivery.py --master <mp4> [--poster <jpg>] [--max-true-peak -0.5]
                    [--silent] [--expect-seconds 64] [--duration-tolerance 1.0]

Exit codes: 0 deliverable · 2 unreadable · 1 something named above is wrong.
"""
from __future__ import annotations

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


def probe(path: str, args: list[str]) -> str:
    result = subprocess.run(
        ["ffprobe", "-v", "error", *args, "-of", "default=nk=1:nw=1", path],
        capture_output=True, text=True, check=False,
    )
    return result.stdout.strip()


def measure_true_peak(path: str) -> float | None:
    result = subprocess.run(
        ["ffmpeg", "-hide_banner", "-i", path, "-af", "loudnorm=print_format=json",
         "-f", "null", os.devnull],
        capture_output=True, text=True, check=False,
    )
    match = re.search(r"\{[^{]*input_i.*?\}", result.stderr, re.S)
    if not match:
        return None
    try:
        return float(json.loads(match.group(0)).get("input_tp"))
    except (json.JSONDecodeError, TypeError, ValueError):
        return None


def poster_is_blank(path: str) -> bool:
    """A flat frame is a blank frame. Uses stdev, so a mid-grey card fails too."""
    try:
        from PIL import Image  # noqa: PLC0415 - optional, only needed for this check
        import numpy as np  # noqa: PLC0415
    except ImportError:
        return False  # cannot judge; do not invent a failure
    try:
        pixels = np.array(Image.open(path).convert("L"))
    except Exception:  # noqa: BLE001 - an unreadable poster is reported by the caller
        return True
    return float(pixels.std()) <= 12.0


def per_second_rms(path: str) -> list[float]:
    """RMS level for each second of the master, in dB.

    `asetnsamples` forces one frame per second; without it `astats` emits one row
    per ~21ms audio frame and every per-second reading is silently wrong.
    """
    result = subprocess.run(
        ["ffprobe", "-v", "error", "-f", "lavfi", "-i",
         f"amovie={path},asetnsamples=n=48000,astats=metadata=1:reset=1",
         "-show_entries", "frame_tags=lavfi.astats.Overall.RMS_level",
         "-of", "csv=p=0"],
        capture_output=True, text=True, check=False,
    )
    out = []
    for line in result.stdout.split():
        try:
            out.append(float(line))
        except ValueError:
            continue
    return out


def find_dead_tail(path: str, max_drop_db: float) -> str | None:
    """Does the audio die before the picture does?

    The bug this exists for: the ducked music was sidechained against the voice,
    and `sidechaincompress` ends when its SHORTER input ends — so a narration
    that finished early killed the score with it. A 64.1s film ran its last eight
    seconds in near-silence (-58 dB against a -17 dB body).

    NOTHING caught that. check_delivery passed: there IS an audio stream and the
    true peak is fine. The loudness gate passed: an average over 64s barely moves
    when eight seconds go quiet. It took a person listening to the delivered file.

    A designed fade-out is not a fault, so the final two seconds are excluded and
    the comparison is median-to-median rather than peak-to-trough.
    """
    levels = per_second_rms(path)
    if len(levels) < 12:
        return None                     # too short to have a meaningful tail
    body = sorted(levels[: len(levels) - 8])
    tail = sorted(levels[len(levels) - 8 : len(levels) - 2])
    if not body or not tail:
        return None
    body_med = body[len(body) // 2]
    tail_med = tail[len(tail) // 2]
    drop = body_med - tail_med
    if drop > max_drop_db:
        # Digital silence reads as -inf, which renders as an unhelpful "inf dB
        # below". Each branch is a COMPLETE clause: splicing a fragment into a
        # shared sentence produced "the last seconds is SILENT the body of the
        # film" the first time this fired.
        if tail_med == float("-inf"):
            what = "the last seconds are SILENT"
        else:
            what = (
                f"the last seconds sit {drop:.1f} dB below the body of the film "
                f"({tail_med:.1f} vs {body_med:.1f} dB)"
            )
        return (
            f"the audio dies before the picture does — {what}. A voice layer that ends "
            f"early takes the ducked music with it; pad the voice so the sidechain runs "
            f"the whole film"
        )
    return None


def detect_speech(path: str, max_no_speech_prob: float) -> tuple[list[str], str | None]:
    """Transcribe the master and return any CONFIDENT speech segments.

    Returns (findings, skip_reason). A missing whisper is reported as a skip,
    never as a pass — a check that quietly does nothing is the failure mode this
    whole file exists to close.

    Whisper hallucinates on silence ("You", "Thank you.", subtitle credits), so
    confidence is the discriminator, not the presence of text. Real dialogue in
    the delivered film scored no_speech_prob 0.224; the same window after the
    fix scored 0.821. The default cut at 0.30 sits well clear of both.
    """
    import shutil  # noqa: PLC0415 - only needed here
    import tempfile  # noqa: PLC0415

    if not shutil.which("whisper"):
        return [], "whisper is not installed, so the silent-film check did NOT run"

    with tempfile.TemporaryDirectory() as tmp:
        wav = os.path.join(tmp, "master.wav")
        extract = subprocess.run(
            ["ffmpeg", "-v", "error", "-i", path, "-ac", "1", "-ar", "16000", "-y", wav],
            capture_output=True, text=True, check=False,
        )
        if extract.returncode != 0 or not os.path.isfile(wav):
            return [], "could not extract audio, so the silent-film check did NOT run"
        run = subprocess.run(
            ["whisper", wav, "--model", "small", "--language", "en",
             "--output_format", "json", "--output_dir", tmp, "--fp16", "False"],
            capture_output=True, text=True, check=False,
        )
        transcript = os.path.join(tmp, "master.json")
        if run.returncode != 0 or not os.path.isfile(transcript):
            return [], "whisper failed, so the silent-film check did NOT run"
        try:
            with open(transcript, encoding="utf-8") as handle:
                segments = json.load(handle).get("segments", [])
        except (OSError, json.JSONDecodeError):
            return [], "whisper output was unreadable, so the silent-film check did NOT run"

    findings = []
    for segment in segments:
        text = str(segment.get("text", "")).strip()
        prob = segment.get("no_speech_prob")
        if not text or not isinstance(prob, (int, float)):
            continue
        # Whisper annotates NON-speech audio in brackets or music notes —
        # "[Music]", "(gentle flute)", '["Pomp and Circumstance"]', "♪♪♪". These
        # score as confident because the model is confident it heard something;
        # it just isn't a voice. Every film with a score would trip the gate
        # otherwise, and a gate that always fires gets switched off.
        if re.fullmatch(r"[\[\(♪].*[\]\)♪]", text, re.S):
            continue
        if prob < max_no_speech_prob:
            findings.append(
                f"{float(segment.get('start', 0)):.1f}s-{float(segment.get('end', 0)):.1f}s "
                f"(no_speech_prob {prob:.3f}): {text!r}"
            )
    return findings, None


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--master", required=True)
    ap.add_argument("--poster", default="")
    ap.add_argument("--max-true-peak", type=float, default=-0.5,
                    help="dBTP ceiling; above this the limiter did not hold")
    ap.add_argument("--silent", action="store_true",
                    help="this film has no dialogue — fail on any confident speech")
    ap.add_argument("--max-no-speech-prob", type=float, default=0.30,
                    help="below this, whisper is confident it heard real speech")
    ap.add_argument("--max-tail-drop-db", type=float, default=18.0,
                    help="how far the tail may sit below the body before it counts as dead air")
    ap.add_argument("--expect-seconds", type=float, default=0.0,
                    help="planned length (0 = do not check)")
    ap.add_argument("--duration-tolerance", type=float, default=1.0,
                    help="seconds of slack allowed against --expect-seconds")
    args = ap.parse_args()

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

    problems: list[str] = []

    if not probe(args.master, ["-select_streams", "a", "-show_entries", "stream=codec_type"]):
        problems.append("the delivered master has NO audio stream")
    else:
        peak = measure_true_peak(args.master)
        if peak is not None and peak > args.max_true_peak:
            problems.append(
                f"true peak {peak} dBTP is above {args.max_true_peak} — it is clipping, "
                f"so the limiter did not hold (is it AFTER the gain, with level=disabled?)"
            )

        dead_tail = find_dead_tail(args.master, args.max_tail_drop_db)
        if dead_tail:
            problems.append(dead_tail)

    if not probe(args.master, ["-select_streams", "v", "-show_entries", "stream=codec_type"]):
        problems.append("the delivered master has NO video stream")

    if args.poster:
        if not os.path.isfile(args.poster):
            problems.append(f"no poster frame at {args.poster}")
        elif poster_is_blank(args.poster):
            problems.append("the poster frame is blank or flat — pick a composed frame")

    if args.expect_seconds > 0:
        raw = probe(args.master, ["-show_entries", "format=duration"])
        try:
            actual = float(raw)
        except ValueError:
            problems.append("could not read the delivered duration")
        else:
            drift = abs(actual - args.expect_seconds)
            if drift > args.duration_tolerance:
                problems.append(
                    f"delivered {actual:.2f}s against a planned {args.expect_seconds:.2f}s "
                    f"— {drift:.2f}s out, over the {args.duration_tolerance:.2f}s tolerance"
                )

    if args.silent:
        speech, skipped = detect_speech(args.master, args.max_no_speech_prob)
        if skipped:
            # Say it rather than passing quietly. An unrun check that reports
            # success is how the dialogue shipped in the first place.
            print(f"  WARNING: {skipped}", file=sys.stderr)
        for finding in speech:
            problems.append(f"SPEECH in a film declared silent — {finding}")
        if speech:
            problems.append(
                "the render route generates audio regardless of generateAudio:false. "
                "Either re-render the shot named above (keeps the diegetic ambience), "
                "or re-run assemble with --drop-clip-audio and redeliver (loses it)"
            )

    for problem in problems:
        print(f"  {problem}", file=sys.stderr)
    if problems:
        raise SystemExit(1)
    print(f"check_delivery: {os.path.basename(args.master)} is deliverable", file=sys.stderr)


if __name__ == "__main__":
    main()
