#!/usr/bin/env bash
set -u -o pipefail  # NOTE: no "set -e" (we handle errors per-file)

if [[ $# -lt 1 || $# -gt 2 ]]; then
  echo "Usage: $0 <source_dir> [output_dir]"
  exit 1
fi

SRC_DIR="$(cd "$1" && pwd)"
OUT_DIR="${2:-$SRC_DIR}"
mkdir -p "$OUT_DIR"

CRF="${CRF:-20}"
PRESET="${PRESET:-medium}"
AUDIO_BR="${AUDIO_BR:-192k}"

ok=0
fail=0
skipped=0

log_err() { echo "ERROR: $*" >&2; }

# Use process substitution (no pipeline) so the loop is stable.
while IFS= read -r -d '' in; do
  # If file is missing (race / weird paths), skip and continue
  if [[ ! -f "$in" ]]; then
    log_err "Missing input file (skipping): $in"
    ((fail++))
    continue
  fi

  # Compute relative path safely
  rel="${in#$SRC_DIR/}"
  if [[ "$rel" == "$in" ]]; then
    # Fallback if prefix stripping fails for any reason
    rel="$(basename "$in")"
  fi

  out="$OUT_DIR/${rel%.*}.appletv.mp4"
  out_dir="$(dirname "$out")"
  mkdir -p "$out_dir"

  if [[ -f "$out" ]]; then
    echo "SKIP (exists): $out"
    ((skipped++))
    continue
  fi

  echo "Processing: $in"

  # Probe codecs (don’t abort batch on probe error)
  vcodec="$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name \
            -of default=nk=1:nw=1 "$in" 2>/dev/null || true)"
  acodec="$(ffprobe -v error -select_streams a:0 -show_entries stream=codec_name \
            -of default=nk=1:nw=1 "$in" 2>/dev/null || true)"

  # Try remux if looks compatible
  remux_attempted=0
  if [[ "$vcodec" =~ ^(h264|hevc)$ ]] && [[ "$acodec" =~ ^(aac|ac3|eac3)$ ]]; then
    remux_attempted=1
    echo "  -> Remux (no re-encode)"
    if ffmpeg -hide_banner -nostdin -y -i "$in" \
      -map 0:v:0 -map 0:a:0? \
      -c copy -movflags +faststart \
      "$out" >/dev/null 2>&1; then
      echo "DONE: $out"
      ((ok++))
      continue
    else
      rm -f "$out" >/dev/null 2>&1 || true
      echo "  -> Remux failed, will re-encode"
    fi
  fi

  # Re-encode fallback (Apple TV / iPad safe)
  echo "  -> Re-encode H.264 + AAC"
  if ffmpeg -hide_banner -nostdin -y -i "$in" \
    -map 0:v:0 -map 0:a:0? \
    -c:v libx264 -crf "$CRF" -preset "$PRESET" -pix_fmt yuv420p \
    -c:a aac -b:a "$AUDIO_BR" -ac 2 \
    -movflags +faststart \
    "$out"; then
    echo "DONE: $out"
    ((ok++))
  else
    rm -f "$out" >/dev/null 2>&1 || true
    log_err "Failed converting: $in"
    ((fail++))
    continue
  fi

done < <(find "$SRC_DIR" -type f -iname "*.mkv" -print0)

echo
echo "Summary: OK=$ok  FAILED=$fail  SKIPPED=$skipped"
exit 0

