#!/bin/bash

# BZZZ Setup Transition Script
# This script helps users transition to the new web-based configuration system

set -e

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

# Configuration
BZZZ_CONFIG_DIR="$HOME/.bzzz"
BZZZ_CONFIG_FILE="$BZZZ_CONFIG_DIR/config.yaml"
BACKUP_DIR="$BZZZ_CONFIG_DIR/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

echo -e "${BLUE}🐝 BZZZ Setup Transition Script${NC}"
echo -e "${BLUE}================================${NC}"
echo ""

# Check if BZZZ is installed
check_bzzz_installation() {
    echo -e "📦 Checking BZZZ installation..."
    
    if ! command -v bzzz &> /dev/null; then
        if [ -f "./bzzz" ]; then
            echo -e "${GREEN}✅ Found BZZZ binary in current directory${NC}"
            BZZZ_BINARY="./bzzz"
        elif [ -f "./build/bzzz" ]; then
            echo -e "${GREEN}✅ Found BZZZ binary in build directory${NC}"
            BZZZ_BINARY="./build/bzzz"
        else
            echo -e "${RED}❌ BZZZ binary not found${NC}"
            echo -e "Please build BZZZ first: ${YELLOW}make build${NC}"
            exit 1
        fi
    else
        echo -e "${GREEN}✅ BZZZ is installed system-wide${NC}"
        BZZZ_BINARY="bzzz"
    fi
}

# Backup existing configuration
backup_existing_config() {
    if [ -f "$BZZZ_CONFIG_FILE" ]; then
        echo -e "💾 Backing up existing configuration..."
        mkdir -p "$BACKUP_DIR"
        cp "$BZZZ_CONFIG_FILE" "$BACKUP_DIR/config_backup_$TIMESTAMP.yaml"
        echo -e "${GREEN}✅ Configuration backed up to: $BACKUP_DIR/config_backup_$TIMESTAMP.yaml${NC}"
    else
        echo -e "${YELLOW}⚪ No existing configuration found${NC}"
    fi
}

# Check configuration status
check_config_status() {
    echo -e "🔍 Checking configuration status..."
    
    if [ -f "$BZZZ_CONFIG_FILE" ]; then
        echo -e "${GREEN}✅ Configuration file exists: $BZZZ_CONFIG_FILE${NC}"
        
        # Try to validate the configuration
        if $BZZZ_BINARY --config-check 2>/dev/null; then
            echo -e "${GREEN}✅ Configuration is valid${NC}"
            echo -e "${BLUE}🚀 BZZZ should start normally without setup${NC}"
            return 0
        else
            echo -e "${YELLOW}⚠️ Configuration exists but appears invalid${NC}"
            echo -e "${BLUE}🔧 BZZZ will start in setup mode${NC}"
            return 1
        fi
    else
        echo -e "${YELLOW}⚪ No configuration file found${NC}"
        echo -e "${BLUE}🔧 BZZZ will start in setup mode${NC}"
        return 1
    fi
}

# Start setup mode
start_setup_mode() {
    echo -e "🌐 Starting BZZZ in setup mode..."
    echo -e "📍 Setup interface will be available at: ${GREEN}http://localhost:8080${NC}"
    echo -e "📋 Follow the setup wizard to configure your BZZZ cluster"
    echo ""
    echo -e "${YELLOW}Press Ctrl+C to stop the setup server${NC}"
    echo ""
    
    # Start BZZZ (it will automatically detect setup is needed)
    $BZZZ_BINARY
}

# Generate sample configuration
generate_sample_config() {
    echo -e "📄 Generating sample configuration..."
    
    mkdir -p "$BZZZ_CONFIG_DIR"
    
    cat > "$BZZZ_CONFIG_FILE" << 'EOF'
# BZZZ Configuration File
# This is a sample configuration - customize for your environment

agent:
  id: "bzzz-agent-sample"
  capabilities:
    - "code_generation"
    - "task_coordination"
    - "p2p_communication"
  models:
    - "llama2:7b"
    - "codellama:7b"
  specialization: "general_developer"
  max_tasks: 5

github:
  token_file: "~/.config/bzzz/github_token"
  assignee: "your-username"
  rate_limit: true

p2p:
  service_tag: "bzzz-peer-discovery"
  bzzz_topic: "bzzz/coordination/v1"
  hmmm_topic: "hmmm/meta-discussion/v1"
  discovery_timeout: "10s"

logging:
  level: "info"
  format: "text"
  output: "stdout"
  structured: false

v2:
  enabled: true
  dht:
    enabled: true
    bootstrap_peers: []

security:
  election_config:
    heartbeat_timeout: "30s"
    election_timeout: "60s"
    minimum_peers: 1
  audit_logging: true
EOF

    echo -e "${GREEN}✅ Sample configuration created: $BZZZ_CONFIG_FILE${NC}"
    echo -e "${YELLOW}⚠️ Please customize this configuration for your environment${NC}"
}

# Main menu
show_menu() {
    echo -e "What would you like to do?"
    echo -e "1) ${GREEN}Check configuration status${NC}"
    echo -e "2) ${BLUE}Start setup mode (web interface)${NC}"
    echo -e "3) ${YELLOW}Generate sample configuration${NC}"
    echo -e "4) ${GREEN}Backup existing configuration${NC}"
    echo -e "5) ${RED}Exit${NC}"
    echo ""
    read -p "Enter your choice (1-5): " choice
}

# Process menu choice
process_choice() {
    case $choice in
        1)
            check_config_status
            ;;
        2)
            start_setup_mode
            ;;
        3)
            generate_sample_config
            ;;
        4)
            backup_existing_config
            ;;
        5)
            echo -e "${GREEN}👋 Goodbye!${NC}"
            exit 0
            ;;
        *)
            echo -e "${RED}❌ Invalid choice. Please enter 1-5.${NC}"
            ;;
    esac
}

# Main execution
main() {
    check_bzzz_installation
    
    echo ""
    check_config_status
    config_valid=$?
    
    echo ""
    if [ $config_valid -eq 0 ]; then
        echo -e "${GREEN}🎉 Your BZZZ configuration is ready!${NC}"
        echo -e "Run ${YELLOW}$BZZZ_BINARY${NC} to start BZZZ normally"
    else
        echo -e "${BLUE}🔧 Setup is required${NC}"
        while true; do
            echo ""
            show_menu
            process_choice
            
            if [ $choice -eq 5 ]; then
                break
            fi
            
            echo ""
            read -p "Press Enter to continue..."
        done
    fi
}

# Run main function
main