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

set -e

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

echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  ColaFlow Development Environment${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""

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

# Function to check if a port is in use
check_port() {
    local port=$1
    if command -v netstat &> /dev/null; then
        netstat -an | grep ":$port " | grep -q LISTEN
    elif command -v lsof &> /dev/null; then
        lsof -i ":$port" -sTCP:LISTEN -t &> /dev/null
    else
        # Fallback: try to connect
        timeout 1 bash -c "cat < /dev/null > /dev/tcp/localhost/$port" 2>/dev/null
    fi
}

# Function to start backend
start_backend() {
    echo -e "${YELLOW}[Backend] Starting ColaFlow API...${NC}"

    # Check if backend port is already in use
    if check_port 5000; then
        echo -e "${GREEN}[Backend] Port 5000 is already in use. Backend may already be running.${NC}"
        echo -e "${GREEN}[Backend] Swagger UI: http://localhost:5000/swagger${NC}"
        return
    fi

    # Start backend in background
    local backend_path="$PROJECT_ROOT/colaflow-api"
    local backend_project="$backend_path/src/ColaFlow.API/ColaFlow.API.csproj"

    if [ ! -f "$backend_project" ]; then
        echo -e "${RED}[Backend] ERROR: Backend project not found at $backend_project${NC}"
        return
    fi

    echo -e "${GRAY}[Backend] Starting at $backend_path${NC}"

    # Start backend in background, redirecting output to a log file
    cd "$backend_path"
    nohup dotnet run --project "$backend_project" > "$PROJECT_ROOT/backend.log" 2>&1 &
    local backend_pid=$!
    echo $backend_pid > "$PROJECT_ROOT/backend.pid"

    echo -e "${YELLOW}[Backend] Waiting for API to start (PID: $backend_pid)...${NC}"

    # Wait for the backend to start (up to 30 seconds)
    for i in {1..30}; do
        if check_port 5000; then
            echo -e "${GREEN}[Backend] API started successfully at http://localhost:5000${NC}"
            echo -e "${GREEN}[Backend] Swagger UI: http://localhost:5000/swagger${NC}"
            return
        fi
        sleep 1
    done

    echo -e "${YELLOW}[Backend] API is starting... Check backend.log for status${NC}"
}

# Function to start frontend
start_frontend() {
    echo -e "${YELLOW}[Frontend] Starting ColaFlow Web...${NC}"

    # Check if frontend port is already in use
    if check_port 3000; then
        echo -e "${GREEN}[Frontend] Port 3000 is already in use. Frontend may already be running.${NC}"
        echo -e "${GREEN}[Frontend] Web UI: http://localhost:3000${NC}"
        return
    fi

    # Start frontend in background
    local frontend_path="$PROJECT_ROOT/colaflow-web"

    if [ ! -d "$frontend_path" ]; then
        echo -e "${RED}[Frontend] ERROR: Frontend directory not found at $frontend_path${NC}"
        return
    fi

    # Check if node_modules exists
    if [ ! -d "$frontend_path/node_modules" ]; then
        echo -e "${YELLOW}[Frontend] node_modules not found. Installing dependencies first...${NC}"
        cd "$frontend_path"
        npm install
    fi

    echo -e "${GRAY}[Frontend] Starting at $frontend_path${NC}"

    # Start frontend in background, redirecting output to a log file
    cd "$frontend_path"
    nohup npm run dev > "$PROJECT_ROOT/frontend.log" 2>&1 &
    local frontend_pid=$!
    echo $frontend_pid > "$PROJECT_ROOT/frontend.pid"

    echo -e "${YELLOW}[Frontend] Waiting for Web to start (PID: $frontend_pid)...${NC}"

    # Wait for the frontend to start (up to 30 seconds)
    for i in {1..30}; do
        if check_port 3000; then
            echo -e "${GREEN}[Frontend] Web started successfully at http://localhost:3000${NC}"
            return
        fi
        sleep 1
    done

    echo -e "${YELLOW}[Frontend] Web is starting... Check frontend.log for status${NC}"
}

# Function to stop services
stop_services() {
    echo ""
    echo -e "${YELLOW}Stopping services...${NC}"

    if [ -f "$PROJECT_ROOT/backend.pid" ]; then
        local backend_pid=$(cat "$PROJECT_ROOT/backend.pid")
        if ps -p $backend_pid > /dev/null 2>&1; then
            echo -e "${YELLOW}[Backend] Stopping (PID: $backend_pid)...${NC}"
            kill $backend_pid 2>/dev/null || true
        fi
        rm "$PROJECT_ROOT/backend.pid"
    fi

    if [ -f "$PROJECT_ROOT/frontend.pid" ]; then
        local frontend_pid=$(cat "$PROJECT_ROOT/frontend.pid")
        if ps -p $frontend_pid > /dev/null 2>&1; then
            echo -e "${YELLOW}[Frontend] Stopping (PID: $frontend_pid)...${NC}"
            kill $frontend_pid 2>/dev/null || true
        fi
        rm "$PROJECT_ROOT/frontend.pid"
    fi

    echo -e "${GREEN}Services stopped.${NC}"
    exit 0
}

# Set up trap to stop services on Ctrl+C
trap stop_services INT TERM

# Main execution
echo -e "${CYAN}Starting development environment...${NC}"
echo ""

# Start backend first
start_backend
echo ""

# Start frontend
start_frontend
echo ""

echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  Development Environment Started${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""
echo -e "Services:"
echo -e "  - Backend API: http://localhost:5000"
echo -e "  - Swagger UI:  http://localhost:5000/swagger"
echo -e "  - Frontend:    http://localhost:3000"
echo ""
echo -e "${GRAY}Logs:${NC}"
echo -e "  - Backend:  tail -f backend.log"
echo -e "  - Frontend: tail -f frontend.log"
echo ""
echo -e "${GRAY}Press Ctrl+C to stop all services.${NC}"
echo ""

# Keep the script running
while true; do
    sleep 1
done
