#!/bin/bash
# MCP-ZERO Configuration Generator
# Generates configuration files for burn folder deployment

# Ensure templates directory exists
mkdir -p "$(dirname "$0")/templates"

# Generate API configuration
generate_api_config() {
  local config_dir="$1"
  local api_port="$2"
  local offline_mode="$3"
  
  cat > "${config_dir}/api.json" << EOF
{
  "server": {
    "port": ${api_port},
    "host": "0.0.0.0",
    "workers": 4,
    "debug": false
  },
  "auth": {
    "provider": "jwt",
    "secret_key_path": ".mcp/certs/jwt_secret",
    "token_expiry": 86400
  },
  "cors": {
    "enabled": true,
    "origins": ["*"],
    "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
  },
  "rate_limiting": {
    "enabled": true,
    "requests_per_minute": 60
  },
  "offline_mode": {
    "enabled": ${offline_mode},
    "fallback_enabled": true,
    "connection_attempts": 1,
    "lock_file": ".mcp/locks/offline.lock"
  },
  "database": {
    "path": ".mcp/db/agent_memory.db",
    "backup_path": ".mcp/db/backups"
  },
  "monitoring": {
    "enabled": true,
    "metrics_collection": true,
    "log_level": "INFO"
  }
}
EOF

  echo "Generated API configuration at ${config_dir}/api.json"
}

# Generate Dashboard configuration
generate_dashboard_config() {
  local config_dir="$1"
  local dashboard_port="$2"
  local api_port="$3"
  local offline_mode="$4"
  
  cat > "${config_dir}/dashboard.json" << EOF
{
  "server": {
    "port": ${dashboard_port},
    "host": "0.0.0.0"
  },
  "api": {
    "url": "http://localhost:${api_port}",
    "timeout": 30000
  },
  "ui": {
    "theme": "light",
    "offline_indicator": true,
    "auto_refresh": true,
    "refresh_interval": 60000
  },
  "features": {
    "agent_management": true,
    "memory_metrics": true,
    "audit_trails": true,
    "ai_testing": true,
    "ai_playground": true
  },
  "offline_mode": {
    "enabled": ${offline_mode},
    "ui_indication": true
  }
}
EOF

  echo "Generated Dashboard configuration at ${config_dir}/dashboard.json"
}

# Generate RPC configuration
generate_rpc_config() {
  local config_dir="$1"
  local rpc_port="$2"
  local offline_mode="$3"
  
  cat > "${config_dir}/rpc.json" << EOF
{
  "server": {
    "port": ${rpc_port},
    "host": "0.0.0.0",
    "workers": 4
  },
  "protocol": {
    "version": "1.0",
    "timeout": 30,
    "max_message_size": 10485760
  },
  "security": {
    "tls_enabled": false,
    "cert_file": ".mcp/certs/server.crt",
    "key_file": ".mcp/certs/server.key"
  },
  "offline_mode": {
    "enabled": ${offline_mode},
    "fallback_enabled": true,
    "connection_attempts": 1
  }
}
EOF

  echo "Generated RPC configuration at ${config_dir}/rpc.json"
}

# Generate Monitoring configuration
generate_monitoring_config() {
  local config_dir="$1"
  local offline_mode="$2"
  
  cat > "${config_dir}/monitoring.json" << EOF
{
  "metrics": {
    "collection_interval": 60,
    "retention_days": 30,
    "storage_path": ".mcp/db/metrics.db"
  },
  "alerts": {
    "enabled": true,
    "cpu_threshold": 80,
    "memory_threshold": 80,
    "disk_threshold": 90
  },
  "logging": {
    "level": "INFO",
    "file": "logs/monitoring.log",
    "max_size_mb": 100,
    "max_files": 10
  },
  "offline_mode": {
    "enabled": ${offline_mode},
    "metrics_storage": "local"
  }
}
EOF

  echo "Generated Monitoring configuration at ${config_dir}/monitoring.json"
}

# Generate Offline mode configuration
generate_offline_config() {
  local config_dir="$1"
  
  cat > "${config_dir}/offline.json" << EOF
{
  "mode": {
    "enabled": true,
    "permanent": false,
    "reason": "Configured during deployment",
    "created_at": "$(date -Iseconds)"
  },
  "policies": {
    "fallback_strategy": "local_first",
    "connection_attempts": 1,
    "lock_file_path": ".mcp/locks/offline.lock"
  },
  "caching": {
    "enabled": true,
    "storage_path": ".mcp/cache",
    "max_size_mb": 1024,
    "ttl_seconds": 86400
  },
  "security": {
    "enforce_local_auth": true,
    "warn_on_sensitive_operations": true
  }
}
EOF

  echo "Generated Offline mode configuration at ${config_dir}/offline.json"
}

# Generate Security configuration
generate_security_config() {
  local config_dir="$1"
  
  cat > "${config_dir}/security.json" << EOF
{
  "auth": {
    "providers": ["local", "jwt"],
    "default_provider": "local",
    "session_timeout": 3600
  },
  "encryption": {
    "algorithm": "AES-256-GCM",
    "key_rotation_days": 90
  },
  "access_control": {
    "enabled": true,
    "default_policy": "deny",
    "roles": [
      {
        "name": "admin",
        "permissions": ["*"]
      },
      {
        "name": "user",
        "permissions": ["read", "execute"]
      },
      {
        "name": "guest",
        "permissions": ["read"]
      }
    ]
  },
  "audit": {
    "enabled": true,
    "storage": ".mcp/db/audit_trail.db",
    "retention_days": 365,
    "immutable": true
  }
}
EOF

  echo "Generated Security configuration at ${config_dir}/security.json"
}

# Generate all configurations
generate_all_configs() {
  local config_dir="$1"
  local api_port="$2"
  local dashboard_port="$3"
  local rpc_port="$4"
  local offline_mode="$5"
  
  # Convert offline_mode to JSON boolean
  if [ "$offline_mode" -eq 1 ]; then
    offline_json="true"
  else
    offline_json="false"
  fi
  
  generate_api_config "$config_dir" "$api_port" "$offline_json"
  generate_dashboard_config "$config_dir" "$dashboard_port" "$api_port" "$offline_json"
  generate_rpc_config "$config_dir" "$rpc_port" "$offline_json"
  generate_monitoring_config "$config_dir" "$offline_json"
  
  if [ "$offline_mode" -eq 1 ]; then
    generate_offline_config "$config_dir"
  fi
  
  generate_security_config "$config_dir"
  
  echo "All configuration files generated successfully"
}

# If script is executed directly, show usage
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  echo "This script is intended to be sourced by burn.sh"
  echo "Usage: source $(basename "$0")"
fi
