#!/usr/bin/env bash
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

INPUT=""
OUTPUT=""

MODEL_WIDTH=480
MODEL_HEIGHT=270
OUTPUT_WIDTH=1920
OUTPUT_HEIGHT=1080

usage() {
  cat <<EOF2
Usage: $(basename "$0") <input_video> [-o <output>]

  -o, --output   Output path (default: <input>_smart_v2_1920x1080.mp4)
  -h, --help     Show this help
EOF2
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    -o|--output) OUTPUT="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    -*) echo "Unknown option: $1" >&2; usage; exit 2 ;;
    *) INPUT="$1"; shift ;;
  esac
done

[[ -z "$INPUT" ]] && { echo "Error: input video required" >&2; usage; exit 2; }
[[ ! -f "$INPUT" ]] && { echo "Error: input not found: $INPUT" >&2; exit 1; }

FFPROBE="$DIR/bin/ffprobe"
if [[ ! -x "$FFPROBE" ]]; then
  if command -v ffprobe &>/dev/null; then
    FFPROBE="$(command -v ffprobe)"
  else
    echo "Error: ffprobe not found. Run install.sh first." >&2
    exit 1
  fi
fi

if [[ -f "$DIR/.venv/bin/activate" ]]; then
  # shellcheck disable=SC1091
  source "$DIR/.venv/bin/activate"
fi
PYTHON="${PYTHON:-python3}"

read -r in_w in_h <<<"$($FFPROBE -v error -select_streams v:0 -show_entries stream=width,height -of default=nw=1:nk=1 "$INPUT" | tr '\n' ' ')"
[[ -n "$in_w" && -n "$in_h" ]] || { echo "Error: probe failed" >&2; exit 1; }

if [[ -z "$OUTPUT" ]]; then
  OUTPUT="${INPUT%.*}_smart_v2_${OUTPUT_WIDTH}x${OUTPUT_HEIGHT}.mp4"
fi
OUTPUT="$(realpath -m "$OUTPUT")"

echo "Input:     ${in_w}x${in_h}"
echo "Pre-scale: in-memory lanczos -> ${MODEL_WIDTH}x${MODEL_HEIGHT}"
echo "AI stage:  Real-ESRGAN general-x4v3 x4 -> ${OUTPUT_WIDTH}x${OUTPUT_HEIGHT}"

if (( in_w == MODEL_WIDTH && in_h == MODEL_HEIGHT )); then
  echo "[stage 0] input already at ${MODEL_WIDTH}x${MODEL_HEIGHT}, Lanczos pre-scale skipped."
else
  echo "[stage 0] in-memory Lanczos ${in_w}x${in_h} -> ${MODEL_WIDTH}x${MODEL_HEIGHT}"
fi

echo "[stage 1] Real-ESRGAN x4 ${MODEL_WIDTH}x${MODEL_HEIGHT} -> ${OUTPUT_WIDTH}x${OUTPUT_HEIGHT}"
"$PYTHON" "$DIR/sr_video_ov.py" "$INPUT" -o "$OUTPUT"
