#!/bin/bash
# Pre-flight checks for Mantimon TCG dev environment
# Runs validation checks before starting dev servers

PROJECT_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
FRONTEND_DIR="$PROJECT_ROOT/frontend"
BACKEND_DIR="$PROJECT_ROOT/backend"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "Running pre-flight checks..."
echo ""

ISSUES=0
WARNINGS=0

# Check function
check() {
    local name="$1"
    local status="$2"
    local message="$3"

    if [ "$status" = "OK" ]; then
        echo -e "  ${GREEN}✓${NC} $name"
    elif [ "$status" = "WARN" ]; then
        echo -e "  ${YELLOW}⚠${NC} $name: $message"
        ((WARNINGS++))
    else
        echo -e "  ${RED}✗${NC} $name: $message"
        ((ISSUES++))
    fi
}

echo "=== Environment Files ==="

# Frontend .env.development
if [ -f "$FRONTEND_DIR/.env.development" ]; then
    # Check for required vars
    if grep -q "VITE_API_BASE_URL" "$FRONTEND_DIR/.env.development"; then
        check "Frontend .env.development" "OK"
    else
        check "Frontend .env.development" "FAIL" "Missing VITE_API_BASE_URL"
    fi
else
    check "Frontend .env.development" "FAIL" "File not found"
fi

# Backend .env (optional - might use system env)
if [ -f "$BACKEND_DIR/.env" ]; then
    check "Backend .env" "OK"
else
    check "Backend .env" "WARN" "No .env file (using system environment?)"
fi

echo ""
echo "=== Dependencies ==="

# Frontend node_modules
if [ -d "$FRONTEND_DIR/node_modules" ]; then
    check "Frontend node_modules" "OK"
else
    check "Frontend node_modules" "FAIL" "Run: cd frontend && npm install"
fi

# Backend venv
if [ -d "$BACKEND_DIR/.venv" ]; then
    check "Backend .venv" "OK"
else
    check "Backend .venv" "FAIL" "Run: cd backend && uv sync"
fi

echo ""
echo "=== Port Availability ==="

# Check port 8000
if lsof -i :8000 2>/dev/null | grep -q LISTEN; then
    PID=$(lsof -t -i :8000 2>/dev/null | head -1)
    PROC=$(ps -p $PID -o comm= 2>/dev/null || echo "unknown")
    check "Port 8000" "WARN" "In use by $PROC (PID $PID)"
else
    check "Port 8000" "OK"
fi

# Check port 8001
if lsof -i :8001 2>/dev/null | grep -q LISTEN; then
    PID=$(lsof -t -i :8001 2>/dev/null | head -1)
    PROC=$(ps -p $PID -o comm= 2>/dev/null || echo "unknown")
    check "Port 8001" "WARN" "In use by $PROC (PID $PID)"
else
    check "Port 8001" "OK"
fi

# Check frontend ports
for PORT in 5173 3000 3001; do
    if lsof -i :$PORT 2>/dev/null | grep -q LISTEN; then
        check "Port $PORT" "WARN" "In use (Vite will try next port)"
        break
    fi
done
check "Frontend ports" "OK"

echo ""
echo "=== Services ==="

# PostgreSQL
if command -v pg_isready &> /dev/null; then
    if pg_isready -q 2>/dev/null; then
        check "PostgreSQL" "OK"
    else
        check "PostgreSQL" "WARN" "Not running or not accessible"
    fi
else
    check "PostgreSQL" "WARN" "pg_isready not found"
fi

# Redis
if command -v redis-cli &> /dev/null; then
    if redis-cli ping 2>/dev/null | grep -q PONG; then
        check "Redis" "OK"
    else
        check "Redis" "WARN" "Not running"
    fi
else
    check "Redis" "WARN" "redis-cli not found"
fi

echo ""
echo "=== Configuration Consistency ==="

# Check if frontend API URL matches an available port
if [ -f "$FRONTEND_DIR/.env.development" ]; then
    API_URL=$(grep "VITE_API_BASE_URL" "$FRONTEND_DIR/.env.development" | cut -d= -f2)
    API_PORT=$(echo "$API_URL" | grep -oE '[0-9]+$')

    if [ -n "$API_PORT" ]; then
        if lsof -i :$API_PORT 2>/dev/null | grep -q LISTEN; then
            # Check if it's our backend
            if curl -s "http://localhost:$API_PORT/docs" 2>/dev/null | grep -q "swagger"; then
                check "API URL -> Backend" "OK"
            else
                check "API URL -> Backend" "WARN" "Port $API_PORT in use but not our backend"
            fi
        else
            check "API URL -> Backend" "WARN" "Backend not running on port $API_PORT"
        fi
    fi
fi

echo ""
echo "=== Summary ==="
if [ $ISSUES -gt 0 ]; then
    echo -e "${RED}$ISSUES issue(s) found that need to be fixed${NC}"
    exit 1
elif [ $WARNINGS -gt 0 ]; then
    echo -e "${YELLOW}$WARNINGS warning(s) - servers may still start${NC}"
    exit 0
else
    echo -e "${GREEN}All checks passed!${NC}"
    exit 0
fi
