#!/usr/bin/env bash
# Start Nexus local dev: Docker (mysql+redis) + uvicorn
# Usage: bash scripts/start-dev.sh
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${ROOT}"

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
}

if ! command -v docker >/dev/null; then
  echo "Install docker.io first" >&2
  exit 1
fi

if [ ! -f .env ]; then
  python3 docker/generate_env.py
  python3 docker/sync_root_env.py
fi

echo "Starting MySQL + Redis..."
docker_cmd compose up -d mysql redis

echo "Waiting for MySQL..."
for _ in $(seq 1 40); do
  st=$(docker_cmd inspect -f '{{.State.Health.Status}}' nexus-mysql-1 2>/dev/null || echo starting)
  [ "${st}" = "healthy" ] && break
  sleep 2
done

if [ ! -d .venv ]; then
  bash scripts/ensure_venv.sh
fi

if ! redis_ping; then
  echo "Waiting for Redis..."
  for _ in $(seq 1 30); do
    redis_ping && break
    sleep 1
  done
fi
redis_ping || {
  echo "ERROR: Redis not responding (127.0.0.1:6379 / nexus-redis-1)" >&2
  exit 1
}

if ! .venv/bin/python -c "
import asyncio
from sqlalchemy import text
from server.infrastructure.database.session import AsyncSessionLocal
async def c():
    async with AsyncSessionLocal() as s:
        n=(await s.execute(text('SELECT COUNT(*) FROM admins'))).scalar()
    print(n)
asyncio.run(c())
" 2>/dev/null | grep -qE '^[0-9]+$'; then
  echo "No admin or DB not ready — run: NEXUS_TEST_ADMIN_PASSWORD='your-pass' python3 scripts/seed_local_admin.py"
fi

if ! ss -tlnp 2>/dev/null | grep -q ':8600'; then
  echo "Starting API on :8600..."
  nohup .venv/bin/uvicorn server.main:app --host 0.0.0.0 --port 8600 --reload \
    > /tmp/nexus-uvicorn.log 2>&1 &
  sleep 3
fi

code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8600/health 2>/dev/null || echo "000")
if [ "${code}" != "200" ]; then
  echo "WARN: /health → ${code} — see /tmp/nexus-uvicorn.log"
else
  echo "Health: ok"
fi

echo ""
echo "API:  http://127.0.0.1:8600/app/"
echo "Verify: bash scripts/local_verify.sh  (full)  |  bash scripts/local_integration_smoke.sh"
echo "Logs: tail -f /tmp/nexus-uvicorn.log"
