#!/bin/bash

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

print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

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

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

echo ""
echo "╔═══════════════════════════════════════════════════════╗"
echo "║         Stopping Pixel Development Services           ║"
echo "╚═══════════════════════════════════════════════════════╝"
echo ""

# Function to kill processes on port
kill_port() {
    local port=$1
    local name=$2
    
    if command -v lsof >/dev/null 2>&1; then
        if lsof -i :$port >/dev/null 2>&1; then
            print_info "Stopping $name on port $port..."
            local pids=$(lsof -ti :$port)
            for pid in $pids; do
                kill -15 $pid 2>/dev/null
            done
            sleep 1
            
            # Force kill if still running
            if lsof -i :$port >/dev/null 2>&1; then
                print_warning "Force killing $name..."
                local pids=$(lsof -ti :$port)
                for pid in $pids; do
                    kill -9 $pid 2>/dev/null
                done
            fi
            
            print_success "$name stopped"
        else
            print_info "$name not running on port $port"
        fi
    else
        print_warning "lsof not available, cannot check ports"
    fi
}

# Stop backend (port 8000)
kill_port 8000 "Backend"

# Stop frontend (port 3000)
kill_port 3000 "Frontend"

# Kill any remaining uvicorn or npm processes
print_info "Cleaning up remaining processes..."

# Kill uvicorn processes
pkill -f "uvicorn src.main:app" 2>/dev/null

# Kill npm dev processes
pkill -f "npm run dev" 2>/dev/null
pkill -f "next dev" 2>/dev/null

sleep 1

echo ""
print_success "All services stopped"
echo ""
