#!/bin/bash
#
# Paper Dynasty Game Engine - Single Command Startup
#
# Usage:
#   ./start.sh dev      Start in development mode (hot-reload)
#   ./start.sh prod     Start in production mode
#   ./start.sh stop     Stop all services
#   ./start.sh logs     Tail all logs
#   ./start.sh rebuild  Force rebuild and start
#   ./start.sh status   Show service status
#
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 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_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[OK]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARN]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check Docker is running
check_docker() {
    if ! docker info > /dev/null 2>&1; then
        print_error "Docker is not running. Please start Docker Desktop."
        exit 1
    fi
    print_success "Docker is running"
}

# Check required env files exist
check_env_files() {
    local missing=0

    if [[ ! -f "backend/.env" ]]; then
        print_error "backend/.env not found"
        print_status "  Run: cp backend/.env.example backend/.env"
        missing=1
    fi

    if [[ ! -f "frontend-sba/.env" ]]; then
        print_error "frontend-sba/.env not found"
        print_status "  Run: cp frontend-sba/.env.example frontend-sba/.env"
        missing=1
    fi

    if [[ $missing -eq 1 ]]; then
        echo ""
        print_status "Quick fix: ./scripts/env-switch.sh dev"
        exit 1
    fi

    print_success "Environment files found"
}

# Wait for service to be healthy
wait_for_health() {
    local service=$1
    local max_wait=60
    local waited=0

    print_status "Waiting for $service to be healthy..."

    while [[ $waited -lt $max_wait ]]; do
        if docker compose ps "$service" 2>/dev/null | grep -q "healthy"; then
            print_success "$service is healthy"
            return 0
        fi
        sleep 2
        waited=$((waited + 2))
    done

    print_error "$service failed to become healthy after ${max_wait}s"
    docker compose logs "$service" --tail 20
    return 1
}

# Start in development mode
start_dev() {
    print_status "Starting in DEVELOPMENT mode..."
    echo ""

    check_docker
    check_env_files

    # Switch to dev env if not already
    if grep -q "gameplay-demo.manticorum.com" backend/.env 2>/dev/null; then
        print_warning "Detected production .env - switching to dev"
        ./scripts/env-switch.sh dev
    fi

    print_status "Building and starting containers..."
    docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build

    echo ""
    wait_for_health "redis"
    wait_for_health "backend"

    echo ""
    print_success "All services started!"
    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  Development Environment Ready${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo "  Backend API:  http://localhost:8000"
    echo "  Frontend:     http://localhost:3000"
    echo "  API Docs:     http://localhost:8000/docs"
    echo ""
    echo "  Hot-reload is enabled for both backend and frontend."
    echo ""
    echo "  Commands:"
    echo "    ./start.sh logs     View logs"
    echo "    ./start.sh stop     Stop services"
    echo ""
}

# Start in production mode
start_prod() {
    print_status "Starting in PRODUCTION mode..."
    echo ""

    check_docker
    check_env_files

    # Switch to prod env if not already
    if grep -q "localhost:8000" backend/.env 2>/dev/null; then
        print_warning "Detected dev .env - switching to prod"
        ./scripts/env-switch.sh prod
    fi

    print_status "Building and starting containers..."
    docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d --build

    echo ""
    wait_for_health "redis"
    wait_for_health "backend"

    echo ""
    print_success "All services started!"
    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  Production Environment Ready${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo "  Public URL: https://gameplay-demo.manticorum.com"
    echo ""
    echo "  Commands:"
    echo "    ./start.sh logs     View logs"
    echo "    ./start.sh stop     Stop services"
    echo ""
}

# Stop all services
stop_services() {
    print_status "Stopping all services..."
    docker compose down --remove-orphans
    print_success "All services stopped"
}

# Show logs
show_logs() {
    docker compose logs -f
}

# Force rebuild
rebuild() {
    local mode=${1:-dev}
    print_status "Force rebuilding containers..."
    docker compose down --remove-orphans

    if [[ "$mode" == "prod" ]]; then
        docker compose -f docker-compose.yml -f docker-compose.prod.yml build --no-cache
        start_prod
    else
        docker compose -f docker-compose.yml -f docker-compose.dev.yml build --no-cache
        start_dev
    fi
}

# Show status
show_status() {
    print_status "Service Status:"
    echo ""
    docker compose ps
    echo ""

    # Quick health check
    if curl -sf http://localhost:8000/api/health > /dev/null 2>&1; then
        print_success "Backend: responding"
    else
        print_error "Backend: not responding"
    fi

    if curl -sf http://localhost:3000 > /dev/null 2>&1; then
        print_success "Frontend: responding"
    else
        print_error "Frontend: not responding"
    fi
}

# Show usage
show_usage() {
    echo "Paper Dynasty Game Engine"
    echo ""
    echo "Usage: ./start.sh <command>"
    echo ""
    echo "Commands:"
    echo "  dev       Start in development mode (hot-reload enabled)"
    echo "  prod      Start in production mode (optimized build)"
    echo "  stop      Stop all services"
    echo "  logs      Tail logs from all services"
    echo "  rebuild   Force rebuild containers (add 'prod' for production)"
    echo "  status    Show service status and health"
    echo ""
    echo "Examples:"
    echo "  ./start.sh dev          # Start development environment"
    echo "  ./start.sh prod         # Start production environment"
    echo "  ./start.sh rebuild prod # Force rebuild production"
    echo ""
}

# Main
case "${1:-}" in
    dev)
        start_dev
        ;;
    prod)
        start_prod
        ;;
    stop)
        stop_services
        ;;
    logs)
        show_logs
        ;;
    rebuild)
        rebuild "${2:-dev}"
        ;;
    status)
        show_status
        ;;
    *)
        show_usage
        exit 1
        ;;
esac
