#!/bin/bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

source "$PROJECT_ROOT/scripts/runtime-env.sh"
nexus_export_runtime_env "$PROJECT_ROOT"

PORT_ARG="${1:-$PORT}"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔄 NexusCRM Server Restart Script"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo

# Step 1: Kill ALL processes on target port
echo "1. Killing all processes on port ${PORT_ARG}..."
PIDS_ON_PORT=$(lsof -ti:${PORT_ARG} 2>/dev/null || true)
if [ -n "$PIDS_ON_PORT" ]; then
    echo "   Found PIDs: $PIDS_ON_PORT"
    kill -9 $PIDS_ON_PORT 2>/dev/null || true
    echo "   ✅ Killed processes on port ${PORT_ARG}"
else
    echo "   ℹ️  No processes found on port ${PORT_ARG}"
fi

# Step 2: Wait for port to be freed
echo "2. Waiting for port ${PORT_ARG} to be freed..."
sleep 2
if lsof -ti:${PORT_ARG} >/dev/null 2>&1; then
    echo "   ❌ ERROR: Port ${PORT_ARG} still in use!"
    lsof -i:${PORT_ARG}
    exit 1
fi
echo "   ✅ Port ${PORT_ARG} is free"

# Step 3: Run codegen to ensure schema consistency
if [ "${SKIP_CODEGEN}" != "1" ]; then
    echo "3. Running codegen..."
    cd "$(cd "$(dirname "$0")" && pwd)"
    go build -o bin/codegen ./cmd/codegen/ && ./bin/codegen > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "   ⚠️  Codegen failed (non-fatal)"
    else
        echo "   ✅ Codegen complete"
    fi
else
    echo "3. Skipping codegen (SKIP_CODEGEN=1)"
fi

# Step 4: Rebuild server (optional - skip if binary is fresh)
if [ "${SKIP_BUILD}" != "1" ]; then
    echo "4. Building server..."
    cd "$(cd "$(dirname "$0")" && pwd)"
    go build -o bin/server ./cmd/server/
    if [ $? -ne 0 ]; then
        echo "   ❌ Build failed!"
        exit 1
    fi
    BUILD_TIME=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" bin/server)
    echo "   ✅ Build successful (${BUILD_TIME})"
else
    echo "4. Skipping build (SKIP_BUILD=1)"
fi

# Step 5: Start server (env already loaded via runtime-env.sh)
echo "5. Starting server..."
cd "$(cd "$(dirname "$0")" && pwd)"

PORT=${PORT_ARG} ./bin/server > /tmp/server.log 2>&1 &
SERVER_PID=$!

echo "   Server PID: $SERVER_PID"
echo "   Log file: /tmp/server.log"

# Step 5: Verify server started
echo "6. Verifying server startup..."

# Poll for health check (max 180 attempts * 2s = 360s = 6 minutes)
# Increased timeout for TiDB Cloud bootstrap which can be slow
MAX_ATTEMPTS=180
ATTEMPT=1
SERVER_READY=false

while [ $ATTEMPT -le $MAX_ATTEMPTS ]; do
    # Check if process is still running
    if ! ps -p $SERVER_PID > /dev/null; then
        echo "   ❌ Server process died!"
        echo "   Last 20 lines of log:"
        tail -20 /tmp/server.log
        exit 1
    fi

    # Check health endpoint
    HEALTH_CHECK=$(curl -s http://localhost:${PORT_ARG}/health 2>&1 || echo "failed")
    if [[ "$HEALTH_CHECK" == *"golang"* ]]; then
        echo "   ✅ Server is healthy!"
        echo "   Response: $HEALTH_CHECK"
        SERVER_READY=true
        break
    fi

    echo "   ⏳ Waiting for server... ($ATTEMPT/$MAX_ATTEMPTS)"
    sleep 2
    ATTEMPT=$((ATTEMPT + 1))
done

if [ "$SERVER_READY" = false ]; then
    echo "   ❌ Health check failed after 6 minutes!"
    echo "   Last 20 lines of log:"
    tail -20 /tmp/server.log
    kill -9 $SERVER_PID
    exit 1
fi

echo
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Server started successfully!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "PID: $SERVER_PID"
echo "URL: http://localhost:${PORT_ARG}"
echo "Log: tail -f /tmp/server.log"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo
