#!/bin/bash
# ZETA Integration Burn Script
# Implements contract burning for ZETA components with offline-first resilience

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)"
MCP_ZERO_ROOT="${SCRIPT_DIR}"
ZETA_PLAYGROUND_DIR="${MCP_ZERO_ROOT}/src/zeta_playground"
ZETA_SI_DIR="${MCP_ZERO_ROOT}/src/zeta_si"
CONTRACT_DIR="${MCP_ZERO_ROOT}/contracts/zeta"
BURN_DIR="${MCP_ZERO_ROOT}/.mcpzero/contracts/burned"
LOCK_DIR="${MCP_ZERO_ROOT}/.mcpzero/contracts/locks"

# 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 ZETA configuration..."
  
  # Create burn config if it doesn't exist
  if [ ! -f "${SCRIPT_DIR}/zeta_burn_config.json" ]; then
    print_message "${YELLOW}" "zeta_burn_config.json not found. Creating default configuration..."
    cat > "${SCRIPT_DIR}/zeta_burn_config.json" << EOF
{
  "offline_mode": true,
  "contracts_enabled": true,
  "contract_verification_enabled": true,
  "zeta_si_enabled": true,
  "zeta_asi_enabled": true,
  "zeta_integration_enabled": true,
  "burn_timestamp": "$(date +%Y-%m-%dT%H:%M:%S%z)"
}
EOF
  fi
  
  # Check if config is valid JSON
  if ! jq empty "${SCRIPT_DIR}/zeta_burn_config.json" 2>/dev/null; then
    print_message "${RED}" "Error: zeta_burn_config.json is not valid JSON."
    exit 1
  fi
  
  print_message "${GREEN}" "Configuration verified."
}

# Setup directories
setup_directories() {
  print_message "${BLUE}" "Setting up ZETA directories..."
  
  # Create necessary directories
  mkdir -p "${BURN_DIR}"
  mkdir -p "${LOCK_DIR}"
  mkdir -p "${CONTRACT_DIR}"
  mkdir -p "${MCP_ZERO_ROOT}/.mcpzero/logs"
  
  # Create offline lock file if enabled in config
  OFFLINE_MODE=$(jq -r '.offline_mode // true' "${SCRIPT_DIR}/zeta_burn_config.json")
  if [ "${OFFLINE_MODE}" = "true" ]; then
    mkdir -p "${MCP_ZERO_ROOT}/.mcpzero/locks"
    for component in "zeta_si_bridge" "zeta_asi" "zeta_integration"; do
      LOCK_FILE="${MCP_ZERO_ROOT}/.mcpzero/locks/${component}.offline.lock"
      if [ ! -f "${LOCK_FILE}" ]; then
        echo "{\"timestamp\": $(date +%s), \"reason\": \"Configured by ZETA burn script\", \"immutable\": true}" > "${LOCK_FILE}"
        chmod 444 "${LOCK_FILE}"
        print_message "${YELLOW}" "Created immutable offline lock file for ${component}."
      fi
    done
  fi
  
  print_message "${GREEN}" "ZETA directories setup complete."
}

# Setup and burn ZETA contracts
burn_zeta_contracts() {
  print_message "${BLUE}" "Burning ZETA contracts to make them immutable..."
  
  # Check if Python burn script exists
  if [ -f "${ZETA_PLAYGROUND_DIR}/burn_zeta_integration.py" ]; then
    # Execute the Python burn script
    cd "${MCP_ZERO_ROOT}"
    python3 "${ZETA_PLAYGROUND_DIR}/burn_zeta_integration.py" \
      --contract-dir="${CONTRACT_DIR}" \
      --burn-dir="${BURN_DIR}" \
      --lock-dir="${LOCK_DIR}" \
      --zeta-si-dir="${ZETA_SI_DIR}" \
      --zeta-playground-dir="${ZETA_PLAYGROUND_DIR}" \
      --offline-locks
    
    if [ $? -eq 0 ]; then
      print_message "${GREEN}" "Successfully burned ZETA contracts"
    else
      print_message "${RED}" "Warning: ZETA contract burn process completed with errors"
    fi
  else
    print_message "${RED}" "ZETA burn script not found at ${ZETA_PLAYGROUND_DIR}/burn_zeta_integration.py"
    exit 1
  fi
  
  print_message "${GREEN}" "ZETA contract burning complete."
}

# Run integration test
run_integration_test() {
  print_message "${BLUE}" "Running ZETA integration test..."
  
  # Check if integration runner exists
  if [ -f "${ZETA_PLAYGROUND_DIR}/run_integration.py" ]; then
    # Execute the integration runner
    cd "${MCP_ZERO_ROOT}"
    python3 "${ZETA_PLAYGROUND_DIR}/run_integration.py"
    
    if [ $? -eq 0 ]; then
      print_message "${GREEN}" "Integration test completed successfully."
    else
      print_message "${RED}" "Warning: Integration test completed with errors."
    fi
  else
    print_message "${YELLOW}" "Integration runner not found. Skipping test."
  fi
}

# Main function
main() {
  print_message "${BLUE}" "=== ZETA Integration Burn Process ==="
  
  check_dependencies
  verify_configuration
  setup_directories
  burn_zeta_contracts
  
  # Run integration test if requested
  RUN_TEST=$(jq -r '.run_integration_test // false' "${SCRIPT_DIR}/zeta_burn_config.json")
  if [ "${RUN_TEST}" = "true" ]; then
    run_integration_test
  fi
  
  print_message "${GREEN}" "=== ZETA Burn Process Complete ==="
  print_message "${GREEN}" "Contracts are now immutable and offline-first resilience is configured."
  print_message "${GREEN}" "Contract burn audit trail available in: ${BURN_DIR}"
  print_message "${GREEN}" "Contract locks available in: ${LOCK_DIR}"
  print_message "${GREEN}" "Offline locks available in: ${MCP_ZERO_ROOT}/.mcpzero/locks"
  print_message "${GREEN}" "Run './burn_zeta.sh' to re-burn contracts if needed."
}

# Run the main function
main
