#!/bin/bash

# Configuration
FRONTEND_PORT=8002
CONTAINER_NAME="ai_unified_frontend"

# Load environment
export PATH=$PATH:/usr/local/bin:/opt/homebrew/bin

# Parse flags
REBUILD=false
for arg in "$@"; do
    if [[ "$arg" == "--rebuild" ]]; then
        REBUILD=true
    fi
done

# Check if docker is available
if ! command -v docker &> /dev/null; then
    echo "❌ Error: 'docker' command not found. Please ensure Docker is installed and running."
    exit 1
fi

# Check if containers are already running
if [ "$REBUILD" = false ] && docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo "✅ CortexAI is already running on port ${FRONTEND_PORT}."
    echo "   Use './start_server.sh --rebuild' to force a restart/rebuild."
    exit 0
fi

if [ "$REBUILD" = true ]; then
    echo "🔄 Rebuilding and restarting services..."
    if ! FRONTEND_PORT=$FRONTEND_PORT docker compose up -d --build --remove-orphans; then
        echo "❌ Error: Docker Compose failed to rebuild/start."
        exit 1
    fi
else
    echo "🚀 Starting CortexAI on port ${FRONTEND_PORT}..."
    if ! FRONTEND_PORT=$FRONTEND_PORT docker compose up -d; then
        echo "❌ Error: Docker Compose failed to start."
        exit 1
    fi
fi

echo ""
echo "=========================================="
echo "🌐 CortexAI is locally available at:"
echo "   http://localhost:${FRONTEND_PORT}"
echo "=========================================="
