#!/bin/bash
# 19106-vsr-upscale service launcher (container port 8082).
# Venv lives on container-local disk /home/agent/vsr-venv (NOT in project:
# the project bind mount to Windows is too slow for torch's many files).
# On a container RECREATE the local venv is gone; this script rebuilds it.
# On a simple restart it is preserved and reuse is fast.
cd /home/agent/.claude/workspace/project || exit 1
mkdir -p uploads outputs data static logs weights
exec >> logs/start.log 2>&1
echo "[$(date -Iseconds)] vsr start"

if ! command -v ffmpeg >/dev/null 2>&1; then
  echo "ffmpeg missing, installing via apt"
  sudo apt-get update -qq && sudo apt-get install -y ffmpeg python3.11-venv python3-dev
fi

VENV=/home/agent/vsr-venv
if [ ! -x "$VENV/bin/python" ]; then
  echo "venv missing, creating $VENV"
  python3 -m venv "$VENV"
fi
# NOTE: basicsr is NOT used (vendored realbasicvsr_arch.py only needs
# torch/cv2/flask). Do NOT add basicsr back: basicsr 1.4.2 is incompatible
# with torchvision 0.29 (functional_tensor removed) and its import fails.
if ! "$VENV/bin/python" -c "import torch, cv2, flask" 2>/dev/null; then
  echo "deps missing, installing (torch cu130 + flask + opencv)"
  export PIP_CACHE_DIR=/tmp/pipcache
  "$VENV/bin/pip" install --upgrade pip
  "$VENV/bin/pip" install torch torchvision --index-url https://download.pytorch.org/whl/cu130
  "$VENV/bin/pip" install flask opencv-python-headless numpy Pillow
fi

# Kill stale app, start fresh. Pattern must match the app's own cmdline
# (vsr-venv/bin/python app.py); do NOT use a pattern that also matches
# this script's own command line, or pkill kills the launcher itself.
pkill -f "vsr-venv/bin/python app.py" 2>/dev/null; sleep 2
nohup "$VENV/bin/python" app.py > logs/app.log 2>&1 &
echo "app pid $! started, waiting for 8082"
for i in $(seq 1 60); do
  if curl -sf http://127.0.0.1:8082/health >/dev/null 2>&1; then
    echo "[$(date -Iseconds)] vsr up on 8082"
    exit 0
  fi
  sleep 2
done
echo "WARNING: 8082 not up after 120s, see logs/app.log"
