#!/bin/bash
# ColaFlow Development Environment Stop Script
# This script stops both backend API and frontend web application

# Colors
CYAN='\033[0;36m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color

echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  Stopping ColaFlow Services${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

# Get the script directory (project root)
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Stop backend
echo -e "${YELLOW}[Backend] Stopping dotnet processes...${NC}"
if [ -f "$PROJECT_ROOT/backend.pid" ]; then
    backend_pid=$(cat "$PROJECT_ROOT/backend.pid")
    if ps -p $backend_pid > /dev/null 2>&1; then
        kill $backend_pid 2>/dev/null
        echo -e "${GREEN}[Backend] Stopped process $backend_pid${NC}"
    else
        echo -e "${GRAY}[Backend] Process $backend_pid not running${NC}"
    fi
    rm "$PROJECT_ROOT/backend.pid"
else
    # Fallback: kill all dotnet processes
    pkill -f "dotnet.*ColaFlow" 2>/dev/null && echo -e "${GREEN}[Backend] Stopped dotnet processes${NC}" || echo -e "${GRAY}[Backend] No dotnet processes found${NC}"
fi

# Stop frontend
echo -e "${YELLOW}[Frontend] Stopping Node.js processes...${NC}"
if [ -f "$PROJECT_ROOT/frontend.pid" ]; then
    frontend_pid=$(cat "$PROJECT_ROOT/frontend.pid")
    if ps -p $frontend_pid > /dev/null 2>&1; then
        kill $frontend_pid 2>/dev/null
        echo -e "${GREEN}[Frontend] Stopped process $frontend_pid${NC}"
    else
        echo -e "${GRAY}[Frontend] Process $frontend_pid not running${NC}"
    fi
    rm "$PROJECT_ROOT/frontend.pid"
else
    # Fallback: kill processes on port 3000
    if command -v lsof &> /dev/null; then
        lsof -ti:3000 | xargs kill 2>/dev/null && echo -e "${GREEN}[Frontend] Stopped processes on port 3000${NC}" || echo -e "${GRAY}[Frontend] No processes found on port 3000${NC}"
    else
        pkill -f "next dev" 2>/dev/null && echo -e "${GREEN}[Frontend] Stopped Next.js processes${NC}" || echo -e "${GRAY}[Frontend] No Next.js processes found${NC}"
    fi
fi

# Clean up log files
if [ -f "$PROJECT_ROOT/backend.log" ]; then
    rm "$PROJECT_ROOT/backend.log"
fi
if [ -f "$PROJECT_ROOT/frontend.log" ]; then
    rm "$PROJECT_ROOT/frontend.log"
fi

echo ""
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  Services Stopped${NC}"
echo -e "${CYAN}========================================${NC}"
