#!/usr/bin/env bash
# Fit a take to an aspect, set loudness to -14 LUFS (two passes) and add faststart.
# Usage: finish_ad.sh in.mp4 out.mp4 [9:16|4:5|1:1|16:9] [blur|pad|crop]
set -euo pipefail

usage="usage: finish_ad.sh in.mp4 out.mp4 [9:16|4:5|1:1|16:9] [blur|pad|crop]"
in="${1:?$usage}"
out="${2:?$usage}"
aspect="${3:-9:16}"
fit="${4:-blur}"
ff="${FFMPEG:-ffmpeg}"

case "$aspect" in
  9:16) w=1080; h=1920 ;;
  4:5) w=1080; h=1350 ;;
  1:1) w=1080; h=1080 ;;
  16:9) w=1920; h=1080 ;;
  *) echo "aspect must be 9:16, 4:5, 1:1 or 16:9" >&2; exit 2 ;;
esac

case "$fit" in
  pad) vf="[0:v]scale=${w}:${h}:force_original_aspect_ratio=decrease,pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=30,format=yuv420p[v]" ;;
  crop) vf="[0:v]scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},setsar=1,fps=30,format=yuv420p[v]" ;;
  blur) vf="[0:v]split=2[bg][fg];[bg]scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},gblur=sigma=40[bg];[fg]scale=${w}:${h}:force_original_aspect_ratio=decrease[fg];[bg][fg]overlay=(W-w)/2:(H-h)/2,setsar=1,fps=30,format=yuv420p[v]" ;;
  *) echo "fit must be blur, pad or crop" >&2; exit 2 ;;
esac

[ -f "$in" ] || { echo "not found: $in" >&2; exit 2; }

audio=()
info=$("$ff" -hide_banner -i "$in" 2>&1 || true)
if [[ "$info" == *"Audio:"* ]]; then
  stats=$("$ff" -hide_banner -nostats -i "$in" -vn -af loudnorm=I=-14:TP=-1.0:LRA=11:print_format=json -f null - 2>&1 || true)
  field() { printf '%s\n' "$stats" | grep "\"$1\"" | tail -n 1 | sed -E 's/.*: *"([^"]*)".*/\1/'; }
  mi=$(field input_i); mtp=$(field input_tp); mlra=$(field input_lra); mth=$(field input_thresh); off=$(field target_offset)
  if [ -n "$mi" ] && [ "$mi" != "-inf" ] && [ -n "$mtp" ] && [ "$mtp" != "-inf" ]; then
    af="loudnorm=I=-14:TP=-1.0:LRA=11:measured_I=${mi}:measured_TP=${mtp}:measured_LRA=${mlra}:measured_thresh=${mth}:offset=${off}:linear=true,aresample=48000"
  else
    af="aresample=48000"
  fi
  audio=(-map 0:a:0 -af "$af" -c:a aac -b:a 192k -ar 48000 -ac 2)
fi

"$ff" -hide_banner -loglevel error -y -i "$in" -filter_complex "$vf" -map "[v]" ${audio[@]+"${audio[@]}"} \
  -c:v libx264 -preset medium -crf 18 -movflags +faststart "$out"
echo "$out"
