#!/usr/bin/env bash
# crop_windows.sh — THE CORPUS-COHERENCE BENCH, STEP 2 cropper.
#
# Registered by PREREG-COHERENCE.md §4.2 / §10.3 (sealed
# 4bbe9548945d1bd849b355a080b49c481c067e21fd105e98d8d6d30c9f2fe5f2).
# Cuts one 10 s window per plan row with the EXACT registered ffmpeg form.
#
#   mode=norm : §4.2 primary  — mono, 48 kHz, loudnorm I=-16 TP=-1.0 LRA=11, 16-bit PCM
#   mode=raw  : §4.4 arm S1   — mono, 48 kHz, LEVEL UNTOUCHED,             16-bit PCM
#
# Usage:  crop_windows.sh <plan.tsv> [parallelism]
#   plan.tsv columns (TAB separated, no header): out_path  src_path  start_seconds  mode
#
# TMPDIR must already point at the run's own disk (never /tmp) — see §10.2.

set -uo pipefail

SELF="$(readlink -f "$0")"

crop_one() {
  local out="$1" src="$2" start="$3" mode="$4"
  if [ "$mode" = "norm" ]; then
    ffmpeg -nostdin -v error -ss "$start" -t 10 -i "$src" \
      -ac 1 -ar 48000 \
      -af loudnorm=I=-16:TP=-1.0:LRA=11:print_format=summary \
      -c:a pcm_s16le -y "$out" </dev/null
  else
    ffmpeg -nostdin -v error -ss "$start" -t 10 -i "$src" \
      -ac 1 -ar 48000 \
      -c:a pcm_s16le -y "$out" </dev/null
  fi
  local rc=$?
  if [ $rc -ne 0 ] || [ ! -s "$out" ]; then
    echo "CROP-FAIL rc=$rc mode=$mode start=$start src=$src" >&2
    return 1
  fi
  return 0
}

if [ "${1:-}" = "__one" ]; then
  shift
  crop_one "$@"
  exit $?
fi

PLAN="${1:?usage: crop_windows.sh <plan.tsv> [parallelism]}"
PAR="${2:-8}"

[ -n "${TMPDIR:-}" ] || { echo "TMPDIR unset — §10.2 requires the run's own disk" >&2; exit 2; }

# NUL-delimit so paths containing spaces survive xargs.
awk -F'\t' 'NF>=4 { printf "%s%c%s%c%s%c%s%c", $1, 0, $2, 0, $3, 0, $4, 0 }' "$PLAN" \
  | xargs -0 -n4 -P "$PAR" "$SELF" __one

echo "crop_windows.sh: finished plan=$PLAN rows=$(wc -l < "$PLAN") par=$PAR"
