#!/usr/bin/env bash
# Local code verification (unit tests + /health + JWT 401).
# Usage:
#   bash scripts/local_integration_smoke.sh
#   bash scripts/local_integration_smoke.sh --start
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

MODE="${1:---code-only}"
BASE="${NEXUS_TEST_BASE:-http://127.0.0.1:8600}"

if [[ -x "${ROOT}/.venv/bin/python3" ]]; then
  PY="${ROOT}/.venv/bin/python3"
else
  PY="python3"
fi

ok() { echo "[OK] $*"; }
fail() { echo "[FAIL] $*"; exit 1; }
warn() { echo "[WARN] $*"; }

docker_cmd() {
  if docker info >/dev/null 2>&1; then
    docker "$@"
  else
    sg docker -c "docker $(printf '%q ' "$@")"
  fi
}

redis_ping() {
  if command -v redis-cli >/dev/null 2>&1; then
    redis-cli -h 127.0.0.1 ping 2>/dev/null | grep -q PONG && return 0
  fi
  docker_cmd exec nexus-redis-1 redis-cli ping 2>/dev/null | grep -q PONG
}

verify_code() {
  echo "=== Nexus local code verification ==="
  python3 --version >/dev/null 2>&1 || fail "python3 missing"
  ok "python3 $(python3 --version 2>&1 | awk '{print $2}')"

  if [[ "$PY" != "python3" ]]; then
    ok "venv ${PY}"
  else
    warn "no .venv — run: bash scripts/ensure_venv.sh"
  fi

  redis_ping || fail "redis ping — run: bash scripts/start-dev.sh"

  ok "redis PONG"

  if [[ -f .env ]]; then
    ok ".env present"
  else
    warn ".env missing (install mode until wizard completes)"
  fi

  "$PY" scripts/check_mysql.py || fail "MySQL schema check"

  ok "MySQL nexus schema"

  "$PY" -m pytest tests/test_security_unit.py tests/test_retry_runner_outcome.py -q --tb=line || fail "unit tests"

  ok "unit tests passed"

  code=$(curl -s -o /dev/null -w "%{http_code}" "${BASE}/health" 2>/dev/null || echo "000")
  [[ "$code" == "200" ]] || fail "GET /health → ${code} (run: bash scripts/start-dev.sh)"

  ok "GET /health → 200"

  code=$(curl -s -o /dev/null -w "%{http_code}" "${BASE}/api/servers/" 2>/dev/null || echo "000")
  [[ "$code" == "401" ]] || fail "GET /api/servers/ → ${code} (expected 401 JWT)"

  ok "GET /api/servers/ → 401"

  echo "=== Local code verification passed ==="
}

case "$MODE" in
  --code-only|--check-only)
    verify_code
    ;;
  --start)
    exec bash scripts/start-dev.sh
    ;;
  *)
    echo "Usage: $0 [--code-only|--start]"
    exit 1
    ;;
esac
