#!/usr/bin/env nu

# Installation script for nushell and plugins
# This script registers all plugins with the nushell binary

def main [
    --verify  # Verify installation after completion
] {
    print "🚀 Installing Nushell and plugins..."

    # Get current directory (should be the distribution directory)
    let dist_dir = $env.PWD

    # Find nushell binary
    let nu_binary = if ("nu" | path exists) {
        "./nu"
    } else if ("nu.exe" | path exists) {
        "./nu.exe"
    } else {
        print "❌ Nushell binary not found in distribution"
        exit 1
    }

    # Find plugin binaries
    let plugins = ls . | where type == "file" | where name =~ "nu_plugin_" | get name

    print $"📦 Found ($plugins | length) plugins to register"

    # Register each plugin
    for plugin in $plugins {
        print $"  Registering ($plugin)..."
        let result = (do {
            run-external $nu_binary "-c" $"plugin add ./($plugin)"
        } | complete)

        if $result.exit_code != 0 {
            print $"  ⚠️  Failed to register ($plugin): ($result.stderr)"
        }
    }

    if $verify {
        print "🔍 Verifying installation..."
        let verify_result = (do {
            let plugin_list = (run-external $nu_binary "-c" "plugin list" | complete)
            if $plugin_list.exit_code == 0 {
                print "✅ Plugin verification successful"
                print $plugin_list.stdout
            } else {
                print "❌ Plugin verification failed"
                print $plugin_list.stderr
            }
        } | complete)

        if $verify_result.exit_code != 0 {
            print $"❌ Verification failed: ($verify_result.stderr)"
        }
    }

    print "✅ Installation complete!"
}
