#!/bin/bash
# Multi-App Management Script

set -e

COMPOSE_FILE="docker-compose.multi.yml"
FLASK_IMAGE="cqa-test-app/flask-app"
MCP_IMAGE="cqa-test-app/mcp-server"

show_help() {
    cat << EOF
CQA Test App Multi-Service Management

Usage: $0 [COMMAND] [OPTIONS]

Commands:
    build [flask|mcp|all]     Build specific or all services
    start [flask|mcp|all]     Start specific or all services  
    stop [flask|mcp|all]      Stop specific or all services
    restart [flask|mcp|all]   Restart specific or all services
    logs [flask|mcp]          Show logs for specific service
    status                    Show status of all services
    test                      Run integration tests
    deploy [dev|prod]         Deploy to environment
    clean                     Clean up containers and images

Examples:
    $0 build all              Build all services
    $0 start flask            Start only Flask app
    $0 logs mcp               Show MCP server logs
    $0 deploy prod            Deploy to production
EOF
}

build_service() {
    local service=$1
    echo "🔨 Building $service..."
    
    case $service in
        flask)
            docker build --target flask-app -t $FLASK_IMAGE:latest -f Dockerfile.multi .
            ;;
        mcp)
            docker build --target mcp-server -t $MCP_IMAGE:latest -f Dockerfile.multi .
            ;;
        all)
            docker-compose -f $COMPOSE_FILE build
            ;;
        *)
            echo "❌ Unknown service: $service"
            exit 1
            ;;
    esac
    echo "✅ Build completed for $service"
}

start_service() {
    local service=$1
    echo "🚀 Starting $service..."
    
    case $service in
        flask)
            docker-compose -f $COMPOSE_FILE up -d flask-app
            ;;
        mcp)
            docker-compose -f $COMPOSE_FILE up -d mcp-server
            ;;
        all)
            docker-compose -f $COMPOSE_FILE up -d
            ;;
        *)
            echo "❌ Unknown service: $service"
            exit 1
            ;;
    esac
    echo "✅ Started $service"
}

stop_service() {
    local service=$1
    echo "🛑 Stopping $service..."
    
    case $service in
        flask)
            docker-compose -f $COMPOSE_FILE stop flask-app
            ;;
        mcp)
            docker-compose -f $COMPOSE_FILE stop mcp-server
            ;;
        all)
            docker-compose -f $COMPOSE_FILE down
            ;;
        *)
            echo "❌ Unknown service: $service"
            exit 1
            ;;
    esac
    echo "✅ Stopped $service"
}

show_logs() {
    local service=$1
    case $service in
        flask)
            docker-compose -f $COMPOSE_FILE logs -f flask-app
            ;;
        mcp)
            docker-compose -f $COMPOSE_FILE logs -f mcp-server
            ;;
        *)
            echo "❌ Unknown service: $service"
            exit 1
            ;;
    esac
}

show_status() {
    echo "📊 Service Status:"
    docker-compose -f $COMPOSE_FILE ps
    
    echo ""
    echo "🌐 Endpoints:"
    echo "   Flask App:  http://localhost:10345"
    echo "   MCP Server: http://localhost:8001/mcp"
    echo "   Prometheus: http://localhost:9090"
    echo "   Nginx:      http://localhost:80"
}

run_tests() {
    echo "🧪 Running integration tests..."
    
    # Ensure services are running
    start_service all
    sleep 10
    
    # Test Flask app
    if curl -f http://localhost:10345/test > /dev/null 2>&1; then
        echo "✅ Flask app is healthy"
    else
        echo "❌ Flask app test failed"
        exit 1
    fi
    
    # Test MCP server
    if curl -f http://localhost:8001/mcp > /dev/null 2>&1; then
        echo "✅ MCP server is healthy"
    else
        echo "❌ MCP server test failed"
        exit 1
    fi
    
    # Test MCP protocol
    if curl -X POST http://localhost:8001/mcp \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \
        > /dev/null 2>&1; then
        echo "✅ MCP protocol test passed"
    else
        echo "❌ MCP protocol test failed"
        exit 1
    fi
    
    echo "🎉 All tests passed!"
}

deploy() {
    local env=$1
    echo "🚀 Deploying to $env environment..."
    
    case $env in
        dev)
            kubectl apply -f k8s/ --context=dev-cluster
            ;;
        prod)
            kubectl apply -f k8s/ --context=prod-cluster
            ;;
        *)
            echo "❌ Unknown environment: $env"
            exit 1
            ;;
    esac
    
    echo "✅ Deployment completed"
}

clean_up() {
    echo "🧹 Cleaning up..."
    docker-compose -f $COMPOSE_FILE down --volumes --remove-orphans
    docker system prune -f
    echo "✅ Cleanup completed"
}

# Main script logic
case ${1:-help} in
    build)
        build_service ${2:-all}
        ;;
    start)
        start_service ${2:-all}
        ;;
    stop)
        stop_service ${2:-all}
        ;;
    restart)
        stop_service ${2:-all}
        start_service ${2:-all}
        ;;
    logs)
        show_logs $2
        ;;
    status)
        show_status
        ;;
    test)
        run_tests
        ;;
    deploy)
        deploy $2
        ;;
    clean)
        clean_up
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo "❌ Unknown command: $1"
        show_help
        exit 1
        ;;
esac