#!/usr/bin/env nu

# Rustelo Build Examples Script
# Nushell version of build-examples.sh
# Demonstrates building the application with different feature combinations

def main [...args] {
    # Parse arguments using Nushell's built-in argument handling
    let options = parse_args $args

    print $"(ansi blue)🏗️  Rustelo Build Examples(ansi reset)"

    # Validate project structure
    validate_project

    # Clean build artifacts if requested
    if $options.clean {
        clean_build
    }

    # Execute build configurations based on options
    if $options.minimal or $options.all {
        build_minimal_config
    }

    if $options.quick or $options.all {
        build_quick_configs
    }

    if $options.full or $options.all {
        build_full_config
    }

    if $options.prod or $options.all {
        build_prod_config
    }

    if $options.all {
        build_specialized_configs
    }

    # Show build summary
    show_build_summary
}

# Parse command line arguments into structured data
def parse_args [args] {
    let mut options = {
        all: false,
        minimal: false,
        full: false,
        prod: false,
        quick: false,
        clean: false,
        help: false
    }

    # Check for help first
    if ($args | any { |arg| $arg in ["-h", "--help"] }) {
        show_help
        exit 0
    }

    # Parse other options
    for arg in $args {
        match $arg {
            "-c" | "--clean" => { $options.clean = true }
            "-a" | "--all" => { $options.all = true }
            "-m" | "--minimal" => { $options.minimal = true }
            "-f" | "--full" => { $options.full = true }
            "-p" | "--prod" => { $options.prod = true }
            "-q" | "--quick" => { $options.quick = true }
            _ => {
                print $"(ansi red)❌ Unknown option: ($arg)(ansi reset)"
                show_help
                exit 1
            }
        }
    }

    # Default to build all if no specific option provided
    if not ($options.minimal or $options.full or $options.prod or $options.quick) {
        $options.all = true
    }

    $options
}

# Show help message
def show_help [] {
    print "Usage: nu build-examples.nu [OPTIONS]"
    print ""
    print "Options:"
    print "  -h, --help     Show this help message"
    print "  -c, --clean    Clean build artifacts first"
    print "  -a, --all      Build all example configurations"
    print "  -m, --minimal  Build minimal configuration only"
    print "  -f, --full     Build full-featured configuration only"
    print "  -p, --prod     Build production configuration only"
    print "  -q, --quick    Build common configurations only"
    print ""
    print "Examples:"
    print "  nu build-examples.nu --all       Build all configurations"
    print "  nu build-examples.nu --minimal   Build minimal setup"
    print "  nu build-examples.nu --clean     Clean and build all"
}

# Validate project structure
def validate_project [] {
    if not ("Cargo.toml" | path exists) {
        print $"(ansi red)❌ Cargo.toml not found. Please run this script from the project root.(ansi reset)"
        exit 1
    }

    print $"(ansi green)✅ Project structure validated(ansi reset)"
}

# Clean build artifacts
def clean_build [] {
    print $"(ansi yellow)🧹 Cleaning build artifacts...(ansi reset)"

    try {
        cargo clean
        print $"(ansi green)✅ Clean complete(ansi reset)"
    } catch {
        print $"(ansi red)❌ Failed to clean build artifacts(ansi reset)"
        exit 1
    }
}

# Build with specific features and show results
def build_with_features [name: string, features: string, description: string] {
    print $"(ansi blue)================================================(ansi reset)"
    print $"(ansi blue)($name)(ansi reset)"
    print $"(ansi blue)================================================(ansi reset)"
    print $"(ansi yellow)Building: ($name)(ansi reset)"
    print $"(ansi yellow)Features: ($features)(ansi reset)"
    print $"(ansi yellow)Description: ($description)(ansi reset)"

    let build_result = if ($features | is-empty) {
        try {
            cargo build --no-default-features --release
            "success"
        } catch {
            "failed"
        }
    } else {
        try {
            cargo build --release --features $features
            "success"
        } catch {
            "failed"
        }
    }

    if $build_result == "success" {
        print $"(ansi green)✅ Build successful(ansi reset)"

        # Get binary size
        if ("target/release/server" | path exists) {
            let binary_size = (du target/release/server | get apparent | first)
            print $"(ansi green)📊 Binary size: ($binary_size)(ansi reset)"
        }
    } else {
        print $"(ansi red)❌ Build failed(ansi reset)"
        exit 1
    }

    print ""
}

# Build minimal configuration
def build_minimal_config [] {
    print $"(ansi blue)1. MINIMAL CONFIGURATION(ansi reset)"
    build_with_features "Minimal Static Website" "" "Basic Leptos SSR with static content only"
}

# Build quick configurations
def build_quick_configs [] {
    print $"(ansi blue)2. TLS ONLY CONFIGURATION(ansi reset)"
    build_with_features "Secure Static Website" "tls" "Static website with HTTPS support"

    print $"(ansi blue)3. AUTHENTICATION ONLY CONFIGURATION(ansi reset)"
    build_with_features "Authentication App" "auth" "User authentication without database content"

    print $"(ansi blue)4. CONTENT MANAGEMENT ONLY CONFIGURATION(ansi reset)"
    build_with_features "Content Management System" "content-db" "Database-driven content without authentication"
}

# Build full-featured configuration
def build_full_config [] {
    print $"(ansi blue)5. FULL-FEATURED CONFIGURATION (DEFAULT)(ansi reset)"
    build_with_features "Complete Web Application" "auth,content-db" "Authentication + Content Management"
}

# Build production configuration
def build_prod_config [] {
    print $"(ansi blue)6. PRODUCTION CONFIGURATION(ansi reset)"
    build_with_features "Production Ready" "tls,auth,content-db" "All features with TLS for production"
}

# Build specialized configurations
def build_specialized_configs [] {
    print $"(ansi blue)7. SPECIALIZED CONFIGURATIONS(ansi reset)"

    build_with_features "TLS + Auth" "tls,auth" "Secure authentication app"
    build_with_features "TLS + Content" "tls,content-db" "Secure content management"
}

# Show build summary and next steps
def show_build_summary [] {
    print $"(ansi blue)================================================(ansi reset)"
    print $"(ansi blue)BUILD SUMMARY(ansi reset)"
    print $"(ansi blue)================================================(ansi reset)"

    print $"(ansi green)✅ Build completed successfully!(ansi reset)"
    print $"(ansi blue)📁 Binary location: target/release/server(ansi reset)"

    if ("target/release/server" | path exists) {
        let final_size = (du target/release/server | get apparent | first)
        print $"(ansi blue)📊 Final binary size: ($final_size)(ansi reset)"
    }

    print $"(ansi yellow)💡 Next steps:(ansi reset)"
    print "1. Choose your configuration based on your needs"
    print "2. Set up your .env file with appropriate settings"
    print "3. Configure database if using auth or content-db features"
    print "4. Run: ./target/release/server"

    print $"(ansi blue)================================================(ansi reset)"
    print $"(ansi blue)CONFIGURATION QUICK REFERENCE(ansi reset)"
    print $"(ansi blue)================================================(ansi reset)"

    print "Minimal (no database needed):"
    print "  cargo build --release --no-default-features"
    print ""
    print "With TLS (requires certificates):"
    print "  cargo build --release --features tls"
    print ""
    print "With Authentication (requires database):"
    print "  cargo build --release --features auth"
    print ""
    print "With Content Management (requires database):"
    print "  cargo build --release --features content-db"
    print ""
    print "Full Featured (default):"
    print "  cargo build --release"
    print ""
    print "Production (all features):"
    print "  cargo build --release --features \"tls,auth,content-db\""

    print $"(ansi green)✅ Build examples completed!(ansi reset)"
}
