#!/bin/bash

# ParentFlow Development Servers Stop Script
# Stops all development servers and cleans up

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
}

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

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

# Header
echo ""
echo "============================================"
echo "   Stopping ParentFlow Development Servers  "
echo "============================================"
echo ""

# Function to stop a service by PID file
stop_service() {
    local SERVICE=$1
    local PID_FILE=$2
    local PORT=$3

    log "Stopping $SERVICE..."

    # Try to stop using PID file
    if [ -f "$PID_FILE" ]; then
        PID=$(cat $PID_FILE)
        if kill -0 $PID 2>/dev/null; then
            log "Stopping process PID: $PID"
            kill -TERM $PID 2>/dev/null || true
            sleep 2
            # Force kill if still running
            if kill -0 $PID 2>/dev/null; then
                warning "Process didn't stop gracefully, force killing..."
                kill -9 $PID 2>/dev/null || true
            fi
            rm -f $PID_FILE
            success "$SERVICE stopped"
        else
            warning "$SERVICE process (PID: $PID) was not running"
            rm -f $PID_FILE
        fi
    else
        warning "PID file not found for $SERVICE"
    fi

    # Double-check and kill any remaining processes on the port
    if lsof -i:$PORT > /dev/null 2>&1; then
        warning "Found process still using port $PORT, killing..."
        lsof -t -i:$PORT | xargs -r kill -9 2>/dev/null || true
        success "Port $PORT cleared"
    fi
}

# Function to kill all Node.js processes matching a pattern
kill_node_pattern() {
    local PATTERN=$1
    local SERVICE=$2

    PIDS=$(ps aux | grep -E "$PATTERN" | grep -v grep | awk '{print $2}' || true)
    if [ -n "$PIDS" ]; then
        warning "Found $SERVICE processes: $PIDS"
        echo $PIDS | xargs -r kill -9 2>/dev/null || true
        success "$SERVICE processes killed"
    fi
}

# Step 1: Stop Backend API
log "${CYAN}Step 1: Stopping Backend API...${NC}"
stop_service "Backend API" "/tmp/backend-dev.pid" 3020
kill_node_pattern "npm.*start:dev.*3020" "Backend"
kill_node_pattern "node.*dist/main.*3020" "Backend"

# Step 2: Stop Frontend
log "${CYAN}Step 2: Stopping Frontend...${NC}"
stop_service "Frontend" "/tmp/frontend-dev.pid" 3030
kill_node_pattern "npm.*dev.*3030" "Frontend"
kill_node_pattern "next.*dev.*3030" "Frontend"

# Step 3: Stop Admin Dashboard
log "${CYAN}Step 3: Stopping Admin Dashboard...${NC}"
stop_service "Admin Dashboard" "/tmp/admin-dev.pid" 3335
kill_node_pattern "npm.*dev.*3335" "Admin"
kill_node_pattern "next.*dev.*3335" "Admin"

# Step 4: Clean up log files
log "${CYAN}Step 4: Cleaning up...${NC}"
if [ -f "/tmp/backend-dev.log" ]; then
    rm -f /tmp/backend-dev.log
    log "Removed backend log file"
fi

if [ -f "/tmp/frontend-dev.log" ]; then
    rm -f /tmp/frontend-dev.log
    log "Removed frontend log file"
fi

if [ -f "/tmp/admin-dev.log" ]; then
    rm -f /tmp/admin-dev.log
    log "Removed admin log file"
fi

# Step 5: Final port check
log "${CYAN}Step 5: Verifying ports are free...${NC}"

check_port() {
    local PORT=$1
    local SERVICE=$2

    if lsof -i:$PORT > /dev/null 2>&1; then
        error "Port $PORT is still in use ($SERVICE)"
        return 1
    else
        success "Port $PORT is free ($SERVICE)"
        return 0
    fi
}

ALL_CLEAR=true
check_port 3020 "Backend API" || ALL_CLEAR=false
check_port 3030 "Frontend" || ALL_CLEAR=false
check_port 3335 "Admin Dashboard" || ALL_CLEAR=false

# Kill any remaining Next.js or npm dev processes
log "${CYAN}Step 6: Cleaning up any remaining dev processes...${NC}"
pkill -f "next dev" 2>/dev/null || true
pkill -f "npm run dev" 2>/dev/null || true
pkill -f "npm run start:dev" 2>/dev/null || true

# Final summary
echo ""
echo "============================================"
if [ "$ALL_CLEAR" = true ]; then
    echo -e "${GREEN}   All Development Servers Stopped!   ${NC}"
else
    echo -e "${YELLOW}   Some Ports Still In Use   ${NC}"
    echo ""
    echo "Manual cleanup commands:"
    echo "  lsof -i:3020 | grep LISTEN"
    echo "  lsof -i:3030 | grep LISTEN"
    echo "  lsof -i:3335 | grep LISTEN"
    echo ""
    echo "Force kill all Node processes:"
    echo "  pkill -9 node"
fi
echo "============================================"
echo ""

log "Development servers stop script completed!"