#!/usr/bin/env bash
# =============================================================================
# MCP-ZERO + ZETA Playground Enterprise Deployment Script
# Enterprise-grade deployment, configuration and management
# Version 1.0.0
# =============================================================================

set -eo pipefail
TIMESTAMP=$(date +%Y%m%d%H%M%S)
LOG_FILE="mcpzero_deploy_${TIMESTAMP}.log"

# ANSI colors
BLUE="\033[0;34m"
GREEN="\033[0;32m"
RED="\033[0;31m"
YELLOW="\033[0;33m"
BOLD="\033[1m"
NC="\033[0m" # No Color

# =============================================================================
# Configuration & Environment Variables
# =============================================================================

# Base paths
MCPZERO_ROOT=$(pwd)
ZETA_ROOT="${MCPZERO_ROOT}/.mcpzero/playground"
CONTRACTS_ROOT="${MCPZERO_ROOT}/mlops/contracts"
CONFIG_ROOT="${MCPZERO_ROOT}/config"
ENV_FILE="${MCPZERO_ROOT}/.env"
SERVER_FILE="${MCPZERO_ROOT}/.server"

# Default configuration
DEFAULT_REDIS_HOST="localhost"
DEFAULT_REDIS_PORT="6379"
DEFAULT_OFFLINE_FIRST="true"
DEFAULT_SECURITY_LEVEL="enterprise"
DEFAULT_ENVIRONMENT="production"
DEFAULT_IMMUTABLE_CONTRACTS="true"
DEFAULT_LLM_TRAINING_DEVICE="cpu"

# =============================================================================
# Utility Functions
# =============================================================================

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

safe_mkdir() {
    local dir="$1"
    if [ ! -d "$dir" ]; then
        mkdir -p "$dir"
        log "INFO" "Created directory: ${dir}"
    fi
}

check_dependency() {
    local cmd="$1"
    local package="$2"
    
    if ! command -v "$cmd" &> /dev/null; then
        log "WARNING" "${cmd} not found. Some features may not work properly."
        return 1
    fi
    return 0
}

create_immutable_contract() {
    local contract_name="$1"
    local contract_content="$2"
    local contract_file="${CONTRACTS_ROOT}/${contract_name}.contract"
    
    # Only create if it doesn't exist (immutability)
    if [ ! -f "$contract_file" ]; then
        mkdir -p "${CONTRACTS_ROOT}"
        echo "$contract_content" > "$contract_file"
        log "INFO" "Created immutable contract: ${contract_name}"
    else
        log "INFO" "Contract ${contract_name} already exists (immutable)"
    fi
}

generate_secure_key() {
    local length=${1:-32}
    if command -v openssl &> /dev/null; then
        openssl rand -hex "$length"
    else
        # Fallback to less secure but more available method
        head /dev/urandom | tr -dc A-Za-z0-9 | head -c "$length"
    fi
}

backup_file() {
    local file="$1"
    if [ -f "$file" ]; then
        cp "$file" "${file}.${TIMESTAMP}.bak"
        log "INFO" "Backed up ${file} to ${file}.${TIMESTAMP}.bak"
    fi
}

# =============================================================================
# Environment Setup
# =============================================================================

setup_environment() {
    log "INFO" "Setting up MCP-ZERO environment..."
    
    # Create required directories
    safe_mkdir "${CONFIG_ROOT}"
    safe_mkdir "${ZETA_ROOT}/models"
    safe_mkdir "${ZETA_ROOT}/datasets"
    safe_mkdir "${ZETA_ROOT}/telemetry"
    safe_mkdir "${ZETA_ROOT}/config"
    safe_mkdir "${MCPZERO_ROOT}/.mcpzero/lock"
    safe_mkdir "${MCPZERO_ROOT}/bin"
    
    # Backup existing .env file if it exists
    backup_file "$ENV_FILE"
    
    # Generate secure keys for various components
    API_SECRET_KEY=$(generate_secure_key 32)
    IMMUTABLE_CONTRACT_KEY=$(generate_secure_key 32)
    ENCRYPTION_SALT=$(generate_secure_key 16)
    
    # Create .env file with default settings and generated keys
    cat > "$ENV_FILE" << EOF
# =============================================================================
# MCP-ZERO + ZETA Playground Environment Configuration
# Generated on: $(date)
# =============================================================================

# Base Configuration
MCPZERO_ROOT="${MCPZERO_ROOT}"
MCPZERO_ENV="${DEFAULT_ENVIRONMENT}"
SECURITY_LEVEL="${DEFAULT_SECURITY_LEVEL}"
OFFLINE_FIRST="${DEFAULT_OFFLINE_FIRST}"

# Redis Configuration
REDIS_HOST="${DEFAULT_REDIS_HOST}"
REDIS_PORT="${DEFAULT_REDIS_PORT}"
REDIS_DB_VORTEX=0
REDIS_DB_MOCK_RANGE=1
REDIS_DB_ROUTER=2
REDIS_DB_UNCOMPUTATION=3
REDIS_DB_LLM_TRAINER=5

# Security Keys
API_SECRET_KEY="${API_SECRET_KEY}"
IMMUTABLE_CONTRACT_KEY="${IMMUTABLE_CONTRACT_KEY}"
ENCRYPTION_SALT="${ENCRYPTION_SALT}"

# LLM Training Configuration
LLM_TRAINING_DEVICE="${DEFAULT_LLM_TRAINING_DEVICE}"
LLM_DEFAULT_BATCH_SIZE=4
LLM_GRADIENT_ACCUMULATION_STEPS=4
LLM_MEMORY_LIMIT_MB=1024

# Telemetry and Logging
TELEMETRY_ENABLED=true
LOG_LEVEL=INFO
LOG_DIR="${MCPZERO_ROOT}/logs"
EOF
    
    log "SUCCESS" "Environment file created at ${ENV_FILE}"
    
    # Create .server file for deployment management
    cat > "$SERVER_FILE" << EOF
# =============================================================================
# MCP-ZERO + ZETA Playground Server Configuration
# Generated on: $(date)
# =============================================================================

# Server Configuration
SERVER_MODE="standalone"
SERVER_PORT=8080
API_PORT=8081
REDIS_SERVER_ENABLED=true
REDIS_SERVER_PORT=6379
REDIS_SERVER_CONFIG="${MCPZERO_ROOT}/mlops/redis/mind_vortex.conf"

# Resource Management
MAX_MEMORY_MB=2048
MAX_CPU_THREADS=4
SWAP_ENABLED=true
SWAP_LIMIT_MB=4096

# Component Status
COMPONENT_VORTEX_ENABLED=true
COMPONENT_ETHICS_ENABLED=true
COMPONENT_ZETA_PLAYGROUND=true
COMPONENT_LOCK_MANAGER=true

# Immutable Contracts
IMMUTABLE_CONTRACTS_ENABLED=${DEFAULT_IMMUTABLE_CONTRACTS}
CONTRACT_CHECK_INTERVAL=300
EOF
    
    log "SUCCESS" "Server configuration created at ${SERVER_FILE}"
}

# =============================================================================
# Immutable Contracts Setup
# =============================================================================

setup_immutable_contracts() {
    log "INFO" "Setting up immutable contracts..."
    
    # Create ZETA Playground Contract
    create_immutable_contract "zeta_playground" "
ZETA_PLAYGROUND_CONTRACT
VERSION: 1.0.0
CREATED: $(date)

1. OFFLINE_FIRST_RESILIENCE: All components must attempt connection only once and permanently switch to offline mode if connection fails.
2. IMMUTABLE_STATE: All critical state changes generate immutable lock files.
3. RESOURCE_CONSTRAINTS: All components must respect hardware limitations and use memory-efficient operations.
4. SECURITY_COMPLIANCE: All components must implement security best practices and ethics compliance checks.
5. INTEGRATION: All components must follow MCP-ZERO integration standards.
"
    
    # Create Integration Contract
    create_immutable_contract "mcpzero_zeta_integration" "
INTEGRATION_CONTRACT
VERSION: 1.0.0
CREATED: $(date)

1. DIRECTORY_STRUCTURE: ZETA components reside in .mcpzero/playground directory.
2. OFFLINE_RESILIENCE: All components start in offline mode by default.
3. LOCK_FILES: All state changes generate lock files in .mcpzero/lock directory.
4. CONFIGURATION: All components load configuration from .env file if present.
5. ETHICS_COMPLIANCE: All components verify actions with ethics compliance system.
"
    
    log "SUCCESS" "Immutable contracts established"
}

# =============================================================================
# Integration and Linkage
# =============================================================================

integrate_components() {
    log "INFO" "Integrating ZETA Playground with MCP-ZERO..."
    
    # Link ZETA CLI to main bin directory
    if [ -f "${ZETA_ROOT}/zeta_cli.py" ]; then
        chmod +x "${ZETA_ROOT}/zeta_cli.py"
        ln -sf "${ZETA_ROOT}/zeta_cli.py" "${MCPZERO_ROOT}/bin/zeta"
        log "SUCCESS" "Linked ZETA CLI to bin/zeta"
    else
        log "WARNING" "ZETA CLI not found at ${ZETA_ROOT}/zeta_cli.py"
    fi
    
    # Set correct permissions for MCP-ZERO integration script
    if [ -f "${MCPZERO_ROOT}/bin/mcp_zeta.py" ]; then
        chmod +x "${MCPZERO_ROOT}/bin/mcp_zeta.py"
        ln -sf "${MCPZERO_ROOT}/bin/mcp_zeta.py" "${MCPZERO_ROOT}/bin/mcp-zeta"
        log "SUCCESS" "Set up MCP-ZETA integration script"
    else
        log "WARNING" "MCP-ZETA integration script not found"
    fi
    
    # Create configuration for compact LLM trainer
    cat > "${ZETA_ROOT}/config/llm_trainer.json" << EOF
{
    "training": {
        "batch_size": 4,
        "micro_batch_size": 1,
        "gradient_accumulation_steps": 4,
        "epochs": 3,
        "learning_rate": 2e-4,
        "enable_gradient_checkpointing": true,
        "enable_quantization": true,
        "mixed_precision": "fp16"
    },
    "model": {
        "base_model_type": "gpt2",
        "use_8bit_optimizer": true
    },
    "hardware": {
        "memory_limit_mb": 1024,
        "swap_limit_mb": 2048,
        "cpu_threads": 4
    }
}
EOF
    log "SUCCESS" "Created LLM trainer configuration"
    
    log "SUCCESS" "Components integrated successfully"
}

# =============================================================================
# Security and Compliance Setup
# =============================================================================

setup_security() {
    log "INFO" "Setting up security and compliance..."
    
    # Create directory for security policies
    safe_mkdir "${MCPZERO_ROOT}/security"
    
    # Create security policy file
    cat > "${MCPZERO_ROOT}/security/policy.json" << EOF
{
    "access_control": {
        "role_based": true,
        "default_role": "reader",
        "roles": ["admin", "developer", "analyst", "reader"]
    },
    "compliance": {
        "frameworks": ["SOC2", "GDPR", "HIPAA", "ISO27001"],
        "data_classification": ["public", "internal", "confidential", "restricted"],
        "default_classification": "internal",
        "audit_trail": true,
        "audit_retention_days": 90
    },
    "encryption": {
        "at_rest": true,
        "in_transit": true,
        "algorithm": "AES-256-GCM"
    }
}
EOF
    
    log "SUCCESS" "Security policies established"
}

# =============================================================================
# Integration Testing
# =============================================================================

run_integration_tests() {
    log "INFO" "Running integration tests..."
    
    # Test offline-first resilience
    if [ -x "${ZETA_ROOT}/zeta_cli.py" ]; then
        "${ZETA_ROOT}/zeta_cli.py" test-resilience
        if [ $? -eq 0 ]; then
            log "SUCCESS" "Offline-first resilience test passed"
        else
            log "WARNING" "Offline-first resilience test encountered issues"
        fi
    else
        log "WARNING" "ZETA CLI not executable, skipping tests"
    fi
    
    # Test environment variables
    if [ -f "$ENV_FILE" ]; then
        source "$ENV_FILE"
        if [ -n "$MCPZERO_ROOT" ]; then
            log "SUCCESS" "Environment variables loaded successfully"
        else
            log "WARNING" "Environment variables not loaded properly"
        fi
    fi
    
    log "INFO" "Integration tests completed"
}

# =============================================================================
# Main Command Interface
# =============================================================================

show_help() {
    cat << EOF
MCP-ZERO + ZETA Playground Enterprise Management
Usage: ./enterprise_deploy.sh [COMMAND]

Commands:
  setup       Full setup of the environment and components
  deploy      Deploy the infrastructure with current configuration
  status      Check status of all components
  backup      Create a backup of all configurations and contracts
  test        Run integration tests
  zeta        Access ZETA Playground functionality directly
  
Options:
  --offline   Force offline mode for all operations
  --env=FILE  Use specific environment file
  --help      Show this help message
EOF
}

main() {
    local command=${1:-"setup"}
    
    # Welcome message
    echo -e "${BOLD}${BLUE}=================================================${NC}"
    echo -e "${BOLD}${BLUE}  MCP-ZERO + ZETA Playground Enterprise Deployment${NC}"
    echo -e "${BOLD}${BLUE}=================================================${NC}"
    echo
    
    case "$command" in
        "setup")
            log "INFO" "Starting full setup..."
            setup_environment
            setup_immutable_contracts
            integrate_components
            setup_security
            run_integration_tests
            log "SUCCESS" "MCP-ZERO + ZETA Playground enterprise setup completed!"
            log "INFO" "You can now use 'bin/mcp-zeta' and 'bin/zeta' commands"
            ;;
            
        "deploy")
            log "INFO" "Deploying infrastructure..."
            source "$ENV_FILE" || { log "ERROR" "Failed to load environment"; exit 1; }
            integrate_components
            log "SUCCESS" "Deployment completed!"
            ;;
            
        "status")
            log "INFO" "Checking component status..."
            if [ -f "${SERVER_FILE}" ]; then
                echo -e "${BLUE}Server Configuration:${NC}"
                grep -v "^#" "${SERVER_FILE}" | sort
                echo
            fi
            
            if [ -x "${ZETA_ROOT}/zeta_cli.py" ]; then
                "${ZETA_ROOT}/zeta_cli.py" test-resilience
            fi
            ;;
            
        "backup")
            backup_dir="${MCPZERO_ROOT}/backups/$(date +%Y%m%d)"
            log "INFO" "Creating backup in ${backup_dir}..."
            mkdir -p "${backup_dir}"
            
            cp -r "${CONTRACTS_ROOT}" "${backup_dir}/" || log "WARNING" "Failed to backup contracts"
            cp "${ENV_FILE}" "${backup_dir}/" || log "WARNING" "Failed to backup .env file"
            cp "${SERVER_FILE}" "${backup_dir}/" || log "WARNING" "Failed to backup .server file"
            cp -r "${ZETA_ROOT}/config" "${backup_dir}/" || log "WARNING" "Failed to backup ZETA config"
            
            log "SUCCESS" "Backup completed: ${backup_dir}"
            ;;
            
        "test")
            run_integration_tests
            ;;
            
        "zeta")
            shift
            if [ -x "${ZETA_ROOT}/zeta_cli.py" ]; then
                "${ZETA_ROOT}/zeta_cli.py" "$@"
            else
                log "ERROR" "ZETA CLI not found or not executable"
                exit 1
            fi
            ;;
            
        "--help" | "help" | "-h")
            show_help
            ;;
            
        *)
            log "ERROR" "Unknown command: $command"
            show_help
            exit 1
            ;;
    esac
}

main "$@"
