#!/usr/bin/env nu

# Register Installed Plugins - Simple Plugin Registration
#
# This script finds plugins already installed in ~/.local/bin
# and registers them with Nushell config
#
# Usage:
#   register_installed_plugins.nu              # Register all plugins
#   register_installed_plugins.nu --check      # Check without registering
#   register_installed_plugins.nu --verify     # Register and verify

def main [
    --check (-c)                    # Check only, don't register
    --verify (-v)                   # Verify registration after adding
] {
    log_info "🔌 Plugin Registration Manager"
    log_info "=================================================================="

    let install_dir = $"($env.HOME)/.local/bin"

    # Step 1: Find installed plugins
    log_info $"\n📋 Step 1: Finding installed plugins in ($install_dir)..."
    let plugins = detect_installed_plugins $install_dir

    if ($plugins | length) == 0 {
        log_warn $"No plugins found in ($install_dir)"
        return
    }

    log_success $"Found ($plugins | length) plugin\(s\):"

    # Group by source
    let custom = ($plugins | where source == "custom")
    let core = ($plugins | where source == "core")

    if ($custom | length) > 0 {
        log_info "  Custom plugins:"
        for plugin in $custom {
            log_info $"    • ($plugin.name)"
        }
    }

    if ($core | length) > 0 {
        log_info "  Core Nushell 0.108 plugins:"
        for plugin in $core {
            log_info $"    • ($plugin.name)"
        }
    } else {
        log_info "  Core Nushell 0.108 plugins: Not built yet"
        log_info ""
        log_warn "💡 To include Nushell core plugins (polars, formats, etc):"
        log_warn "   cd nushell && cargo build --release --workspace && cd .."
        log_warn "   Then run this script again"
    }

    if $check {
        log_info "\n✅ DRY RUN - No changes made"
        return
    }

    # Step 2: Register plugins
    log_info "\n🔌 Step 2: Registering plugins with Nushell..."
    register_plugins $plugins $verify

    # Final summary
    log_info "\n=================================================================="
    log_success "✅ Plugin registration complete!"
    log_info "Next steps:"
    log_info "  1. Restart Nushell: exit && nu"
    log_info "  2. Verify plugins: nu -c 'plugin list'"
}

# Find installed plugins in ~/.local/bin and nushell/target/release
def detect_installed_plugins [
    install_dir: string
]: nothing -> list<record> {
    mut all_plugins = []

    # Check ~/.local/bin for custom plugins
    try {
        let custom_plugins = ls $install_dir
            | where type == "file"
            | where {|row|
                let basename = $row.name | path basename
                $basename =~ "^nu_plugin_"
            }
            | each {|row|
                let basename = $row.name | path basename
                {
                    name: $basename
                    path: $row.name
                    source: "custom"
                }
            }

        $all_plugins = ($all_plugins | append $custom_plugins)
    } catch {
        # Silently continue if directory doesn't exist
    }

    # Check nushell/target/release for core Nushell plugins
    let nushell_release = "./nushell/target/release"
    if ($nushell_release | path exists) {
        try {
            let core_plugins = ls $nushell_release
                | where type == "file"
                | where {|row|
                    let basename = $row.name | path basename
                    $basename =~ "^nu_plugin_"
                }
                | each {|row|
                    let basename = $row.name | path basename
                    {
                        name: $basename
                        path: $row.name
                        source: "core"
                    }
                }

            $all_plugins = ($all_plugins | append $core_plugins)
        } catch {
            # Silently continue if error reading directory
        }
    }

    $all_plugins
}

# Register plugins with Nushell
def register_plugins [
    plugins: list<record>
    verify: bool
] {
    let results = $plugins | each {|plugin|
        let plugin_path = $plugin.path
        let plugin_name = ($plugin.name | str replace "^nu_plugin_" "")

        log_info $"  Registering: ($plugin.name)"

        let reg_result = try {
            # Remove old registration if exists (suppress error)
            try {
                nu -c $"plugin rm ($plugin_name)" out+err>| null
            } catch {
                # Ignore if doesn't exist
            }

            # Add new registration
            nu -c $"plugin add ($plugin_path)"
            log_success $"    ✓ Registered"

            # Verify if requested
            if $verify {
                try {
                    let found = nu -c $"plugin list | where name =~ ($plugin_name) | length" | into int
                    if $found > 0 {
                        log_success $"    ✓ Verified"
                        {success: true, verified: true}
                    } else {
                        log_warn $"    ⚠️  Could not verify"
                        {success: true, verified: false}
                    }
                } catch {
                    log_warn $"    ⚠️  Verification failed"
                    {success: true, verified: false}
                }
            } else {
                {success: true, verified: null}
            }
        } catch {|err|
            log_error $"    ✗ Registration failed: ($err.msg)"
            {success: false, verified: false}
        }

        $reg_result
    }

    let registered = ($results | where success | length)
    let failed = ($results | where {|r| not $r.success} | length)

    print ""
    log_success $"📊 Summary:"
    log_success $"  ✅ Registered: ($registered) plugins"
    if $failed > 0 {
        log_error $"  ❌ Failed: ($failed) plugins"
    }
}

# Logging functions
def log_info [msg: string] {
    print $"ℹ️  ($msg)"
}

def log_success [msg: string] {
    print $"✅ ($msg)"
}

def log_error [msg: string] {
    print $"❌ ($msg)"
}

def log_warn [msg: string] {
    print $"⚠️  ($msg)"
}

# Call main function
main
