#!/usr/bin/env bash
# media.sh — asset inspection toolkit for the film pipeline.
# Lets an agent (or a human) probe generated shots and reference stills.
#
#   ./tools/media.sh probe   <file>            technical summary
#   ./tools/media.sh frames  <video> [n] [out] n evenly spaced stills (default 6)
#   ./tools/media.sh sheet   <video> [n] [out] one contact-sheet PNG (default 12)
#   ./tools/media.sh first   <video> [out]     the first frame only (first-frame lock check)
#   ./tools/media.sh audio   <video>           speech/silence map, for the 1s-tail rule
#   ./tools/media.sh loudness <video> [--target L] [--tol T] [--peak P]
#                                              EBU R128; with --target it ENFORCES and exits 1
#   ./tools/media.sh img     <image> [--luma-min N] [--luma-max N] [--aspect-min F] [--aspect-max F]
#                                              stills; with limits it ENFORCES and exits 1
#
# Frames are written as PNG so an agent can read them directly.
# Design rule: this tool must fail loudly. A gate that silently reports "fine"
# on an unreadable file is worse than no gate at all.

set -euo pipefail
export PATH="/opt/homebrew/bin:$PATH"

die() { echo "media.sh: $*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "missing dependency: $1"; }

# stem <path> -> basename with only a real extension stripped.
# basename first, so a dot in a parent directory is never mistaken for one.
stem() { local b; b=$(basename -- "$1"); case "$b" in ?*.*) printf '%s' "${b%.*}";; *) printf '%s' "$b";; esac; }

# duration <file> -> seconds as a positive float, or die.
duration() {
  local f="$1" d
  d=$(ffprobe -v error -show_entries format=duration -of csv=p=0 -- "$f" 2>/dev/null || true)
  if [ -z "$d" ] || [ "$d" = "N/A" ]; then
    d=$(ffprobe -v error -select_streams v:0 -show_entries stream=duration -of csv=p=0 -- "$f" 2>/dev/null || true)
  fi
  case "$d" in
    ''|N/A) die "cannot read duration from '$f' (unreadable, or a stream with no declared duration)";;
  esac
  python3 -c "
import sys
try: v=float('$d')
except ValueError: sys.exit('media.sh: duration not numeric: $d')
if v<=0: sys.exit('media.sh: duration must be > 0, got %r' % v)
print(v)"
}

# posint <value> <label> -> echo it, or die.
posint() {
  case "$2" in ''|*[!0-9]*) die "$1 must be a positive integer, got '$2'";; esac
  [ "$2" -gt 0 ] || die "$1 must be > 0, got '$2'"
  printf '%s' "$2"
}

infile() { [ -f "$1" ] || die "no such file: $1"; }

cmd="${1:-}"; shift || true
[ -n "$cmd" ] || die "usage: media.sh {probe|frames|sheet|first|firstsec|audio|loudness|transcribe|img} <file> [...]"

case "$cmd" in

probe)
  need ffprobe; f="${1:?file required}"; infile "$f"
  ffprobe -v error -show_entries \
    format=duration,size,bit_rate,format_name \
    -show_entries stream=index,codec_type,codec_name,width,height,r_frame_rate,duration,nb_frames,sample_rate,channels \
    -of default=noprint_wrappers=1 -- "$f" \
    || die "ffprobe failed on '$f' (corrupt or unsupported)"
  ;;

frames|sheet)
  need ffmpeg; need ffprobe; need python3
  f="${1:?video required}"; infile "$f"
  [ "$cmd" = frames ] && def=6 || def=12
  n=$(posint "frame count" "${2:-$def}")
  out="${3:-./_frames}"; mkdir -p "$out"
  dur=$(duration "$f")
  base=$(stem "$f")
  work="$out"; [ "$cmd" = sheet ] && work=$(mktemp -d)
  trap '[ "$cmd" = sheet ] && [ -n "${work:-}" ] && rm -rf "$work"' EXIT

  # drawtext is optional — probe the filter once instead of using a blind retry,
  # so a genuine decode/seek error is never misread as a missing font filter.
  label=1
  ffmpeg -nostdin -v error -f lavfi -i color=c=black:s=64x64:d=0.1 \
    -vf "drawtext=text='x':fontsize=10" -frames:v 1 -f null - >/dev/null 2>&1 || label=0

  i=1
  while [ "$i" -le "$n" ]; do
    t=$(python3 -c "print(round($dur*($i-0.5)/$n,3))")
    o="$work/${base}_$(printf '%03d' "$i")_${t}s.png"
    if [ "$label" = 1 ] && [ "$cmd" = frames ]; then
      vf="drawtext=text='t=${t}s':x=12:y=12:fontsize=28:fontcolor=yellow:box=1:boxcolor=black@0.5"
      ffmpeg -nostdin -v error -ss "$t" -i "$f" -frames:v 1 -vf "$vf" -y -- "$o" \
        || die "frame extraction failed at t=${t}s in '$f'"
    else
      ffmpeg -nostdin -v error -ss "$t" -i "$f" -frames:v 1 -y -- "$o" \
        || die "frame extraction failed at t=${t}s in '$f'"
    fi
    [ -s "$o" ] || die "ffmpeg produced an empty frame at t=${t}s (seek past end?)"
    i=$((i+1))
  done

  if [ "$cmd" = frames ]; then
    echo "wrote $n frames -> $out"; ls -1 "$out"
  else
    cols=$(python3 -c "import math;print(min(4,max(1,math.ceil(math.sqrt($n)))))")
    rows=$(python3 -c "import math;print(math.ceil($n/$cols))")
    o="$out/${base}_sheet.png"
    # tiling exactly the n stills sampled above: no re-sampling by fps, so a cell
    # is never a duplicate. Trailing cells in the grid stay blank when n < cols*rows.
    ffmpeg -nostdin -v error -pattern_type glob -i "$work/${base}_*.png" \
      -vf "scale=480:-1,tile=${cols}x${rows}" -frames:v 1 -y -- "$o" \
      || die "tiling failed for '$f'"
    echo "wrote $o  (${cols}x${rows} grid, $n sampled frames)"
  fi
  ;;

first)
  need ffmpeg; f="${1:?video required}"; infile "$f"
  out="${2:-./_frames}"; mkdir -p "$out"
  o="$out/$(stem "$f")_frame001.png"
  ffmpeg -nostdin -v error -i "$f" -frames:v 1 -y -- "$o" || die "could not decode first frame of '$f'"
  [ -s "$o" ] || die "first frame decoded empty for '$f'"
  echo "wrote $o  (check: are all required subjects already in position?)"
  ;;

audio)
  need ffprobe; need ffmpeg
  f="${1:?video required}"; infile "$f"
  # distinguish "probe failed" from "no audio stream" — conflating them turns a
  # corrupt file into a passing gate.
  if ! streams=$(ffprobe -v error -select_streams a -show_entries stream=index -of csv=p=0 -- "$f" 2>&1); then
    die "ffprobe failed on '$f': $streams"
  fi
  if [ -z "$streams" ]; then
    echo "no audio stream"; exit 0
  fi
  echo "== silence map (threshold -35dB, min 0.4s) =="
  sil=$(ffmpeg -nostdin -v info -i "$f" -af silencedetect=noise=-35dB:d=0.4 -f null - 2>&1) \
    || die "ffmpeg silencedetect failed on '$f'"
  echo "$sil" | grep -E 'silence_(start|end|duration)' || echo "(no silence detected at threshold)"
  echo "== mean/peak volume =="
  vol=$(ffmpeg -nostdin -v info -i "$f" -af volumedetect -f null - 2>&1) \
    || die "ffmpeg volumedetect failed on '$f'"
  echo "$vol" | grep -E 'mean_volume|max_volume' || echo "(volumedetect reported nothing)"
  ;;

transcribe)
  # LESSONS L1: intelligibility gate. Prints whisper's transcript of the clip's audio
  # (Mandarin by default; pass a language code as $2). Compare by eye with the card's line.
  need ffmpeg; need whisper-cli
  f="${1:?video required}"; infile "$f"
  lang="${2:-zh}"
  model="${WHISPER_MODEL:-$HOME/.cache/whisper/ggml-large-v3-turbo.bin}"
  [ -f "$model" ] || die "whisper model not found: $model (set WHISPER_MODEL)"
  tmp=$(mktemp -t media_wav).wav
  ffmpeg -nostdin -y -v error -i "$f" -vn -ac 1 -ar 16000 -c:a pcm_s16le "$tmp" \
    || die "ffmpeg wav extract failed on '$f'"
  out=$(whisper-cli -m "$model" -l "$lang" -nt -np -f "$tmp" 2>/dev/null | grep -v '^$') \
    || die "whisper-cli failed on '$f'"
  rm -f "$tmp"
  [ -n "$out" ] && echo "$out" || echo "(no speech recognised)"
  ;;

firstsec)
  # LESSONS L7: settle-in gate. Samples the first 1.2 s at 12 fps, tracks the centroid of a
  # colour mask (default: Crystal's saffron bodice) and prints the max drift in px. Also writes
  # a strip. Usage: media.sh firstsec <clip> <outdir> [x0 x1 as fractions of width for the crop]
  need ffmpeg
  f="${1:?video required}"; infile "$f"; out="${2:?outdir required}"; mkdir -p "$out"
  x0="${3:-0.30}"; x1="${4:-0.60}"
  python3 - "$f" "$out" "$x0" "$x1" <<'PY'
import sys,subprocess,os,tempfile; from PIL import Image; import numpy as np
f,out,x0,x1=sys.argv[1],sys.argv[2],float(sys.argv[3]),float(sys.argv[4])
base=os.path.splitext(os.path.basename(f))[0]; tmp=tempfile.mkdtemp()
ts=[i/12 for i in range(15)]; ims=[]; cs=[]
for t in ts:
    o=f"{tmp}/{t:.3f}.png"; subprocess.run(["ffmpeg","-y","-loglevel","error","-ss",str(t),"-i",f,"-frames:v","1",o])
    im=Image.open(o).convert('RGB'); W,H=im.size
    a=np.asarray(im).astype(int); r,g,b=a[...,0],a[...,1],a[...,2]
    m=(r>150)&(g>100)&(b<90)&(r-b>90)&(g>0.55*r)
    win=np.zeros_like(m); win[:int(H*0.55), int(W*x0):int(W*x1)]=True; m=m&win
    ys,xs=np.nonzero(m)
    cs.append((xs.mean() if len(xs) else float('nan'), ys.mean() if len(ys) else float('nan'), int(m.sum())))
    ims.append(im.crop((int(W*x0),0,int(W*x1),H)).resize((240,720)))
sheet=Image.new('RGB',(8*240,2*720),'black')
for i,im in enumerate(ims): sheet.paste(im,((i%8)*240,(i//8)*720))
sheet.save(f"{out}/{base}_firstsec.jpg",quality=85)
xs=[c[0] for c in cs]; ys=[c[1] for c in cs]
print("t     cx     cy     px")
for t,c in zip(ts,cs): print(f"{t:.2f}  {c[0]:6.1f} {c[1]:6.1f} {c[2]}")
dx=max(xs)-min(xs); dy=max(ys)-min(ys)
print(f"max drift: dx={dx:.1f} dy={dy:.1f} px over 1.2 s  -> {'FAIL (>5 px)' if max(dx,dy)>5 else 'PASS'}")
print(f"wrote {out}/{base}_firstsec.jpg")
PY
  ;;

loudness)
  need ffmpeg; need ffprobe
  f="${1:?video required}"; infile "$f"
  if ! streams=$(ffprobe -v error -select_streams a -show_entries stream=index -of csv=p=0 -- "$f" 2>&1); then
    die "ffprobe failed on '$f': $streams"
  fi
  [ -n "$streams" ] || die "no audio stream in '$f' — cannot measure loudness"
  # EBU R128 via ffmpeg's ebur128 filter. Gives the numbers G7 and delivery actually need.
  target=""; tol="1.0"; peak=""
  while [ $# -gt 1 ]; do
    case "$2" in
      --target) target="${3:?--target needs a value}"; shift 2;;
      --tol)    tol="${3:?--tol needs a value}";       shift 2;;
      --peak)   peak="${3:?--peak needs a value}";     shift 2;;
      *) die "unknown loudness option: $2";;
    esac
  done
  out=$(ffmpeg -nostdin -v info -i "$f" -af ebur128=peak=true -f null - 2>&1) \
    || die "ffmpeg ebur128 failed on '$f'"
  sum=$(echo "$out" | awk '/Integrated loudness/,0')
  echo "$sum" | grep -E 'I:|LRA:|Peak:|Threshold:|LRA low|LRA high' \
    || die "ebur128 produced no summary for '$f' (clip too short? needs >~0.4s)"
  # Enforcement: without --target this only reports, and the caller must not claim a gate.
  [ -n "$target" ] || exit 0
  I=$(echo "$sum"  | awk '/^ *I: /{print $2}')
  TP=$(echo "$sum" | awk '/^ *Peak: /{print $2}')
  python3 - "$I" "$TP" "$target" "$tol" "${peak:-}" <<'PYCHK'
import sys
I, TP, target, tol, peak = sys.argv[1:6]
fails = []
try:
    I, target, tol = float(I), float(target), float(tol)
except ValueError:
    sys.exit(f"media.sh: could not parse integrated loudness {I!r}")
if abs(I - target) > tol:
    fails.append(f"integrated {I:+.1f} LUFS is {abs(I-target):.1f} LU off target {target:+.1f} (tol ±{tol})")
if peak:
    try:
        if float(TP) > float(peak):
            fails.append(f"true peak {float(TP):+.1f} dBTP exceeds ceiling {float(peak):+.1f}")
    except ValueError:
        sys.exit(f"media.sh: could not parse true peak {TP!r}")
if fails:
    print("G7 FAIL:"); [print("  " + f) for f in fails]; sys.exit(1)
print(f"G7 PASS: integrated {I:+.1f} LUFS within ±{tol} of {target:+.1f}" + (f", true peak {TP} dBTP under {peak}" if peak else ""))
PYCHK
  ;;

img)
  need python3; f="${1:?image required}"; infile "$f"; shift
  python3 - "$f" "$@" <<'PY'
import sys
try:
    from PIL import Image
except ImportError:
    sys.exit("media.sh: missing dependency: Pillow (pip3 install --user Pillow)")
p = sys.argv[1]
try:
    im = Image.open(p); im.load()
except Exception as e:
    sys.exit(f"media.sh: cannot read image {p}: {e}")
print(f"file       {p}")
print(f"format     {im.format}")
print(f"size       {im.size[0]}x{im.size[1]}  ({im.size[0]/im.size[1]:.3f} aspect)")
print(f"mode       {im.mode}")
rgb = im.convert("RGB")
small = rgb.resize((160, 160))
px = list(small.getdata())
luma = sum(0.2126*r + 0.7152*g + 0.0722*b for r, g, b in px) / len(px)
print(f"mean luma  {luma:.1f}/255")
q = rgb.convert("P", palette=Image.ADAPTIVE, colors=6).convert("RGB")
counts = {}
for c in q.resize((160, 160)).getdata():
    counts[c] = counts.get(c, 0) + 1
tot = sum(counts.values())
print("palette    (top 6, against the world's stated split)")
for c, n in sorted(counts.items(), key=lambda kv: -kv[1])[:6]:
    print(f"           #{c[0]:02x}{c[1]:02x}{c[2]:02x}  {100*n/tot:5.1f}%")

# --- enforcement: only when limits are supplied, so a bare call never fakes a gate ---
import argparse
ap = argparse.ArgumentParser(add_help=False)
ap.add_argument("--luma-min", type=float); ap.add_argument("--luma-max", type=float)
ap.add_argument("--aspect-min", type=float); ap.add_argument("--aspect-max", type=float)
a, _ = ap.parse_known_args(sys.argv[2:])
limits = [a.luma_min, a.luma_max, a.aspect_min, a.aspect_max]
if all(v is None for v in limits):
    sys.exit(0)
aspect = im.size[0] / im.size[1]
fails = []
if a.luma_min is not None and luma < a.luma_min:
    fails.append(f"mean luma {luma:.1f} below minimum {a.luma_min}")
if a.luma_max is not None and luma > a.luma_max:
    fails.append(f"mean luma {luma:.1f} above maximum {a.luma_max}")
if a.aspect_min is not None and aspect < a.aspect_min:
    fails.append(f"aspect {aspect:.3f} below minimum {a.aspect_min}")
if a.aspect_max is not None and aspect > a.aspect_max:
    fails.append(f"aspect {aspect:.3f} above maximum {a.aspect_max}")
if fails:
    print("G2 FAIL:"); [print("  " + f) for f in fails]; sys.exit(1)
print("G2 PASS: within stated limits")
PY
  ;;

*) die "unknown command: $cmd" ;;
esac
