#!/bin/bash

# Menu Configuration Setup Script
# This script helps configure and validate menu files for the flexible menu 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

# Default paths
DEFAULT_MENU_DIR="content/menus"
DEFAULT_CONFIG_FILE="content/menu.toml"

# Print colored output
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Show help
show_help() {
    cat << EOF
Menu Configuration Setup Script

USAGE:
    $0 [COMMAND] [OPTIONS]

COMMANDS:
    setup       Set up menu configuration with prompts
    validate    Validate existing menu files
    create      Create new menu files from templates
    env         Show environment variable configuration
    test        Test menu loading functionality
    help        Show this help message

OPTIONS:
    --menu-dir DIR      Custom menu directory (default: $DEFAULT_MENU_DIR)
    --config FILE       Custom config file (default: $DEFAULT_CONFIG_FILE)
    --lang LANG         Language code for operations (default: en,es)
    --force             Force overwrite existing files
    --quiet             Minimal output

EXAMPLES:
    $0 setup                           # Interactive setup
    $0 validate                        # Validate all menu files
    $0 create --lang fr                # Create French menu template
    $0 env --menu-dir /custom/path     # Show env vars for custom path
    $0 test --lang es                  # Test Spanish menu loading

ENVIRONMENT VARIABLES:
    MENU_DIR              Custom menu directory
    MENU_CONFIG_PATH      Path to default menu config

EOF
}

# Parse command line arguments
parse_args() {
    COMMAND=""
    MENU_DIR="$DEFAULT_MENU_DIR"
    CONFIG_FILE="$DEFAULT_CONFIG_FILE"
    LANGUAGES="en es"
    FORCE=false
    QUIET=false

    while [[ $# -gt 0 ]]; do
        case $1 in
            setup|validate|create|env|test|help)
                COMMAND="$1"
                shift
                ;;
            --menu-dir)
                MENU_DIR="$2"
                shift 2
                ;;
            --config)
                CONFIG_FILE="$2"
                shift 2
                ;;
            --lang)
                LANGUAGES="$2"
                shift 2
                ;;
            --force)
                FORCE=true
                shift
                ;;
            --quiet)
                QUIET=true
                shift
                ;;
            *)
                print_error "Unknown option: $1"
                show_help
                exit 1
                ;;
        esac
    done

    if [[ -z "$COMMAND" ]]; then
        COMMAND="help"
    fi
}

# Check if required tools are available
check_dependencies() {
    local missing_deps=()

    if ! command -v toml &> /dev/null; then
        missing_deps+=("toml")
    fi

    if [[ ${#missing_deps[@]} -gt 0 ]]; then
        print_warning "Missing optional dependencies: ${missing_deps[*]}"
        print_info "Install with: cargo install toml-cli"
    fi
}

# Create menu directory if it doesn't exist
ensure_menu_dir() {
    if [[ ! -d "$MENU_DIR" ]]; then
        print_info "Creating menu directory: $MENU_DIR"
        mkdir -p "$MENU_DIR"
    fi
}

# Create a sample menu file for a language
create_menu_template() {
    local lang="$1"
    local file_path="$MENU_DIR/$lang.toml"

    if [[ -f "$file_path" && "$FORCE" != true ]]; then
        print_warning "Menu file already exists: $file_path (use --force to overwrite)"
        return 1
    fi

    local menu_content
    case "$lang" in
        "en")
            menu_content='# English Menu Configuration

[[menu]]
route = "/"
label = "Home"
is_external = false

[[menu]]
route = "/about"
label = "About"
is_external = false

[[menu]]
route = "/services"
label = "Services"
is_external = false

[[menu]]
route = "/contact"
label = "Contact"
is_external = false

[[menu]]
route = "https://github.com/your-repo"
label = "GitHub"
is_external = true'
            ;;
        "es")
            menu_content='# Spanish Menu Configuration

[[menu]]
route = "/"
label = "Inicio"
is_external = false

[[menu]]
route = "/about"
label = "Acerca de"
is_external = false

[[menu]]
route = "/services"
label = "Servicios"
is_external = false

[[menu]]
route = "/contact"
label = "Contacto"
is_external = false

[[menu]]
route = "https://github.com/your-repo"
label = "GitHub"
is_external = true'
            ;;
        *)
            menu_content="# $lang Menu Configuration

[[menu]]
route = \"/\"
label = \"Home\"
is_external = false

[[menu]]
route = \"/about\"
label = \"About\"
is_external = false"
            ;;
    esac

    echo "$menu_content" > "$file_path"
    print_success "Created menu template: $file_path"
}

# Validate a TOML file
validate_toml_file() {
    local file_path="$1"

    if [[ ! -f "$file_path" ]]; then
        print_error "File not found: $file_path"
        return 1
    fi

    # Basic TOML validation if toml command is available
    if command -v toml &> /dev/null; then
        if toml get "$file_path" . &> /dev/null; then
            print_success "Valid TOML: $file_path"
        else
            print_error "Invalid TOML: $file_path"
            return 1
        fi
    else
        # Basic check for common issues
        if grep -q "^\[\[menu\]\]" "$file_path"; then
            print_success "Basic validation passed: $file_path"
        else
            print_warning "No [[menu]] sections found in: $file_path"
        fi
    fi

    # Check required fields
    if ! grep -q "route.*=" "$file_path"; then
        print_warning "No 'route' fields found in: $file_path"
    fi

    if ! grep -q "label.*=" "$file_path"; then
        print_warning "No 'label' fields found in: $file_path"
    fi
}

# Validate all menu files
validate_menus() {
    local valid_count=0
    local total_count=0

    print_info "Validating menu files in: $MENU_DIR"

    if [[ -d "$MENU_DIR" ]]; then
        for file in "$MENU_DIR"/*.toml; do
            if [[ -f "$file" ]]; then
                total_count=$((total_count + 1))
                if validate_toml_file "$file"; then
                    valid_count=$((valid_count + 1))
                fi
            fi
        done
    fi

    # Validate default config file
    if [[ -f "$CONFIG_FILE" ]]; then
        total_count=$((total_count + 1))
        if validate_toml_file "$CONFIG_FILE"; then
            valid_count=$((valid_count + 1))
        fi
    fi

    if [[ $total_count -eq 0 ]]; then
        print_warning "No menu files found to validate"
    else
        print_info "Validation complete: $valid_count/$total_count files valid"
    fi
}

# Set up interactive menu configuration
setup_interactive() {
    print_info "Menu Configuration Setup"
    echo

    # Ask for menu directory
    read -p "Menu directory [$MENU_DIR]: " user_menu_dir
    if [[ -n "$user_menu_dir" ]]; then
        MENU_DIR="$user_menu_dir"
    fi

    # Ask for languages
    read -p "Languages to configure [$LANGUAGES]: " user_languages
    if [[ -n "$user_languages" ]]; then
        LANGUAGES="$user_languages"
    fi

    # Create directory
    ensure_menu_dir

    # Create menu files for each language
    for lang in $LANGUAGES; do
        print_info "Creating menu for language: $lang"
        create_menu_template "$lang"
    done

    # Show environment variables
    echo
    print_info "Environment variable configuration:"
    echo "export MENU_DIR=\"$(realpath "$MENU_DIR")\""
    echo "export MENU_CONFIG_PATH=\"$(realpath "$CONFIG_FILE")\""

    echo
    print_success "Menu setup complete!"
    print_info "Next steps:"
    echo "  1. Edit the generated menu files in: $MENU_DIR"
    echo "  2. Set environment variables (shown above)"
    echo "  3. Test with: $0 test"
}

# Show environment variable configuration
show_env_config() {
    print_info "Environment Variable Configuration"
    echo
    echo "# Set custom menu directory"
    echo "export MENU_DIR=\"$(realpath "$MENU_DIR")\""
    echo
    echo "# Set custom default menu config"
    echo "export MENU_CONFIG_PATH=\"$(realpath "$CONFIG_FILE")\""
    echo
    echo "# Current values:"
    echo "MENU_DIR=${MENU_DIR:-'(not set)'}"
    echo "MENU_CONFIG_PATH=${MENU_CONFIG_PATH:-'(not set)'}"
}

# Test menu loading functionality
test_menu_loading() {
    print_info "Testing menu loading functionality"

    # Test with cargo if available
    if command -v cargo &> /dev/null && [[ -f "Cargo.toml" ]]; then
        print_info "Running Rust menu loading test..."

        # Create a simple test
        cat > /tmp/test_menu_loading.rs << 'EOF'
use shared::{load_menu_for_language, load_menu_toml};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Testing default menu loading...");
    match load_menu_toml() {
        Ok(menu) => println!("✓ Default menu loaded with {} items", menu.menu.len()),
        Err(e) => println!("✗ Failed to load default menu: {}", e),
    }

    for lang in &["en", "es"] {
        println!("Testing {} menu loading...", lang);
        match load_menu_for_language(lang) {
            Ok(menu) => println!("✓ {} menu loaded with {} items", lang, menu.menu.len()),
            Err(e) => println!("✗ Failed to load {} menu: {}", lang, e),
        }
    }

    Ok(())
}
EOF

        # Note: This would require the shared crate to be available
        print_info "Test file created at /tmp/test_menu_loading.rs"
        print_info "To run: cargo run --bin test_menu_loading"
    else
        print_info "Manual testing steps:"
        echo "  1. Set environment variables:"
        echo "     export MENU_DIR=\"$(realpath "$MENU_DIR")\""
        echo "  2. Run your application"
        echo "  3. Check logs for menu loading messages"
    fi
}

# Create new menu files
create_menus() {
    ensure_menu_dir

    for lang in $LANGUAGES; do
        print_info "Creating menu template for: $lang"
        create_menu_template "$lang"
    done
}

# Main function
main() {
    parse_args "$@"

    [[ "$QUIET" != true ]] && check_dependencies

    case "$COMMAND" in
        "setup")
            setup_interactive
            ;;
        "validate")
            validate_menus
            ;;
        "create")
            create_menus
            ;;
        "env")
            show_env_config
            ;;
        "test")
            test_menu_loading
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

# Run main function with all arguments
main "$@"
