#!/usr/bin/env nu

# Plugin Registration Script with Verification
# Handles registration of nushell plugins with automatic verification

# Register a single plugin
def register_single_plugin [
    plugin_path: string
    --verify (-v)                # Verify registration after plugin add
] {
    let plugin_name = ($plugin_path | path basename)
    let display_name = ($plugin_name | str replace "nu_plugin_" "")

    print $"🔌 Registering ($plugin_name)..."

    if not ($plugin_path | path exists) {
        print $"❌ Plugin binary not found: ($plugin_path)"
        return {success: false, error: "binary_not_found"}
    }

    # Register the plugin
    try {
        nu -c $"plugin add ($plugin_path)"
        print $"  ✅ Registered ($plugin_name)"

        # Verify if requested
        if $verify {
            print $"  🔍 Verifying registration..."
            let found = (nu -c $"plugin list | where name =~ ($display_name) | length" | into int)

            if $found > 0 {
                print $"  ✅ Verified ($plugin_name)"
                return {success: true, verified: true}
            } else {
                print $"  ⚠️  Could not verify ($plugin_name)"
                return {success: true, verified: false}
            }
        } else {
            return {success: true, verified: null}
        }
    } catch {|err|
        print $"  ❌ Failed to register ($plugin_name): ($err.msg)"
        return {success: false, error: $err.msg}
    }
}

# Register multiple plugins
def register_multiple_plugins [
    plugin_paths: list<string>
    --verify (-v)                # Verify registration after each plugin add
] {
    mut results = []
    mut registered = 0
    mut failed = 0
    mut verified = 0

    for plugin_path in $plugin_paths {
        let result = (register_single_plugin $plugin_path --verify=$verify)
        $results = ($results | append $result)

        if $result.success {
            $registered = $registered + 1
            if $verify and $result.verified {
                $verified = $verified + 1
            }
        } else {
            $failed = $failed + 1
        }
    }

    print ""
    print "📊 Registration summary:"
    print $"  ✅ Registered: ($registered) plugins"
    if $verify {
        print $"  🔍 Verified: ($verified) plugins"
    }
    if $failed > 0 {
        print $"  ❌ Failed: ($failed) plugins"
    }

    {
        total: ($plugin_paths | length),
        registered: $registered,
        failed: $failed,
        verified: $verified,
        results: $results
    }
}

# Verify plugin registration status
def verify_plugin_registration [
    plugin_paths: list<string>
] {
    print "🔍 Verifying plugin registration status..."
    print ""

    mut registered_plugins = 0
    mut total_plugins = ($plugin_paths | length)

    for plugin_path in $plugin_paths {
        let plugin_name = ($plugin_path | path basename)
        let display_name = ($plugin_name | str replace "nu_plugin_" "")

        if ($plugin_path | path exists) {
            let found = (nu -c $"plugin list | where name =~ ($display_name) | length" | into int)

            if $found > 0 {
                print $"  ✅ ($plugin_name) \(registered\)"
                $registered_plugins = $registered_plugins + 1
            } else {
                print $"  ❌ ($plugin_name) \(not registered\)"
                print $"      💡 Register with: nu register_plugins.nu register ($plugin_path)"
            }
        } else {
            print $"  ⚠️  ($plugin_name) \(binary not found\)"
        }
    }

    print ""
    print "📊 Verification summary:"
    print $"  📦 Total plugins: ($total_plugins)"
    print $"  ✅ Registered: ($registered_plugins)"
    print $"  ❌ Not registered: ($total_plugins - $registered_plugins)"

    if $registered_plugins == $total_plugins and $total_plugins > 0 {
        print ""
        print "🎉 All plugins are properly registered!"
    } else if $total_plugins == 0 {
        print ""
        print "💡 No plugins found."
    } else {
        print ""
        print "💡 Some plugins need registration"
    }

    {
        total: $total_plugins,
        registered: $registered_plugins,
        missing: ($total_plugins - $registered_plugins)
    }
}

# Find all built plugins in the workspace
def find_built_plugins [] {
    glob "nu_plugin_*/target/release/nu_plugin_*"
    | where ($it | path type) == "file"
    | where not ($it | str ends-with ".d")
}

# Main command interface
def main [
    command?: string            # Command: register, verify, register-all
    plugin_path?: string        # Plugin path for single registration
    --verify (-v)               # Verify registration
    --paths (-p): list<string> = []  # Multiple plugin paths
] {
    match $command {
        "register" => {
            if ($plugin_path | is-empty) {
                print "❌ Plugin path required for register command"
                print "Usage: nu register_plugins.nu register <plugin_path> [--verify]"
                return
            }
            register_single_plugin $plugin_path --verify=$verify
        }
        "register-multiple" => {
            if ($paths | is-empty) {
                print "❌ Plugin paths required for register-multiple command"
                print "Usage: nu register_plugins.nu register-multiple --paths [path1, path2, ...]"
                return
            }
            register_multiple_plugins $paths --verify=$verify
        }
        "register-all" => {
            let built_plugins = (find_built_plugins)
            if ($built_plugins | is-empty) {
                print "❓ No built plugins found"
                print "💡 Run 'cargo build --release' in plugin directories first"
                return
            }
            print $"🔌 Registering all built plugins... \(found ($built_plugins | length)\)"
            register_multiple_plugins $built_plugins --verify=$verify
        }
        "verify" => {
            if not ($plugin_path | is-empty) {
                verify_plugin_registration [$plugin_path]
            } else if not ($paths | is-empty) {
                verify_plugin_registration $paths
            } else {
                let built_plugins = (find_built_plugins)
                verify_plugin_registration $built_plugins
            }
        }
        _ => {
            print "🔌 Plugin Registration Script"
            print "=============================="
            print ""
            print "Commands:"
            print "  register <path>          - Register single plugin"
            print "  register-multiple        - Register multiple plugins (use --paths)"
            print "  register-all             - Register all built plugins"
            print "  verify [path]            - Verify plugin registration"
            print ""
            print "Options:"
            print "  --verify (-v)            - Verify registration after plugin add"
            print "  --paths (-p) [...]       - Specify multiple plugin paths"
            print ""
            print "Examples:"
            print "  nu register_plugins.nu register ./nu_plugin_clipboard/target/release/nu_plugin_clipboard --verify"
            print "  nu register_plugins.nu register-all --verify"
            print "  nu register_plugins.nu verify"
        }
    }
}