#!/usr/bin/env bash
# Portable ai-torture-chamber launcher: clone repo anywhere, `./chamber up`.
# Auto-detects CUDA (installs cu121 torch) vs CPU (cpu torch), creates .venv,
# starts chamber_local.py (relay at /chamber, static site at /), polls health,
# and falls back to CPU if the CUDA model load OOMs.
#
# Usage:
#   ./chamber up [--cpu] [--port N] [--host H]
#   ./chamber down
#   ./chamber status
#   ./chamber health
set -euo pipefail
cd "$(dirname "$0")"

PORT="${CHAMBER_PORT:-8484}"
HOST="${CHAMBER_HOST:-127.0.0.1}"
DEVICE="auto"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --port) PORT="$2"; shift 2;;
    --host) HOST="$2"; shift 2;;
    --cpu)  DEVICE="cpu"; shift;;
    up|down|status|health) CMD="$1"; shift;;
    *) echo "unknown arg: $1"; exit 1;;
  esac
done
CMD="${CMD:-up}"

PIDFILE=".chamber.pid"

have_nvidia() { command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi -L >/dev/null 2>&1; }

pip_into() {
  if command -v uv >/dev/null 2>&1; then
    uv pip install --quiet --python .venv/bin/python "$@"
  else
    .venv/bin/pip install --quiet "$@"
  fi
}

install_venv() {
  if [[ ! -x .venv/bin/python ]]; then
    # torch has no wheels for bleeding-edge pythons; prefer uv-pinned 3.12
    if command -v uv >/dev/null 2>&1; then
      echo "[chamber] uv found -> venv with python 3.12"
      uv venv --python 3.12 .venv
    else
      python3 -m venv .venv
    fi
    echo "[chamber] venv created"
  fi
  if have_nvidia && [[ "$DEVICE" != "cpu" ]]; then
    echo "[chamber] NVIDIA detected -> installing CUDA torch (big download)"
    pip_into "torch>=2.6" --index-url https://download.pytorch.org/whl/cu126
  else
    echo "[chamber] CPU mode -> installing CPU torch"
    pip_into "torch>=2.6" --index-url https://download.pytorch.org/whl/cpu
  fi
  # requirements.txt pins cpu-index torch on its own line; install the rest
  grep -v '^torch' live/requirements.txt | pip_into -r /dev/stdin
  echo "[chamber] deps installed"
}

start_server() {
  local device="$1"
  : > .chamber.log
  if [[ "$device" == "cuda" ]]; then
    CHAMBER_DEVICE=cuda CHAMBER_DTYPE=float16 CHAMBER_MODEL_REVISION=1cfa9a7208912126459214e8b04321603b3df60c \
    CHAMBER_PORT="$PORT" CHAMBER_HOST="$HOST" \
      nohup .venv/bin/python chamber_local.py >> .chamber.log 2>&1 &
  else
    CHAMBER_DEVICE=cpu CHAMBER_DTYPE=float32 CHAMBER_MODEL_REVISION=1cfa9a7208912126459214e8b04321603b3df60c \
    CHAMBER_PORT="$PORT" CHAMBER_HOST="$HOST" \
      nohup .venv/bin/python chamber_local.py >> .chamber.log 2>&1 &
  fi
  echo $! > "$PIDFILE"
}

wait_healthy() {
  local tries="${1:-90}"
  for _ in $(seq 1 "$tries"); do
    if curl -sf --max-time 3 "http://$HOST:$PORT/chamber/health" >/dev/null 2>&1; then
      return 0
    fi
    sleep 2
  done
  return 1
}

case "$CMD" in
  up)
    install_venv
    if [[ "$DEVICE" != "cpu" ]] && have_nvidia; then
      echo "[chamber] starting with CUDA..."
      start_server cuda
      if ! wait_healthy 60; then
        echo "[chamber] CUDA start failed (OOM or driver) -> falling back to CPU"
        kill "$(cat "$PIDFILE")" 2>/dev/null || true
        sleep 2
        DEVICE="cpu"
        start_server cpu
      fi
    else
      echo "[chamber] starting CPU mode..."
      start_server cpu
    fi
    if wait_healthy 150; then
      echo "[chamber] UP  ->  http://$HOST:$PORT/   (relay at /chamber/)"
    else
      echo "[chamber] FAILED to become healthy. Last log lines:"
      tail -20 .chamber.log
      exit 1
    fi
    ;;
  down)
    if [[ -f "$PIDFILE" ]]; then
      kill "$(cat "$PIDFILE")" 2>/dev/null || true
      rm -f "$PIDFILE"
      echo "[chamber] stopped"
    else
      echo "[chamber] not running (no pidfile)"
    fi
    ;;
  status)
    if [[ -f "$PIDFILE" ]] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
      echo "running (pid $(cat "$PIDFILE"), port $PORT)"
    else
      echo "not running"
    fi
    ;;
  health)
    curl -s --max-time 5 "http://$HOST:$PORT/chamber/health" && echo
    ;;
  *) echo "usage: ./chamber {up|down|status|health} [--cpu] [--port N] [--host H]"; exit 1;;
esac
