#!/bin/bash
# Hive AI Configuration Deployment Script
# Bash script for managing Hive AI configurations across environments
# 
# New Features:
# - HTTP+SSE MCP transport configuration and validation
# - Multi-IDE setup automation (Claude Code, VS Code, Cursor, Windsurf)
# - MCP server port management and conflict resolution
# - Environment-specific MCP endpoint deployment
# 
# Usage: ./deploy-hive-config.sh -e production -c configs/prod.yaml

set -euo pipefail

# Default values
ENVIRONMENT=""
CONFIG_PATH=""
VALIDATE_ONLY=false
DRY_RUN=false
FORCE=false
HIVE_CLI="hive"
LOG_FILE="hive-deployment-$(date +%Y%m%d-%H%M%S).log"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

function usage() {
    cat << EOF
Usage: $0 -e ENVIRONMENT -c CONFIG_PATH [OPTIONS]

Options:
    -e, --environment   Target environment (required)
    -c, --config        Path to configuration file (required)
    -v, --validate      Validate configuration only
    -d, --dry-run       Show what would be done without executing
    -f, --force         Skip confirmation prompts
    -h, --help          Show this help message

Examples:
    $0 -e production -c configs/prod.yaml
    $0 -e staging -c configs/staging.yaml --validate
    $0 -e dev -c configs/dev.yaml --dry-run
EOF
}

function log() {
    local level=${2:-INFO}
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local color=""
    
    case $level in
        ERROR) color=$RED ;;
        SUCCESS) color=$GREEN ;;
        WARN) color=$YELLOW ;;
        *) color=$NC ;;
    esac
    
    echo -e "${color}[$timestamp] [$level] $message${NC}"
    echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
}

function check_prerequisites() {
    log "Checking prerequisites..."
    
    # Check if hive CLI is available
    if ! command -v "$HIVE_CLI" &> /dev/null; then
        log "Hive CLI not found in PATH" ERROR
        return 1
    fi
    
    local version
    version=$($HIVE_CLI --version 2>/dev/null || true)
    log "Hive CLI found: $version"
    
    # Check if config file exists
    if [[ ! -f "$CONFIG_PATH" ]]; then
        log "Configuration file not found: $CONFIG_PATH" ERROR
        return 1
    fi
    
    log "Prerequisites check passed" SUCCESS
    return 0
}

function execute_hive_command() {
    local command="$1"
    local description="$2"
    
    log "Executing: $description"
    log "Command: $HIVE_CLI $command"
    
    if [[ "$DRY_RUN" == true ]]; then
        log "DRY RUN: Would execute - $HIVE_CLI $command" WARN
        return 0
    fi
    
    if $HIVE_CLI $command >> "$LOG_FILE" 2>&1; then
        log "Success: $description" SUCCESS
        return 0
    else
        log "Failed: $description" ERROR
        return 1
    fi
}

function validate_configuration() {
    log "Validating configuration file..."
    
    if execute_hive_command "config validate $CONFIG_PATH" "Configuration validation"; then
        log "Configuration validation passed" SUCCESS
        return 0
    else
        log "Configuration validation failed" ERROR
        return 1
    fi
}

function show_config_diff() {
    log "Checking configuration differences..."
    
    # Note: diff command might fail if there are differences, but that's expected
    set +e
    $HIVE_CLI config diff "$CONFIG_PATH" 2>&1 | tee -a "$LOG_FILE"
    set -e
    
    log "Configuration diff check completed"
}

function validate_mcp_configuration() {
    log "Validating MCP transport configuration..."
    
    # Check if MCP configuration exists in the config file
    if grep -q "mcp:" "$CONFIG_PATH"; then
        log "MCP configuration found in config file"
        
        # Extract MCP port from config (basic validation)
        local mcp_port=$(grep -A 5 "transport:" "$CONFIG_PATH" | grep "port:" | head -1 | sed 's/.*port: *\([0-9]*\).*/\1/')
        
        if [[ -n "$mcp_port" ]]; then
            log "MCP port configured: $mcp_port"
            
            # Check if port is available (only if not dry run)
            if [[ "$DRY_RUN" != true ]]; then
                if netstat -ln 2>/dev/null | grep -q ":$mcp_port "; then
                    log "Warning: Port $mcp_port is already in use" WARN
                    log "Port conflict will be resolved during deployment" 
                else
                    log "Port $mcp_port is available" SUCCESS
                fi
            fi
        fi
        
        # Validate IDE configurations if present
        if grep -q "configurations:" "$CONFIG_PATH"; then
            local ide_count=$(grep -A 10 "configurations:" "$CONFIG_PATH" | grep -c "ide:" || true)
            log "IDE configurations found: $ide_count IDEs"
        fi
        
        log "MCP configuration validation completed" SUCCESS
    else
        log "No MCP configuration found in config file" WARN
        log "Using default MCP settings"
    fi
}

function setup_mcp_server() {
    log "Setting up MCP server for environment: $ENVIRONMENT"
    
    # Check current MCP server status
    local mcp_status
    mcp_status=$($HIVE_CLI mcp-server status 2>/dev/null || echo "not running")
    log "Current MCP server status: $mcp_status"
    
    if [[ "$DRY_RUN" == true ]]; then
        log "DRY RUN: Would configure MCP server for $ENVIRONMENT environment" WARN
        return 0
    fi
    
    # Setup IDE integration
    if execute_hive_command "setup-ide --silent" "IDE configuration setup"; then
        log "IDE configuration completed" SUCCESS
    else
        log "IDE configuration failed (continuing anyway)" WARN
    fi
    
    # Start or restart MCP server to apply new configuration
    if execute_hive_command "mcp-server restart" "MCP server restart"; then
        log "MCP server restarted successfully" SUCCESS
        
        # Verify server is running
        sleep 2
        if execute_hive_command "mcp-server status" "MCP server status check"; then
            log "MCP server is running and healthy" SUCCESS
        else
            log "MCP server status check failed" WARN
        fi
    else
        log "MCP server restart failed" WARN
        log "Manual restart may be required: hive mcp-server restart"
    fi
}

function confirm_deployment() {
    if [[ "$FORCE" == true ]] || [[ "$DRY_RUN" == true ]]; then
        return 0
    fi
    
    echo -n "Proceed with deployment? (y/N): "
    read -r response
    
    case $response in
        [yY]|[yY][eE][sS])
            return 0
            ;;
        *)
            log "Deployment cancelled by user"
            exit 0
            ;;
    esac
}

function deploy_configuration() {
    log "Starting Hive AI configuration deployment"
    log "Environment: $ENVIRONMENT"
    log "Config Path: $CONFIG_PATH"
    
    # Check prerequisites
    if ! check_prerequisites; then
        log "Prerequisites check failed" ERROR
        exit 1
    fi
    
    # Validate configuration
    if ! validate_configuration; then
        log "Configuration validation failed" ERROR
        exit 1
    fi
    
    # Validate MCP configuration
    validate_mcp_configuration
    
    if [[ "$VALIDATE_ONLY" == true ]]; then
        log "Validation-only mode complete" SUCCESS
        exit 0
    fi
    
    # Show configuration diff
    show_config_diff
    
    # Confirm deployment
    confirm_deployment
    
    # Apply configuration
    if execute_hive_command "config apply $CONFIG_PATH" "Configuration deployment"; then
        log "Configuration deployment completed successfully" SUCCESS
        
        # Setup MCP server with new configuration
        setup_mcp_server
        
        # Create backup
        local backup_path="backup-$ENVIRONMENT-$(date +%Y%m%d-%H%M%S).yaml"
        if execute_hive_command "config export $backup_path" "Configuration backup"; then
            log "Configuration backed up to: $backup_path"
        fi
        
        # Final verification
        log "Performing final verification..."
        if execute_hive_command "status" "System status check"; then
            log "Deployment verification completed" SUCCESS
            log "🎉 Hive AI deployment completed successfully for environment: $ENVIRONMENT"
            log "📊 View deployment log: $LOG_FILE"
            log "🚀 MCP server configured for HTTP+SSE streaming"
        else
            log "Deployment verification failed" WARN
        fi
        
    else
        log "Configuration deployment failed" ERROR
        exit 1
    fi
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -e|--environment)
            ENVIRONMENT="$2"
            shift 2
            ;;
        -c|--config)
            CONFIG_PATH="$2"
            shift 2
            ;;
        -v|--validate)
            VALIDATE_ONLY=true
            shift
            ;;
        -d|--dry-run)
            DRY_RUN=true
            shift
            ;;
        -f|--force)
            FORCE=true
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            log "Unknown option: $1" ERROR
            usage
            exit 1
            ;;
    esac
done

# Validate required arguments
if [[ -z "$ENVIRONMENT" ]] || [[ -z "$CONFIG_PATH" ]]; then
    log "Missing required arguments" ERROR
    usage
    exit 1
fi

# Main execution
deploy_configuration