#!/bin/bash

# Configuration System Demonstration Script
# Shows the new modular configuration system in action
# Usage: ./demo-config.sh

set -e

# Script configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$(dirname "$SCRIPT_DIR")"
PROJECT_ROOT="$(dirname "$CONFIG_DIR")"

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

# Print functions
print_header() {
    echo -e "\n${BOLD}${BLUE}================================${NC}"
    echo -e "${BOLD}${BLUE}$1${NC}"
    echo -e "${BOLD}${BLUE}================================${NC}\n"
}

print_section() {
    echo -e "\n${BOLD}${CYAN}--- $1 ---${NC}"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

# Main demonstration
main() {
    print_header "Rustelo Configuration System Demo"

    echo "This demonstration shows the new modular configuration system"
    echo "that separates features into environment-specific configurations."
    echo ""
    echo "The system provides:"
    echo "  • Environment-specific settings (dev, prod, example)"
    echo "  • Feature-based configuration modules"
    echo "  • Automatic configuration building and validation"
    echo "  • Backup and management utilities"

    print_section "Configuration Structure"
    echo "Current configuration directory structure:"
    echo ""
    tree "$CONFIG_DIR" -I "__pycache__|*.pyc|*.backup*" 2>/dev/null || {
        find "$CONFIG_DIR" -type f -name "*.toml" -o -name "*.sh" -o -name "*.py" | head -20
    }

    print_section "Available Features"
    echo "Features configured in the system:"
    echo ""

    local features_dir="$CONFIG_DIR/features"
    if [ -d "$features_dir" ]; then
        for feature_dir in "$features_dir"/*; do
            if [ -d "$feature_dir" ]; then
                local feature_name=$(basename "$feature_dir")
                local env_count=0
                local env_list=""

                for env_file in "$feature_dir"/*.toml; do
                    if [ -f "$env_file" ]; then
                        env_count=$((env_count + 1))
                        local env_name=$(basename "$env_file" .toml)
                        env_list="$env_list $env_name"
                    fi
                done

                printf "  %-12s → %d environments (%s)\n" "$feature_name" "$env_count" "$env_list"
            fi
        done
    fi

    print_section "Building Development Configuration"
    echo "Building configuration for development environment..."
    echo ""

    local dev_config="demo_config_dev.toml"
    if "$SCRIPT_DIR/build-config.sh" dev "$dev_config"; then
        print_success "Development configuration built successfully"

        # Show some statistics
        local file_size=$(du -h "$dev_config" | cut -f1)
        local line_count=$(wc -l < "$dev_config")
        local section_count=$(grep -c "^\[.*\]" "$dev_config")

        echo ""
        echo "Development Configuration Stats:"
        echo "  • File size: $file_size"
        echo "  • Lines: $line_count"
        echo "  • Sections: $section_count"

        echo ""
        echo "Sample configuration sections:"
        echo ""
        grep "^\[.*\]" "$dev_config" | head -10 | sed 's/^/  /'
    else
        print_error "Failed to build development configuration"
    fi

    print_section "Building Production Configuration"
    echo "Building configuration for production environment..."
    echo ""

    local prod_config="demo_config_prod.toml"
    if "$SCRIPT_DIR/build-config.sh" prod "$prod_config"; then
        print_success "Production configuration built successfully"

        # Show some statistics
        local file_size=$(du -h "$prod_config" | cut -f1)
        local line_count=$(wc -l < "$prod_config")
        local section_count=$(grep -c "^\[.*\]" "$prod_config")

        echo ""
        echo "Production Configuration Stats:"
        echo "  • File size: $file_size"
        echo "  • Lines: $line_count"
        echo "  • Sections: $section_count"
    else
        print_error "Failed to build production configuration"
    fi

    print_section "Configuration Comparison"
    echo "Comparing development vs production configurations:"
    echo ""

    if [ -f "$dev_config" ] && [ -f "$prod_config" ]; then
        echo "Environment Differences:"
        echo ""

        # Extract key differences
        echo "Development specific settings:"
        grep -E "(debug|log_level|localhost|127\.0\.0\.1)" "$dev_config" | head -5 | sed 's/^/  /'

        echo ""
        echo "Production specific settings:"
        grep -E "(https|ssl|encryption|backup)" "$prod_config" | head -5 | sed 's/^/  /'

        echo ""
        echo "Size comparison:"
        echo "  • Dev config:  $(wc -l < "$dev_config") lines"
        echo "  • Prod config: $(wc -l < "$prod_config") lines"
        echo "  • Difference:  $(($(wc -l < "$prod_config") - $(wc -l < "$dev_config"))) lines"
    fi

    print_section "Feature Configuration Examples"
    echo "Sample feature configurations:"
    echo ""

    # Show auth feature differences
    if [ -f "$CONFIG_DIR/features/auth/dev.toml" ] && [ -f "$CONFIG_DIR/features/auth/prod.toml" ]; then
        echo "Authentication Feature:"
        echo "  Development:"
        grep -E "(max_login_attempts|lockout_duration)" "$CONFIG_DIR/features/auth/dev.toml" | head -2 | sed 's/^/    /'
        echo "  Production:"
        grep -E "(max_login_attempts|lockout_duration)" "$CONFIG_DIR/features/auth/prod.toml" | head -2 | sed 's/^/    /'
        echo ""
    fi

    # Show TLS feature differences
    if [ -f "$CONFIG_DIR/features/tls/dev.toml" ] && [ -f "$CONFIG_DIR/features/tls/prod.toml" ]; then
        echo "TLS Feature:"
        echo "  Development:"
        grep -E "(tls = |enabled = )" "$CONFIG_DIR/features/tls/dev.toml" | head -2 | sed 's/^/    /'
        echo "  Production:"
        grep -E "(tls = |enabled = )" "$CONFIG_DIR/features/tls/prod.toml" | head -2 | sed 's/^/    /'
        echo ""
    fi

    print_section "Configuration Validation"
    echo "Validating built configurations..."
    echo ""

    # Basic validation
    local validation_passed=0
    local validation_total=0

    for config in "$dev_config" "$prod_config"; do
        if [ -f "$config" ]; then
            validation_total=$((validation_total + 1))

            # Check for required sections
            local required_sections=("server" "database" "app")
            local config_name=$(basename "$config" .toml)

            echo "Validating $config_name:"

            local section_issues=0
            for section in "${required_sections[@]}"; do
                if grep -q "^\[${section}\]" "$config"; then
                    echo "  ✓ Section [$section] present"
                else
                    echo "  ✗ Section [$section] missing"
                    section_issues=$((section_issues + 1))
                fi
            done

            if [ $section_issues -eq 0 ]; then
                validation_passed=$((validation_passed + 1))
                print_success "$config_name validation passed"
            else
                print_error "$config_name validation failed"
            fi
            echo ""
        fi
    done

    print_section "Build Information"
    echo "Configuration build metadata:"
    echo ""

    if [ -f "$dev_config" ]; then
        echo "Development build info:"
        grep -A 5 "^\[build_info\]" "$dev_config" | sed 's/^/  /'
        echo ""
    fi

    print_section "Usage Examples"
    echo "How to use the configuration system:"
    echo ""
    echo "1. Build configuration for development:"
    echo "   ./config/scripts/build-config.sh dev"
    echo ""
    echo "2. Build configuration for production:"
    echo "   ./config/scripts/build-config.sh prod config.prod.toml"
    echo ""
    echo "3. Validate configuration:"
    echo "   ./config/scripts/manage-config.sh validate dev"
    echo ""
    echo "4. Compare configurations:"
    echo "   ./config/scripts/manage-config.sh diff dev prod"
    echo ""
    echo "5. Create new feature:"
    echo "   ./config/scripts/manage-config.sh template my_feature"
    echo ""
    echo "6. Show system status:"
    echo "   ./config/scripts/manage-config.sh status"

    print_section "Cleanup"
    echo "Cleaning up demo files..."

    # Clean up demo files
    rm -f "$dev_config" "$prod_config"
    print_success "Demo files cleaned up"

    print_header "Demo Complete"
    echo "The new configuration system provides:"
    echo ""
    echo "✓ Environment-specific configurations"
    echo "✓ Feature-based modularity"
    echo "✓ Automatic building and validation"
    echo "✓ Easy management and maintenance"
    echo "✓ Backup and recovery capabilities"
    echo ""
    echo "For more information, see:"
    echo "  • config/README.md - Complete documentation"
    echo "  • config/scripts/ - Available management scripts"
    echo "  • config/features/ - Feature configuration modules"
    echo ""
    print_success "Configuration system is ready to use!"
}

# Check if we're in the right directory
if [ ! -d "$CONFIG_DIR" ]; then
    print_error "Configuration directory not found: $CONFIG_DIR"
    echo "Please run this script from the project root directory."
    exit 1
fi

# Run the demonstration
main "$@"
