#!/bin/bash

# ParentFlow Development Servers Start Script
# Starts all development servers on 0.0.0.0 for external access

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Logging functions
log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
    exit 1
}

success() {
    echo -e "${GREEN}✓${NC} $1"
}

warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

# Header
echo ""
echo "============================================"
echo "   ParentFlow Development Servers v1.0     "
echo "============================================"
echo ""

# Function to kill processes on a port - more aggressive
kill_port() {
    local PORT=$1
    local SERVICE=$2

    log "Forcefully clearing port $PORT ($SERVICE)..."

    # Method 1: Using lsof
    if command -v lsof &> /dev/null; then
        local PIDS=$(lsof -t -i:$PORT 2>/dev/null || true)
        if [ -n "$PIDS" ]; then
            warning "Found PIDs on port $PORT: $PIDS"
            echo $PIDS | xargs -r kill -9 2>/dev/null || true
            sleep 1
        fi
    fi

    # Method 2: Using fuser as fallback
    fuser -k $PORT/tcp 2>/dev/null || true
    sleep 1

    # Method 3: Kill any process with the port in its command
    pkill -f ":$PORT" 2>/dev/null || true
    pkill -f "PORT=$PORT" 2>/dev/null || true
    sleep 1

    # Method 4: Using netstat/ss to find and kill
    if command -v ss &> /dev/null; then
        local PIDS=$(ss -tulpn 2>/dev/null | grep ":$PORT " | grep -oP 'pid=\K[0-9]+' || true)
        if [ -n "$PIDS" ]; then
            echo $PIDS | xargs -r kill -9 2>/dev/null || true
            sleep 1
        fi
    fi

    # Final aggressive cleanup - kill anything that might be related
    pkill -f "npm.*dev.*$PORT" 2>/dev/null || true
    pkill -f "node.*$PORT" 2>/dev/null || true
    pkill -f "next.*$PORT" 2>/dev/null || true
    sleep 1

    # Verify the port is free
    if lsof -i:$PORT > /dev/null 2>&1; then
        error "Failed to clear port $PORT after multiple attempts. Please run: sudo lsof -i:$PORT and kill -9 <PID>"
    else
        success "Port $PORT cleared and ready"
    fi
}

# Step 0: Kill ALL Node.js dev processes first
log "${CYAN}Step 0: Cleaning up all development processes...${NC}"

# Kill all existing dev servers
pkill -f "npm run dev" 2>/dev/null || true
pkill -f "npm run start:dev" 2>/dev/null || true
pkill -f "next dev" 2>/dev/null || true
pkill -f "node.*dist/main" 2>/dev/null || true
sleep 2

# Now clear the specific ports
log "${CYAN}Clearing specific ports...${NC}"
kill_port 3020 "Backend API"
kill_port 3030 "Frontend"
kill_port 3335 "Admin Dashboard"

# Verify Node.js is installed
if ! command -v node &> /dev/null; then
    error "Node.js is not installed. Please install Node.js first."
fi

# Verify npm is installed
if ! command -v npm &> /dev/null; then
    error "npm is not installed. Please install npm first."
fi

# Step 1: Start Backend Development Server
log "${CYAN}Step 1: Starting Backend API on 0.0.0.0:3020...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend

# Check if dependencies are installed
if [ ! -d "node_modules" ]; then
    warning "Backend dependencies not found, installing..."
    npm install
fi

# Start backend in background
npm run start:dev > /tmp/backend-dev.log 2>&1 &
BACKEND_PID=$!
echo $BACKEND_PID > /tmp/backend-dev.pid
success "Backend API started (PID: $BACKEND_PID)"
log "Backend accessible at: http://maternal-api.noru1.ro (0.0.0.0:3020)"

# Step 2: Start Frontend Development Server
log "${CYAN}Step 2: Starting Frontend on 0.0.0.0:3030...${NC}"
cd /root/maternal-app/maternal-web

# Check if dependencies are installed
if [ ! -d "node_modules" ]; then
    warning "Frontend dependencies not found, installing..."
    npm install
fi

# Create .env.local if it doesn't exist
if [ ! -f ".env.local" ]; then
    cat > .env.local << EOF
NEXT_PUBLIC_API_URL=https://maternal-api.noru1.ro
NEXT_PUBLIC_GRAPHQL_URL=https://maternal-api.noru1.ro/graphql
NEXT_PUBLIC_WS_URL=wss://maternal-api.noru1.ro
NEXT_PUBLIC_APP_URL=https://maternal.noru1.ro
NEXT_PUBLIC_APP_NAME=ParentFlow
EOF
    log "Created .env.local for frontend"
fi

# Start frontend in background using full path to next
node_modules/next/dist/bin/next dev -p 3030 -H 0.0.0.0 > /tmp/frontend-dev.log 2>&1 &
FRONTEND_PID=$!
echo $FRONTEND_PID > /tmp/frontend-dev.pid
success "Frontend started (PID: $FRONTEND_PID)"
log "Frontend accessible at: http://maternal.noru1.ro (0.0.0.0:3030)"

# Step 3: Start Admin Dashboard Development Server
log "${CYAN}Step 3: Starting Admin Dashboard on 0.0.0.0:3335...${NC}"
cd /root/maternal-app/parentflow-admin

# Check if dependencies are installed
if [ ! -d "node_modules" ]; then
    warning "Admin dependencies not found, installing..."
    npm install
fi

# Create .env.local if it doesn't exist
if [ ! -f ".env.local" ]; then
    cat > .env.local << EOF
NEXT_PUBLIC_API_URL=https://maternal-api.noru1.ro
NEXT_PUBLIC_APP_URL=https://pfadmin.noru1.ro
NEXT_PUBLIC_APP_NAME=ParentFlow Admin
EOF
    log "Created .env.local for admin dashboard"
fi

# Start admin dashboard in background using full path to next
node_modules/next/dist/bin/next dev -p 3335 -H 0.0.0.0 > /tmp/admin-dev.log 2>&1 &
ADMIN_PID=$!
echo $ADMIN_PID > /tmp/admin-dev.pid
success "Admin Dashboard started (PID: $ADMIN_PID)"
log "Admin accessible at: http://pfadmin.noru1.ro (0.0.0.0:3335)"

# Step 4: Verify all services are running
log "${CYAN}Step 4: Verifying services...${NC}"
log "Waiting 60 seconds for services to start..."
sleep 60

verify_service() {
    local SERVICE=$1
    local PORT=$2
    local PID_FILE=$3

    # Check if port is listening
    if ss -tulpn | grep -q ":$PORT.*LISTEN"; then
        success "$SERVICE is listening on port $PORT"
        return 0
    else
        # Check if process is still starting
        if [ -f "$PID_FILE" ]; then
            PID=$(cat $PID_FILE)
            if kill -0 $PID 2>/dev/null; then
                warning "$SERVICE is running (PID: $PID) but not yet listening on port $PORT"
                return 1
            else
                error "$SERVICE process (PID: $PID) died. Check logs: tail -50 /tmp/${SERVICE,,}-dev.log"
                return 1
            fi
        else
            warning "$SERVICE PID file not found"
            return 1
        fi
    fi
}

ALL_GOOD=true
verify_service "Backend API" 3020 /tmp/backend-dev.pid || ALL_GOOD=false
verify_service "Frontend" 3030 /tmp/frontend-dev.pid || ALL_GOOD=false
verify_service "Admin Dashboard" 3335 /tmp/admin-dev.pid || ALL_GOOD=false

# Final summary
echo ""
echo "============================================"
if [ "$ALL_GOOD" = true ]; then
    echo -e "${GREEN}   All Development Servers Started!   ${NC}"
else
    echo -e "${YELLOW}   Some Services Failed to Start   ${NC}"
fi
echo "============================================"
echo ""
echo "Access URLs:"
echo "  Backend API:     http://maternal-api.noru1.ro (0.0.0.0:3020)"
echo "  Frontend:        http://maternal.noru1.ro (0.0.0.0:3030)"
echo "  Admin Dashboard: http://pfadmin.noru1.ro (0.0.0.0:3335)"
echo ""
echo "Log files:"
echo "  Backend:  tail -f /tmp/backend-dev.log"
echo "  Frontend: tail -f /tmp/frontend-dev.log"
echo "  Admin:    tail -f /tmp/admin-dev.log"
echo ""
echo "To stop all servers: ./stop-dev.sh"
echo ""
echo "PID files stored in:"
echo "  /tmp/backend-dev.pid"
echo "  /tmp/frontend-dev.pid"
echo "  /tmp/admin-dev.pid"
echo ""

if [ "$ALL_GOOD" = false ]; then
    warning "Check log files for errors"
    exit 1
fi

log "Development servers started successfully!"