#!/usr/bin/env bash
# WSL code verification only (unit tests + /health + JWT 401).
# Usage:
#   bash scripts/wsl_integration_smoke.sh
#   bash scripts/wsl_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] $*"; }

verify_code() {
  echo "=== Nexus WSL 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/wsl_ensure_venv.sh"
  fi

  redis-cli ping 2>/dev/null | grep -q PONG || fail "redis-cli ping — start redis-server"

  ok "redis PONG"

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

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

  ok "MySQL nexus schema"

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

  ok "security unit tests (15)"

  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/wsl_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 "=== WSL code verification passed ==="
}

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