#!/usr/bin/env nu

# Rustelo Local Development Helper Script
# This script sets up the environment for local template development

# Get the directory where this script is located
let script_dir = $env.FILE_PWD

# Set the default template source to the local templates
let templates_dir = ($env.RUSTELO_TEMPLATES_DIR? | default ($script_dir | path join "templates"))

# Function to print colored output
def print_info [message: string] {
    print $"(ansi blue)ℹ️  ($message)(ansi reset)"
}

def print_success [message: string] {
    print $"(ansi green)✅ ($message)(ansi reset)"
}

def print_warning [message: string] {
    print $"(ansi yellow)⚠️  ($message)(ansi reset)"
}

def print_error [message: string] {
    print $"(ansi red)❌ ($message)(ansi reset)"
}

# Check if templates directory exists
if not ($templates_dir | path exists) {
    print_error $"Templates directory not found: ($templates_dir)"
    print "Please ensure you're running this script from the rustelo repository root."
    exit 1
}

# Check if templates.json exists
let templates_json = ($templates_dir | path join "templates.json")
if not ($templates_json | path exists) {
    print_error $"templates.json not found in ($templates_dir)"
    print "The templates directory appears to be incomplete."
    exit 1
}

# Set RUSTELO_ASSET_SOURCE if not already set
$env.RUSTELO_ASSET_SOURCE = ($env.RUSTELO_ASSET_SOURCE? | default $templates_dir)

print_success "Local development environment configured!"
print_info $"Using templates from: ($templates_dir)"
if $env.RUSTELO_ASSET_SOURCE != $templates_dir {
    print_info $"RUSTELO_ASSET_SOURCE overridden to: ($env.RUSTELO_ASSET_SOURCE)"
}
print ""

# Determine which rustelo binary to use
let debug_binary = ($env.RUSTELO_DEBUG_BINARY? | default ($script_dir | path join "target" "debug" "cargo-rustelo"))
let release_installed = ($env.RUSTELO_RELEASE_BINARY? | default (which cargo-rustelo | get path.0? | default ""))

# Function to get the appropriate rustelo command
def get_rustelo_cmd [command_type: string] {
    match $command_type {
        "production" | "release" | "install" => {
            # Use installed cargo rustelo for production tasks
            if ($release_installed | is-not-empty) {
                "cargo rustelo"
            } else if ($debug_binary | path exists) {
                print_warning "Using debug binary for production command. Consider installing: cargo install --path crates/rustelo-cli"
                $debug_binary
            } else {
                print_error "No rustelo binary available. Build with: cargo build"
                exit 1
            }
        }
        "dev" | "test" | "debug" => {
            # Use debug binary for development and testing (latest changes)
            if ($debug_binary | path exists) {
                $debug_binary
            } else if ($release_installed | is-not-empty) {
                print_info "Debug binary not found, using installed cargo rustelo"
                "cargo rustelo"
            } else {
                print_error "No rustelo binary available. Build with: cargo build --bin cargo-rustelo"
                exit 1
            }
        }
        _ => {
            # Default: prefer debug for local development, fallback to installed
            if ($debug_binary | path exists) {
                $debug_binary
            } else if ($release_installed | is-not-empty) {
                "cargo rustelo"
            } else {
                print_error "No rustelo binary available. Build with: cargo build --bin cargo-rustelo"
                exit 1
            }
        }
    }
}

# Check binary availability and provide guidance
if ($debug_binary | path exists) {
    print_success $"Debug binary available: ($debug_binary)"
} else {
    print_info "Debug binary not found. Build with: cargo build --bin cargo-rustelo"
}

if ($release_installed | is-not-empty) {
    print_success $"Release binary installed: ($release_installed)"
} else {
    print_info "Release binary not installed. Install with: cargo install --path crates/rustelo-cli"
}

print ""

# Main command handler
def main [command?: string, ...args] {
    match $command {
        "init" => {
            let rustelo_cmd = (get_rustelo_cmd "dev")
            print_info "Creating new Rustelo project with local templates..."
            print $"Running: ($rustelo_cmd) init ($args | str join ' ')"
            print ""
            nu -c $"($rustelo_cmd) init ($args | str join ' ')"
        }

        "update" => {
            let rustelo_cmd = (get_rustelo_cmd "dev")
            print_info "Updating Rustelo project with local templates..."
            print $"Running: ($rustelo_cmd) update ($args | str join ' ')"
            nu -c $"($rustelo_cmd) update ($args | str join ' ')"
        }

        "features" => {
            let rustelo_cmd = (get_rustelo_cmd "dev")
            print_info "Managing features with local configuration..."
            print $"Running: ($rustelo_cmd) features ($args | str join ' ')"
            nu -c $"($rustelo_cmd) features ($args | str join ' ')"
        }

        "assets" => {
            let rustelo_cmd = (get_rustelo_cmd "dev")
            print_info "Managing assets with local source..."
            print $"Running: ($rustelo_cmd) assets ($args | str join ' ')"
            nu -c $"($rustelo_cmd) assets ($args | str join ' ')"
        }

        "test" => {
            # Quick test to verify templates are accessible
            let rustelo_cmd = (get_rustelo_cmd "test")
            print_info "Testing template discovery with debug binary..."
            print $"Running: ($rustelo_cmd) init (test project)"
            print ""

            # Create a temporary test project
            let test_dir = $"/tmp/rustelo-test-(random uuid)"
            let result = (do { nu -c $"($rustelo_cmd) init ($test_dir) --template minimal" } | complete)

            if $result.exit_code == 0 {
                print_success "Template system is working correctly!"
                rm -rf $test_dir
            } else {
                print_error "Template system test failed"
            }
        }

        "list" => {
            # List available templates
            print_info $"Available templates in ($templates_dir):"
            print ""

            if (which jq | is-not-empty) {
                open $templates_json | each { |template|
                    let icon = ($template.icon? | default "📦")
                    print $"  ($icon) ($template.name) - ($template.description)"
                }
            } else {
                print "  Install 'jq' for formatted template listing"
                print $"  Templates defined in: ($templates_json)"
            }
        }

        "env" => {
            # Show current environment
            print_info "Current Rustelo environment:"
            print $"  RUSTELO_ASSET_SOURCE=($env.RUSTELO_ASSET_SOURCE)"
            print $"  RUSTELO_TEMPLATES_DIR=($env.RUSTELO_TEMPLATES_DIR? | default '<default>')"
            print $"  RUSTELO_DEBUG_BINARY=($env.RUSTELO_DEBUG_BINARY? | default '<default>')"
            print $"  RUSTELO_RELEASE_BINARY=($env.RUSTELO_RELEASE_BINARY? | default '<auto-detected>')"
            print ""
            print $"  Templates directory: ($templates_dir)"
            print $"  Script directory: ($script_dir)"
            print ""

            # Check for other relevant environment variables
            if ($env.RUST_LOG? | is-not-empty) {
                print $"  RUST_LOG=($env.RUST_LOG)"
            }

            print ""
            print "Binary Selection:"
            if ($debug_binary | path exists) {
                print $"  Debug: ($debug_binary) (preferred for dev/test)"
            } else {
                print "  Debug: Not available - run 'cargo build --bin cargo-rustelo'"
            }

            if ($release_installed | is-not-empty) {
                print $"  Release: ($release_installed) (preferred for production)"
            } else {
                print "  Release: Not installed - run 'cargo install --path crates/rustelo-cli'"
            }
        }

        "build" => {
            # Build the debug binary for local development
            print_info "Building debug binary for local development..."
            print "Running: cargo build --bin cargo-rustelo"
            print ""
            let result = (do { cargo build --bin cargo-rustelo } | complete)

            if $result.exit_code == 0 {
                print_success "Debug binary built successfully!"
                print_info $"Binary location: ($debug_binary)"
            } else {
                print_error "Build failed"
            }
        }

        "install" => {
            # Install release binary for production use
            let rustelo_cmd = (get_rustelo_cmd "production")
            print_info "Installing release binary for production use..."
            print "Running: cargo install --path crates/rustelo-cli"
            print ""
            let result = (do { cargo install --path crates/rustelo-cli } | complete)

            if $result.exit_code == 0 {
                print_success "Release binary installed successfully!"
                print_info "Now available as: cargo rustelo"
            } else {
                print_error "Installation failed"
            }
        }

        "help" | "--help" | "-h" | null => {
            print "Rustelo Local Development Helper"
            print ""
            print "This script configures the environment to use local templates"
            print $"from: ($templates_dir)"
            print ""
            print $"Usage: ($nu.current-exe) ($env.FILE_PWD)/rustelo-local.nu <command> [options]"
            print ""
            print "Commands:"
            print "  init <name> [opts]  Create a new project with local templates (uses debug binary)"
            print "  update [opts]       Update a project using local templates (uses debug binary)"
            print "  features [opts]     Manage features with local configuration (uses debug binary)"
            print "  assets [opts]       Manage assets with local source (uses debug binary)"
            print "  test               Test that local templates are working (uses debug binary)"
            print "  list               List available local templates"
            print "  env                Show current environment and binary settings"
            print "  build              Build debug binary for local development"
            print "  install            Install release binary for production use"
            print "  help               Show this help message"
            print ""
            print "Binary Selection Logic:"
            print "  • Development commands (init, update, features, assets, test) prefer debug binary"
            print "  • Production commands (install) prefer release binary"
            print "  • Debug binary: faster iteration, includes latest changes"
            print "  • Release binary: optimized, suitable for production workflows"
            print ""
            print "Environment Variables (optional overrides):"
            print "  RUSTELO_ASSET_SOURCE    - Override template source directory"
            print "  RUSTELO_TEMPLATES_DIR   - Override local templates directory"
            print "  RUSTELO_DEBUG_BINARY    - Override debug binary path"
            print "  RUSTELO_RELEASE_BINARY  - Override release binary path"
            print ""
            print "Examples:"
            print $"  ($nu.current-exe) ($env.FILE_PWD)/rustelo-local.nu init my-app"
            print $"  ($nu.current-exe) ($env.FILE_PWD)/rustelo-local.nu init my-app --template enterprise"
            print $"  ($nu.current-exe) ($env.FILE_PWD)/rustelo-local.nu test"
            print $"  ($nu.current-exe) ($env.FILE_PWD)/rustelo-local.nu list"
            print ""
            print "For more options, use: cargo rustelo <command> --help"
        }

        _ => {
            print_error $"Unknown command: ($command)"
            print "Run 'help' for usage information"
            exit 1
        }
    }
}
