#!/usr/bin/env nu

# Make Plugin Script
# Creates a new plugin from template using cargo generate

# Load environment variables
def load_env_vars [] {
    let env_file = "env"
    if ($env_file | path exists) {
        open $env_file | lines
        | where ($it | str trim | str length) > 0
        | where not ($it | str starts-with "#")
        | each {|line|
            let parts = $line | split column "=" key value
            if ($parts | length) == 2 {
                {key: ($parts | get 0 | str replace "export " ""), value: ($parts | get 1)}
            } else {
                null
            }
        }
        | compact
        | reduce -f {} {|item, acc| $acc | upsert $item.key $item.value}
    } else {
        {}
    }
}

# Check if cargo-generate is installed
def check_cargo_generate [] {
    try {
        cargo generate --version | ignore
        true
    } catch {
        false
    }
}

# Main function
def main [
    plugin_name?: string        # Name of the plugin to create
    --template (-t): string = "generate/nu_plugin_template"  # Template path
    --force (-f)               # Force overwrite if directory exists
    --dry-run (-d)             # Show what would be done without executing
] {
    # Ensure we're in the repository root directory
    if not ("nu_plugin_clipboard" | path exists) {
        error make {msg: "Please run this script from the nushell-plugins repository root directory"}
    }

    print "🔧 Nushell Plugin Generator"

    # Check if cargo-generate is installed
    if not (check_cargo_generate) {
        print "❌ cargo-generate is not installed"
        print "📥 Install it with: cargo install cargo-generate"
        exit 1
    }

    # Load environment variables
    let env_vars = load_env_vars
    if $env_vars != {} {
        print $"📋 Loaded environment variables from 'env' file"
    }

    # Check if template exists
    if not ($template | path exists) {
        print $"❌ Template not found: ($template)"
        print "💡 Make sure the template directory exists"
        exit 1
    }

    # Interactive mode if no plugin name provided
    let final_plugin_name = if ($plugin_name == null) {
        input "Enter plugin name (e.g., nu_plugin_example): "
    } else {
        $plugin_name
    }

    if ($final_plugin_name | str trim | str length) == 0 {
        print "❌ Plugin name cannot be empty"
        exit 1
    }

    # Check if plugin already exists
    if ($final_plugin_name | path exists) and not $force {
        print $"❌ Directory '($final_plugin_name)' already exists"
        print "💡 Use --force to overwrite or choose a different name"
        exit 1
    }

    # Show what will be done
    print $"📦 Creating plugin: ($final_plugin_name)"
    print $"📁 Template: ($template)"

    if $force {
        print "⚠️  Force mode: Will overwrite existing directory"
    }

    if $dry_run {
        print "🔍 Dry run mode: No changes will be made"
        print $"Would run: cargo generate --path ($template) --name ($final_plugin_name)"
        return
    }

    # Create the plugin
    try {
        print "🚀 Generating plugin..."

        let cmd_args = if $force {
            ["generate", "--force", "--path", $template, "--name", $final_plugin_name]
        } else {
            ["generate", "--path", $template, "--name", $final_plugin_name]
        }

        cargo ...$cmd_args

        print $"✅ Plugin '($final_plugin_name)' created successfully!"

        # Show next steps
        print "\n📝 Next steps:"
        print $"  1. cd ($final_plugin_name)"
        print "  2. Edit Cargo.toml with your plugin details"
        print "  3. Implement your plugin in src/lib.rs"
        print "  4. Build with: cargo build --release"
        print "  5. Test with: cargo test"

        # Check if we should add to registry
        if ("etc/plugin_registry.toml" | path exists) {
            print "\n💡 Consider adding your new plugin to etc/plugin_registry.toml"
        }

    } catch {|err|
        print $"❌ Failed to generate plugin: ($err.msg)"
        exit 1
    }
}

if ($env.NUSHELL_EXECUTION_CONTEXT? | default "" | str contains "run") {
    main
}