#!/bin/bash
# MCP-ZERO Burn Folder Verification Script
# Tests the burn folder creation and ensures 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

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

# Check if a command exists
check_command() {
  if ! command -v "$1" &> /dev/null; then
    print_message "${RED}" "Error: Command '$1' not found"
    return 1
  fi
  return 0
}

# Create test burn folder
create_test_folder() {
  local test_dir="$1"
  
  print_message "${BLUE}" "Creating test burn folder at ${test_dir}..."
  
  # Clean up any existing test directory
  if [ -d "${test_dir}" ]; then
    rm -rf "${test_dir}"
  fi
  
  # Create with all features enabled
  ./burn.sh --offline --docker --agents "${test_dir}"
  
  if [ ! -d "${test_dir}" ]; then
    print_message "${RED}" "Error: Failed to create test burn folder"
    return 1
  fi
  
  print_message "${GREEN}" "Test burn folder created successfully"
  return 0
}

# Verify configuration files
verify_configs() {
  local test_dir="$1"
  local config_dir="${test_dir}/.mcp/config"
  
  print_message "${BLUE}" "Verifying configuration files..."
  
  # Check that all required config files exist
  local required_configs=(
    "api.json"
    "dashboard.json"
    "rpc.json"
    "monitoring.json"
    "offline.json"
    "security.json"
  )
  
  local missing=0
  for config in "${required_configs[@]}"; do
    if [ ! -f "${config_dir}/${config}" ]; then
      print_message "${RED}" "Error: Missing configuration file ${config}"
      missing=1
    fi
  done
  
  if [ ${missing} -eq 1 ]; then
    return 1
  fi
  
  # Verify offline mode is properly configured
  if ! grep -q '"offline_mode": {"enabled": true' "${config_dir}/api.json"; then
    print_message "${RED}" "Error: API not configured for offline mode"
    return 1
  fi
  
  print_message "${GREEN}" "All configuration files verified successfully"
  return 0
}

# Verify database initialization
verify_databases() {
  local test_dir="$1"
  local db_dir="${test_dir}/.mcp/db"
  
  print_message "${BLUE}" "Verifying database initialization..."
  
  # Check that all required databases exist
  local required_dbs=(
    "agent_memory.db"
    "audit_trail.db"
    "metrics.db"
  )
  
  local missing=0
  for db in "${required_dbs[@]}"; do
    if [ ! -f "${db_dir}/${db}" ]; then
      print_message "${RED}" "Error: Missing database file ${db}"
      missing=1
    fi
  done
  
  if [ ${missing} -eq 1 ]; then
    return 1
  fi
  
  # Verify migration files
  if [ ! -d "${db_dir}/migrations" ] || [ $(ls -1 "${db_dir}/migrations"/*.sql 2>/dev/null | wc -l) -lt 2 ]; then
    print_message "${RED}" "Error: Missing database migration files"
    return 1
  fi
  
  print_message "${GREEN}" "All databases verified successfully"
  return 0
}

# Verify TLS certificates
verify_certificates() {
  local test_dir="$1"
  local certs_dir="${test_dir}/.mcp/certs"
  
  print_message "${BLUE}" "Verifying TLS certificates..."
  
  # Check that all required certificate files exist
  local required_certs=(
    "ca.crt"
    "ca.key"
    "server.crt"
    "server.key"
    "client.crt"
    "client.key"
    "jwt_secret"
  )
  
  local missing=0
  for cert in "${required_certs[@]}"; do
    if [ ! -f "${certs_dir}/${cert}" ]; then
      print_message "${RED}" "Error: Missing certificate file ${cert}"
      missing=1
    fi
  done
  
  if [ ${missing} -eq 1 ]; then
    return 1
  fi
  
  # Verify certificate validity
  if ! openssl x509 -in "${certs_dir}/server.crt" -noout 2>/dev/null; then
    print_message "${RED}" "Error: Invalid server certificate"
    return 1
  fi
  
  print_message "${GREEN}" "All certificates verified successfully"
  return 0
}

# Verify ZETA integration for offline-first resilience
verify_zeta_integration() {
  local test_dir="$1"
  local agents_dir="${test_dir}/agents"
  
  print_message "${BLUE}" "Verifying ZETA components integration..."
  
  # Check that all ZETA components are included in agents
  local required_components=(
    "templates/specialized/traffic_analysis.json"
    "templates/specialized/language_processing.json"
    "training/scripts/train_agent.py"
  )
  
  local missing=0
  for component in "${required_components[@]}"; do
    if [ ! -f "${agents_dir}/${component}" ]; then
      print_message "${RED}" "Error: Missing ZETA component ${component}"
      missing=1
    fi
  done
  
  if [ ${missing} -eq 1 ]; then
    return 1
  fi
  
  # Check for offline-first resilience pattern in scripts
  if ! grep -q "single connection attempt" "${agents_dir}/training/scripts/train_agent.py" || \
     ! grep -q "offline_mode" "${agents_dir}/templates/default.json"; then
    print_message "${RED}" "Error: ZETA components missing offline-first resilience pattern"
    return 1
  fi
  
  print_message "${GREEN}" "ZETA components integration verified successfully"
  return 0
}

# Verify offline mode lock files
verify_offline_locks() {
  local test_dir="$1"
  local locks_dir="${test_dir}/.mcp/locks"
  
  print_message "${BLUE}" "Verifying offline mode lock files..."
  
  # Check that offline lock file exists
  if [ ! -f "${locks_dir}/offline.lock" ]; then
    print_message "${RED}" "Error: Missing offline lock file"
    return 1
  fi
  
  # Verify lock file is immutable
  if [ $(stat -c %a "${locks_dir}/offline.lock") != "444" ]; then
    print_message "${RED}" "Error: Offline lock file is not read-only (immutable)"
    return 1
  fi
  
  # Verify lock file content
  if ! grep -q "immutable" "${locks_dir}/offline.lock"; then
    print_message "${RED}" "Error: Invalid offline lock file content"
    return 1
  fi
  
  print_message "${GREEN}" "Offline lock files verified successfully"
  return 0
}

# Verify Docker configuration
verify_docker_config() {
  local test_dir="$1"
  local docker_dir="${test_dir}/docker"
  
  print_message "${BLUE}" "Verifying Docker configuration..."
  
  # Check that all required Docker files exist
  local required_files=(
    "docker-compose.yaml"
    "Dockerfile.api"
    "Dockerfile.dashboard"
    "Dockerfile.rpc"
    "Dockerfile.monitoring"
    ".env"
    "scripts/offline_check.sh"
  )
  
  local missing=0
  for file in "${required_files[@]}"; do
    if [ ! -f "${docker_dir}/${file}" ]; then
      print_message "${RED}" "Error: Missing Docker file ${file}"
      missing=1
    fi
  done
  
  if [ ${missing} -eq 1 ]; then
    return 1
  fi
  
  # Verify offline-first resilience in Docker
  if ! grep -q "offline_check.sh" "${docker_dir}/Dockerfile.api" || \
     ! grep -q "MCP_OFFLINE_MODE" "${docker_dir}/.env"; then
    print_message "${RED}" "Error: Docker configuration missing offline-first resilience"
    return 1
  fi
  
  print_message "${GREEN}" "Docker configuration verified successfully"
  return 0
}

# Verify CLI script
verify_cli_script() {
  local test_dir="$1"
  local cli_script="${test_dir}/mcp-cli.sh"
  
  print_message "${BLUE}" "Verifying CLI script..."
  
  # Check that CLI script exists and is executable
  if [ ! -x "${cli_script}" ]; then
    print_message "${RED}" "Error: CLI script missing or not executable"
    return 1
  fi
  
  # Verify CLI has offline commands
  if ! grep -q "offline enable" "${cli_script}" || \
     ! grep -q "offline disable" "${cli_script}"; then
    print_message "${RED}" "Error: CLI script missing offline mode commands"
    return 1
  fi
  
  print_message "${GREEN}" "CLI script verified successfully"
  return 0
}

# Run all verification tests
run_verification() {
  local test_dir="/tmp/mcp-burn-test"
  local all_passed=true
  
  print_message "${BLUE}" "Starting MCP-ZERO burn folder verification..."
  
  # Create test folder
  if ! create_test_folder "${test_dir}"; then
    print_message "${RED}" "Verification failed: Could not create test folder"
    return 1
  fi
  
  # Run all verification tests
  if ! verify_configs "${test_dir}"; then
    all_passed=false
  fi
  
  if ! verify_databases "${test_dir}"; then
    all_passed=false
  fi
  
  if ! verify_certificates "${test_dir}"; then
    all_passed=false
  fi
  
  if ! verify_zeta_integration "${test_dir}"; then
    all_passed=false
  fi
  
  if ! verify_offline_locks "${test_dir}"; then
    all_passed=false
  fi
  
  if ! verify_docker_config "${test_dir}"; then
    all_passed=false
  fi
  
  if ! verify_cli_script "${test_dir}"; then
    all_passed=false
  fi
  
  # Print final results
  if [ "${all_passed}" = true ]; then
    print_message "${GREEN}" "========================================"
    print_message "${GREEN}" "All verification tests passed successfully!"
    print_message "${GREEN}" "The burn folder implementation is complete and follows offline-first resilience pattern"
    print_message "${GREEN}" "========================================"
    return 0
  else
    print_message "${RED}" "========================================"
    print_message "${RED}" "Verification failed. Please fix the issues listed above."
    print_message "${RED}" "========================================"
    return 1
  fi
}

# Main execution
main() {
  # Check required commands
  if ! check_command "openssl" || \
     ! check_command "sqlite3" || \
     ! check_command "jq" || \
     ! check_command "python3"; then
    print_message "${RED}" "Please install missing dependencies before running this script"
    exit 1
  fi
  
  # Run verification
  if run_verification; then
    exit 0
  else
    exit 1
  fi
}

main "$@"
