#!/bin/bash
# MCP-ZERO Burn Script for Healthcare Agent Integration
# Configures proper integration of healthcare agent with ZETA components and playground

set -e

# Color definitions
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

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

# Print colored message
print_message() {
  local color=$1
  local message=$2
  echo -e "${color}${message}${NC}"
}

# Check for required dependencies
check_dependencies() {
  print_message "${BLUE}" "Checking dependencies..."
  
  MISSING_DEPS=0
  
  # Check for essential tools
  for cmd in python3 pip3 jq; do
    if ! command -v ${cmd} &> /dev/null; then
      print_message "${RED}" "Error: Required tool '${cmd}' is not installed."
      MISSING_DEPS=1
    fi
  done
  
  if [ ${MISSING_DEPS} -eq 1 ]; then
    print_message "${RED}" "Please install missing dependencies and try again."
    exit 1
  fi
  
  print_message "${GREEN}" "All dependencies satisfied."
}

# Verify configuration files
verify_configuration() {
  print_message "${BLUE}" "Verifying configuration..."
  
  # Check if burn_config.json exists
  if [ ! -f "${SCRIPT_DIR}/burn_config.json" ]; then
    print_message "${RED}" "Error: burn_config.json not found."
    exit 1
  fi
  
  # Check if config is valid JSON
  if ! jq empty "${SCRIPT_DIR}/burn_config.json" 2>/dev/null; then
    print_message "${RED}" "Error: burn_config.json is not valid JSON."
    exit 1
  fi
  
  print_message "${GREEN}" "Configuration verified."
}

# Setup core MCP-ZERO infrastructure
setup_core_infrastructure() {
  print_message "${BLUE}" "Setting up core MCP-ZERO infrastructure..."
  
  # Create .mcpzero directory if it doesn't exist
  mkdir -p "${MCPZERO_ROOT}/.mcpzero/locks"
  mkdir -p "${MCPZERO_ROOT}/.mcpzero/logs"
  
  # Create offline lock file if enabled in config
  OFFLINE_MODE=$(jq -r '.offline_mode // false' "${SCRIPT_DIR}/burn_config.json")
  if [ "${OFFLINE_MODE}" = "true" ]; then
    LOCK_FILE="${MCPZERO_ROOT}/.mcpzero/locks/offline.lock"
    if [ ! -f "${LOCK_FILE}" ]; then
      echo "{\"timestamp\": $(date +%s), \"reason\": \"Configured by burn script\", \"immutable\": true}" > "${LOCK_FILE}"
      chmod 444 "${LOCK_FILE}"
      print_message "${YELLOW}" "Created immutable offline lock file."
    fi
  fi
  
  # Verify playground directory exists
  if [ ! -d "${MCPZERO_ROOT}/.mcpzero/playground" ]; then
    print_message "${RED}" "Error: Core playground directory not found at ${MCPZERO_ROOT}/.mcpzero/playground"
    print_message "${YELLOW}" "Make sure you're running this script from a valid burn folder."
    exit 1
  fi
  
  print_message "${GREEN}" "Core infrastructure setup complete."
}

# Setup healthcare agent integration
setup_healthcare_agent() {
  print_message "${BLUE}" "Setting up healthcare agent integration..."
  
  # Create directories if they don't exist
  mkdir -p "${MCPZERO_ROOT}/agents/healthcare/models"
  mkdir -p "${MCPZERO_ROOT}/agents/healthcare/contracts"
  mkdir -p "${MCPZERO_ROOT}/agents/healthcare/data"
  mkdir -p "${MCPZERO_ROOT}/logs"
  
  # Extract healthcare agent path from config
  HEALTHCARE_ENABLED=$(jq -r '.components.healthcare_agent.enabled // false' "${SCRIPT_DIR}/burn_config.json")
  
  if [ "${HEALTHCARE_ENABLED}" = "true" ]; then
    print_message "${GREEN}" "Healthcare agent enabled, configuring integration..."
    
    # Ensure playground_adapter.py exists
    if [ ! -f "${MCPZERO_ROOT}/agents/healthcare/playground_adapter.py" ]; then
      print_message "${RED}" "Error: Healthcare agent adapter not found."
      print_message "${YELLOW}" "Make sure playground_adapter.py exists in agents/healthcare directory."
      exit 1
    fi
    
    # Make executable
    chmod +x "${MCPZERO_ROOT}/agents/healthcare/playground_adapter.py"
    
    # Create symlink to core playground in healthcare directory if it doesn't exist
    if [ ! -L "${MCPZERO_ROOT}/agents/healthcare/zeta_playground.py" ]; then
      ln -sf "${MCPZERO_ROOT}/.mcpzero/playground/zeta_playground.py" "${MCPZERO_ROOT}/agents/healthcare/zeta_playground.py"
      print_message "${GREEN}" "Created symbolic link to core ZETA playground."
    fi
    
    print_message "${GREEN}" "Healthcare agent integration complete."
  else
    print_message "${YELLOW}" "Healthcare agent disabled in configuration, skipping setup."
  fi
}

# Setup and burn contracts
setup_contracts() {
  print_message "${BLUE}" "Setting up immutable contracts..."
  
  # Create contract directories if they don't exist
  mkdir -p "${MCPZERO_ROOT}/agents/healthcare/contracts/burned"
  mkdir -p "${MCPZERO_ROOT}/agents/healthcare/contracts/locks"
  
  # Check if contract.yaml exists
  if [ ! -f "${MCPZERO_ROOT}/agents/healthcare/contracts/contract.yaml" ]; then
    print_message "${YELLOW}" "No contract.yaml found, creating template..."
    
    # Create a template contract.yaml
    cat > "${MCPZERO_ROOT}/agents/healthcare/contracts/contract.yaml" << 'EOL'
# Healthcare Agent Contract System
# This contract.yaml file will be automatically burned during deployment

version: "1.0"
timestamp: "$(date +%Y-%m-%dT%H:%M:%S%z)"
burn_enabled: true
offline_first: true

# Contract definitions for healthcare agent system
contracts:
  patient_data:
    version: "1.0"
    required_fields:
      - case_id
      - patient_info
      - symptoms
    validation_level: "strict"
    hash_algorithm: "sha256"

  message:
    version: "1.0"
    required_fields:
      - message_id
      - content
      - timestamp
    validation_level: "strict"
    hash_algorithm: "sha256"

# Burn process configuration
burn:
  enabled: true
  target_dir: "/opt/mcp-zero/contracts/burned"
  backup_enabled: false
  lock_files: true
  verification_hash: true
EOL
    print_message "${GREEN}" "Created template contract.yaml"
  fi
  
  # Run the contract burn script
  print_message "${BLUE}" "Burning contracts to make them immutable..."
  
  # Check if Python burn script exists
  if [ -f "${MCPZERO_ROOT}/agents/healthcare/scripts/burn_contracts.py" ]; then
    # Execute the Python burn script
    cd "${MCPZERO_ROOT}/agents/healthcare"
    python3 scripts/burn_contracts.py --contract-dir="./contracts" --burn-dir="./contracts/burned" --lock-dir="./contracts/locks"
    
    if [ $? -eq 0 ]; then
      print_message "${GREEN}" "Successfully burned contracts for healthcare agent"
    else
      print_message "${RED}" "Warning: Contract burn process completed with errors"
    fi
    cd - > /dev/null
  else
    # Perform a simple burn if script doesn't exist
    CONTRACT_FILE="${MCPZERO_ROOT}/agents/healthcare/contracts/contract.yaml"
    if [ -f "$CONTRACT_FILE" ]; then
      CONTRACT_HASH=$(sha256sum "$CONTRACT_FILE" | cut -d ' ' -f1)
      TIMESTAMP=$(date +%Y-%m-%dT%H:%M:%S%z)
      BURNED_FILE="${MCPZERO_ROOT}/agents/healthcare/contracts/burned/contract.burned"
      
      echo "{
  \"contract_id\": \"contract\",
  \"hash\": \"$CONTRACT_HASH\",
  \"burned_at\": \"$TIMESTAMP\",
  \"burned_by\": \"burn-script\",
  \"content\": $(cat "$CONTRACT_FILE" | python3 -c "import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin)))")
}" > "$BURNED_FILE"
      
      # Create lock file
      echo "Contract burned at $TIMESTAMP" > "${MCPZERO_ROOT}/agents/healthcare/contracts/locks/contract.lock"
      echo "Hash: $CONTRACT_HASH" >> "${MCPZERO_ROOT}/agents/healthcare/contracts/locks/contract.lock"
      
      print_message "${GREEN}" "Successfully burned contract.yaml (simple burn)"
    else
      print_message "${YELLOW}" "No contracts found to burn"
    fi
  fi
  
  # Setup Terraform for contracts if available
  if [ -d "${MCPZERO_ROOT}/agents/healthcare/terraform" ]; then
    print_message "${BLUE}" "Setting up Terraform for contract deployment..."
    
    # Check if Terraform is installed
    if command -v terraform &> /dev/null; then
      cd "${MCPZERO_ROOT}/agents/healthcare/terraform"
      terraform init -input=false
      
      # Don't apply yet, just prepare
      print_message "${GREEN}" "Terraform initialized for contract deployment"
      cd - > /dev/null
    else
      print_message "${YELLOW}" "Terraform not installed, skipping infrastructure setup"
    fi
  fi
  
  print_message "${GREEN}" "Contracts setup complete"
}

# Create convenience scripts
create_convenience_scripts() {
  print_message "${BLUE}" "Creating convenience scripts..."
  
  # Create start script for healthcare agent
  HEALTHCARE_ENABLED=$(jq -r '.components.healthcare_agent.enabled // false' "${SCRIPT_DIR}/burn_config.json")
  
  if [ "${HEALTHCARE_ENABLED}" = "true" ]; then
    cat > "${MCPZERO_ROOT}/start_healthcare_agent.sh" << 'EOF'
#!/bin/bash
# Start the healthcare agent with ZETA playground integration

set -e

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

# Create logs directory if it doesn't exist
mkdir -p "${SCRIPT_DIR}/logs"

echo "Starting healthcare agent..."
python3 "${SCRIPT_DIR}/agents/healthcare/playground_adapter.py" --config "${SCRIPT_DIR}/burn_config.json" "$@"
EOF
    chmod +x "${MCPZERO_ROOT}/start_healthcare_agent.sh"
    print_message "${GREEN}" "Created healthcare agent start script."
  fi
  
  # Create general start script
  cat > "${MCPZERO_ROOT}/start_all.sh" << 'EOF'
#!/bin/bash
# Start all MCP-ZERO components

set -e

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

# Create logs directory if it doesn't exist
mkdir -p "${SCRIPT_DIR}/logs"

# Check if we're in offline mode
if [ -f "${SCRIPT_DIR}/.mcpzero/locks/offline.lock" ]; then
  echo "Running in offline mode (lock file exists)"
else
  echo "Running in online mode (no lock file)"
fi

# Start core components (add more as needed)
echo "Starting core components..."

# Start healthcare agent if enabled and script exists
if [ -f "${SCRIPT_DIR}/start_healthcare_agent.sh" ]; then
  echo "Starting healthcare agent..."
  "${SCRIPT_DIR}/start_healthcare_agent.sh" --mode status
fi

echo "All components started."
EOF
    chmod +x "${MCPZERO_ROOT}/start_all.sh"
    print_message "${GREEN}" "Created start_all script."
}

# Create burn documentation
create_documentation() {
  print_message "${BLUE}" "Creating documentation..."
  
  cat > "${MCPZERO_ROOT}/BURN-README.md" << 'EOF'
# MCP-ZERO Healthcare Burn Folder

This burn folder integrates the healthcare agent with core MCP-ZERO infrastructure using the ZETA playground.

## Component Architecture

- **Core Infrastructure**: `.mcpzero/playground/`
  - ZETA Integration Layer
  - Intent Emergence System
  - VRLL Engine
  - Causal World
  - Offline-first resilience implementation

- **Healthcare Agent**: `agents/healthcare/`
  - Playground Adapter (interfaces with core ZETA playground)
  - Healthcare-specific models and data
  - Training infrastructure

## Offline-First Resilience

All components implement the offline-first resilience pattern with:
- Single connection attempt before permanent fallback to offline mode
- Immutable lock files for fallback audit (`./mcpzero/locks/`)
- Local processing capabilities for all components

## Getting Started

1. Run the start script:
   ```
   ./start_all.sh
   ```

2. To use just the healthcare agent:
   ```
   ./start_healthcare_agent.sh --mode query --query "Your medical query here"
   ```

3. Train the healthcare agent:
   ```
   ./start_healthcare_agent.sh --mode train --dataset ./agents/healthcare/data/training
   ```

## Configuration

All configuration is centralized in `burn_config.json` at the root of the burn folder.
EOF
  
  print_message "${GREEN}" "Documentation created."
}

# Main execution
main() {
  print_message "${BLUE}" "MCP-ZERO Healthcare Burn Script"
  print_message "${BLUE}" "============================="
  
  # Check dependencies
  check_dependencies
  
  # Verify configuration
  verify_configuration
  
  # Setup core infrastructure
  setup_core_infrastructure
  
  # Setup healthcare agent
  setup_healthcare_agent
  
  # Setup and burn contracts
  setup_contracts
  
  # Create convenience scripts
  create_convenience_scripts
  
  # Create documentation
  create_documentation
  
  print_message "${GREEN}" "Burn process completed successfully!"
  print_message "${YELLOW}" "Next steps:"
  print_message "${YELLOW}" "1. Review the BURN-README.md for usage instructions"
  print_message "${YELLOW}" "2. Run './start_all.sh' to start all components"
  print_message "${YELLOW}" "3. Verify health with './start_healthcare_agent.sh --mode status'"
}

main "$@"
