# Tools Module - Development Tools and Utilities
# Commands for development utilities, plugin management, and system tools

# 🔍 VERSION AND VALIDATION COMMANDS

# Check nushell version consistency
[no-cd]
validate-nushell:
    @echo "🔍 Validating nushell version consistency..."
    @{{justfile_directory()}}/scripts/run.sh --check-only

# Fix nushell version mismatches
[no-cd]
fix-nushell:
    @echo "🔧 Fixing nushell version mismatches..."
    @{{justfile_directory()}}/scripts/run.sh --fix --check-only

# Update nu dependency versions
[no-cd]
update-nu-versions:
    @echo "🔄 Updating nu dependency versions..."
    @{{justfile_directory()}}/scripts/run.sh update_nu_versions.nu

# List current nu dependency versions
[no-cd]
list-nu-versions:
    @echo "📋 Current nu dependency versions:"
    @{{justfile_directory()}}/scripts/run.sh update_nu_versions.nu list

# Update nushell submodule
[no-cd]
update-nushell:
    @echo "🔄 Updating nushell submodule..."
    @bash {{justfile_directory()}}/scripts/sh/update_nushell.sh update

# 🆕 PLUGIN MANAGEMENT COMMANDS

# Create a new plugin from template
[no-cd]
make-plugin PLUGIN_NAME:
    @echo "🆕 Creating new plugin: {{PLUGIN_NAME}}"
    @{{justfile_directory()}}/scripts/run.sh make_plugin.nu {{PLUGIN_NAME}}

# Install specific plugin locally (build + register)
[no-cd]
install-plugin PLUGIN:
    @{{justfile_directory()}}/scripts/run.sh install_plugin.nu {{PLUGIN}} --verify

# Register specific plugin with nushell
[no-cd]
register-plugin PLUGIN:
    @{{justfile_directory()}}/scripts/run.sh register_plugins.nu register ./{{PLUGIN}}/target/release/{{PLUGIN}} --verify

# Register all built plugins with nushell
[no-cd]
register-all-plugins:
    @{{justfile_directory()}}/scripts/run.sh register_plugins.nu register-all --verify

# Verify plugin registration status
[no-cd]
verify-plugins:
    @{{justfile_directory()}}/scripts/run.sh register_plugins.nu verify

# Install plugins locally from distribution
[no-cd]
install-local:
    #!/usr/bin/env bash
    if [ ! -d "distribution" ]; then
        echo "❌ Distribution directory not found"
        echo "💡 Run 'just collect' first to create distribution"
        exit 1
    fi


    # Detect current platform distribution
    PLATFORM_DIR=""
    if [ -d "distribution/darwin-arm64" ]; then
        PLATFORM_DIR="distribution/darwin-arm64"
    elif [ -d "distribution/aarch64-apple-darwin" ]; then
        PLATFORM_DIR="distribution/aarch64-apple-darwin"
    else
        # Find any platform directory
        PLATFORM_DIR=$(find distribution -maxdepth 1 -type d -name "*-*" | head -n1)
    fi

    if [ -z "$PLATFORM_DIR" ] || [ ! -f "$PLATFORM_DIR/install.nu" ]; then
        echo "❌ Installation script not found in distribution"
        echo "💡 Run 'just collect' to regenerate distribution"
        exit 1
    fi

    echo "📦 Installing plugins locally from distribution..."
    echo "💡 Using register-only mode (no sudo required)"
    echo "💡 Using distribution: $PLATFORM_DIR"
    cd "$PLATFORM_DIR" && nu install.nu --verify

    echo ""
    echo "✅ Local installation completed!"
    echo "💡 Plugins are now registered with nushell from current location"
    echo "   Run 'plugin list' in nushell to see installed plugins"

# Install plugins to ~/.local/bin from distribution (no sudo required)
[no-cd]
install-system:
    #!/usr/bin/env bash
    if [ ! -d "distribution" ]; then
        echo "❌ Distribution directory not found"
        echo "💡 Run 'just collect' first to create distribution"
        exit 1
    fi

    # Detect current platform distribution
    PLATFORM_DIR=""
    if [ -d "distribution/darwin-arm64" ]; then
        PLATFORM_DIR="distribution/darwin-arm64"
    elif [ -d "distribution/aarch64-apple-darwin" ]; then
        PLATFORM_DIR="distribution/aarch64-apple-darwin"
    else
        # Find any platform directory
        PLATFORM_DIR=$(find distribution -maxdepth 1 -type d -name "*-*" | head -n1)
    fi

    if [ -z "$PLATFORM_DIR" ] || [ ! -f "$PLATFORM_DIR/install.nu" ]; then
        echo "❌ Installation script not found in distribution"
        echo "💡 Run 'just collect' to regenerate distribution"
        exit 1
    fi

    echo "📦 Installing plugins to system from distribution..."
    echo "💡 Using distribution: $PLATFORM_DIR"
    echo "⚠️  Note: Due to macOS security restrictions, using alternative approach"
    echo "💡 This will install to ~/.local/bin and update PATH"

    # Create user bin directory
    mkdir -p ~/.local/bin

    # Copy nushell binary to user location (safer than system)
    echo "  Installing nushell binary to ~/.local/bin..."
    cp "$PLATFORM_DIR/nu" ~/.local/bin/nu
    chmod +x ~/.local/bin/nu

    # Copy all plugin binaries to user location
    echo "  Installing plugin binaries to ~/.local/bin..."
    cp "$PLATFORM_DIR"/nu_plugin_* ~/.local/bin/
    chmod +x ~/.local/bin/nu_plugin_*

    # Verify nushell installation
    echo "  Verifying nushell installation..."
    ~/.local/bin/nu --version

    # Register plugins with system nushell (with timeout and error handling)
    echo "  Registering plugins..."
    echo "  💡 Waiting a moment for nushell to settle..."
    sleep 2

    for plugin in "$PLATFORM_DIR"/nu_plugin_*; do
        plugin_name=$(basename "$plugin")
        echo "    Registering $plugin_name..."

        # Use timeout to prevent hanging processes, capture both stdout and stderr
        if timeout 15 ~/.local/bin/nu -c "plugin add ~/.local/bin/$plugin_name" >/dev/null 2>&1; then
            echo "    ✅ $plugin_name registered successfully"
        else
            echo "    ⚠️  Failed to register $plugin_name (timeout or error)"
            # Try to continue with other plugins
        fi
        sleep 1  # Small delay between registrations
    done

    # Verify installation
    echo "  Verifying installation..."
    ~/.local/bin/nu -c "plugin list" | head -20

    # Update PATH suggestion
    echo ""
    echo "✅ System installation completed!"
    echo "💡 Plugins are installed in ~/.local/bin and registered with nushell"
    echo "💡 To use system-wide, add ~/.local/bin to your PATH:"
    echo "   echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.zshrc"
    echo "   source ~/.zshrc"
    echo "   Run 'plugin list' in nushell to see installed plugins"

# Remove plugin from workspace
[no-cd]
remove-plugin PLUGIN:
    @echo "🗑️ Removing plugin {{PLUGIN}}..."
    @if [ -d "{{PLUGIN}}" ]; then \
        echo "Are you sure you want to remove {{PLUGIN}}? (y/N)"; \
        read -r confirm; \
        if [ "$$confirm" = "y" ] || [ "$$confirm" = "Y" ]; then \
            rm -rf "{{PLUGIN}}"; \
            echo "✅ Removed {{PLUGIN}}"; \
        else \
            echo "❌ Cancelled"; \
        fi; \
    else \
        echo "Plugin {{PLUGIN}} not found"; \
    fi

# List all plugins
[no-cd]
list-plugins:
    @echo "📋 Available plugins:"
    @for plugin in nu_plugin_*; do \
        if [ -d "$$plugin" ]; then \
            echo "  - $$plugin"; \
        fi; \
    done

# Show plugin information
[no-cd]
plugin-info PLUGIN:
    @echo "ℹ️ Plugin Information: {{PLUGIN}}"
    @if [ -d "{{PLUGIN}}" ]; then \
        echo "Name: {{PLUGIN}}"; \
        echo "Path: $(pwd)/{{PLUGIN}}"; \
        if [ -f "{{PLUGIN}}/Cargo.toml" ]; then \
            echo "Version: $(grep '^version' {{PLUGIN}}/Cargo.toml | cut -d'"' -f2)"; \
            echo "Description: $(grep '^description' {{PLUGIN}}/Cargo.toml | cut -d'"' -f2 || echo 'Not available')"; \
        fi; \
        echo "Binary exists: $([ -f {{PLUGIN}}/target/release/{{PLUGIN}} ] && echo 'Yes' || echo 'No')"; \
        echo "Last modified: $(stat -c %y {{PLUGIN}} 2>/dev/null || stat -f %m {{PLUGIN}} 2>/dev/null || echo 'Unknown')"; \
    else \
        echo "Plugin {{PLUGIN}} not found"; \
    fi

# 🛠️ DEVELOPMENT TOOLS

# Run command on specific plugin
plugin PLUGIN CMD:
    @echo "🔧 Running '{{CMD}}' on {{PLUGIN}}"
    @cd {{PLUGIN}} && {{CMD}}

# Check specific plugin
[no-cd]
check-plugin PLUGIN:
    @echo "🔍 Checking {{PLUGIN}}..."
    @cd {{PLUGIN}} && cargo check

# Watch for changes and rebuild (requires entr)
[no-cd]
watch PLUGIN:
    #!/usr/bin/env bash
    if command -v entr >/dev/null 2>&1; then
        echo "👀 Watching {{PLUGIN}} for changes..."
        find {{PLUGIN}}/src -name "*.rs" | entr just build-plugin {{PLUGIN}}
    else
        echo "❌ entr not installed. Install with: brew install entr (macOS) or apt install entr (Ubuntu)"
    fi

# Interactive plugin selection (requires fzf)
[no-cd]
interactive:
    #!/usr/bin/env bash
    if command -v fzf >/dev/null 2>&1; then
        echo "🎯 Interactive Plugin Selection"
        PLUGIN=$(ls -d nu_plugin_* | fzf --prompt="Select plugin: ")
        if [ -n "$PLUGIN" ]; then
            ACTION=$(echo -e "build\ntest\ncheck\nlint\nupstream-check\nupstream-merge\ninstall" | fzf --prompt="Select action: ")
            if [ -n "$ACTION" ]; then
                case $ACTION in
                    "upstream-check") just upstream-check-plugin $PLUGIN ;;
                    "upstream-merge") just upstream-merge $PLUGIN ;;
                    "build") just build-plugin $PLUGIN ;;
                    "test") just test-plugin $PLUGIN ;;
                    "check") just check-plugin $PLUGIN ;;
                    "lint") cd $PLUGIN && cargo clippy ;;
                    "install") just install-plugin $PLUGIN ;;
                esac
            fi
        fi
    else
        echo "❌ fzf not installed. Install with: brew install fzf (macOS) or apt install fzf (Ubuntu)"
    fi

# 📊 SYSTEM INFORMATION

# Show environment configuration
[no-cd]
env-info:
    @echo "🌍 Environment Configuration:"
    @if [ -f env ]; then \
        cat env; \
    else \
        echo "No env file found"; \
    fi

# Show system information
[no-cd]
system-info:
    #!/usr/bin/env bash
    echo "💻 System Information:"
    echo "OS: $(uname -s)"
    echo "Architecture: $(uname -m)"
    echo "Nushell: $(nu --version 2>/dev/null || echo 'Not installed')"
    echo "Rust: $(rustc --version 2>/dev/null || echo 'Not installed')"
    echo "Cargo: $(cargo --version 2>/dev/null || echo 'Not installed')"
    echo "Just: $(just --version 2>/dev/null || echo 'Not installed')"
    echo "Docker: $(docker --version 2>/dev/null || echo 'Not installed')"
    echo "Git: $(git --version 2>/dev/null || echo 'Not installed')"

# Validate setup and dependencies
[no-cd]
validate:
    @echo "✅ Validating setup..."
    @echo "Checking required tools:"
    @command -v nu >/dev/null 2>&1 && echo "✅ nushell" || echo "❌ nushell (required)"
    @command -v cargo >/dev/null 2>&1 && echo "✅ cargo" || echo "❌ cargo (required)"
    @command -v git >/dev/null 2>&1 && echo "✅ git" || echo "❌ git (required)"
    @command -v just >/dev/null 2>&1 && echo "✅ just" || echo "❌ just (optional but recommended)"
    @command -v docker >/dev/null 2>&1 && echo "✅ docker" || echo "⚠️ docker (optional for cross-compilation)"
    @echo ""
    @echo "Checking directory structure:"
    @[ -d scripts ] && echo "✅ scripts directory" || echo "❌ scripts directory"
    @[ -d etc ] && echo "✅ etc directory" || echo "❌ etc directory"
    @[ -f etc/plugin_registry.toml ] && echo "✅ plugin registry" || echo "❌ plugin registry"
    @[ -f etc/upstream_exclude.toml ] && echo "✅ upstream exclusions" || echo "⚠️ upstream exclusions (optional)"
    @[ -f env ] && echo "✅ env file" || echo "⚠️ env file (optional)"
    @echo ""
    @echo "Plugin directories:"
    @ls -d nu_plugin_* 2>/dev/null | wc -l | xargs echo "📦 Found plugins:"

# 🧹 CLEANUP COMMANDS

# Clean all build artifacts
[no-cd]
clean:
    #!/usr/bin/env bash
    echo "🧹 Cleaning build artifacts..."

    # Clean plugin target directories
    for plugin in nu_plugin_*; do
        if [ -d "$plugin/target" ]; then
            echo "Removing $plugin/target..."
            rm -rf "$plugin/target"
        fi
    done

    # Clean API plugin target directories
    for plugin in api_nu_plugin_*; do
        if [ -d "$plugin/target" ]; then
            echo "Removing $plugin/target..."
            rm -rf "$plugin/target"
        fi
    done

    # Clean wrks subdirectory targets
    if [ -d "wrks" ]; then
        for plugin in wrks/nu_plugin_*; do
            if [ -d "$plugin/target" ]; then
                echo "Removing $plugin/target..."
                rm -rf "$plugin/target"
            fi
        done
    fi

    # Also clean nushell submodule if it exists (use cargo clean for complex projects)
    if [ -d "nushell" ]; then
        echo "Cleaning nushell submodule..."
        cd nushell && cargo clean && cd ..
    fi

# Clean specific plugin
[no-cd]
clean-plugin PLUGIN:
    @echo "🧹 Cleaning {{PLUGIN}}..."
    @if [ -d "{{PLUGIN}}/target" ]; then \
        echo "Removing {{PLUGIN}}/target..."; \
        rm -rf "{{PLUGIN}}/target"; \
    else \
        echo "No target directory found for {{PLUGIN}}"; \
    fi

# Clean distribution files
[no-cd]
clean-dist:
    @echo "🧹 Cleaning distribution files..."
    @rm -rf distribution
    @echo "✅ Cleaned distribution directory"

# Clean all caches
[no-cd]
clean-all:
    @echo "🧹 Cleaning everything..."
    @just clean
    @just clean-dist
    @echo "✅ All clean!"

# 🔄 MAINTENANCE COMMANDS

# Update all dependencies (careful!)
[no-cd]
update-deps:
    @echo "⬆️ Updating dependencies (this may break things)..."
    @for plugin in nu_plugin_*; do \
        if [ -d "$$plugin" ]; then \
            echo "Updating deps in $$plugin..."; \
            cd "$$plugin" && cargo update && cd ..; \
        fi; \
    done

# Fix common issues automatically
[no-cd]
auto-fix:
    @echo "🔧 Running automatic fixes..."
    @just fix-nushell
    @just fmt
    @just lint-fix
    @echo "✅ Automatic fixes completed"

# Generate project statistics
[no-cd]
stats:
    @echo "📊 Project Statistics:"
    @echo "===================="
    @echo "Plugins: $(ls -d nu_plugin_* 2>/dev/null | wc -l)"
    @echo "Rust files: $(find nu_plugin_*/src -name "*.rs" 2>/dev/null | wc -l)"
    @echo "Lines of code: $(find nu_plugin_*/src -name "*.rs" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo '0')"
    @echo "Test files: $(find nu_plugin_* -name "*test*.rs" -o -name "tests" -type d 2>/dev/null | wc -l)"
    @echo "Documentation files: $(find . -name "*.md" 2>/dev/null | wc -l)"

# 🔧 CONFIGURATION MANAGEMENT

# Show configuration files
[no-cd]
config-list:
    @echo "📁 Configuration Files:"
    @echo "======================"
    @echo "Main configuration:"
    @[ -f etc/plugin_registry.toml ] && echo "✅ etc/plugin_registry.toml" || echo "❌ etc/plugin_registry.toml"
    @[ -f etc/build_targets.toml ] && echo "✅ etc/build_targets.toml" || echo "❌ etc/build_targets.toml"
    @[ -f etc/upstream_exclude.toml ] && echo "✅ etc/upstream_exclude.toml" || echo "⚠️ etc/upstream_exclude.toml"
    @echo ""
    @echo "Environment:"
    @[ -f env ] && echo "✅ env" || echo "⚠️ env (optional)"
    @echo ""
    @echo "Build configuration:"
    @[ -f justfile ] && echo "✅ justfile" || echo "❌ justfile"
    @[ -f Dockerfile.cross ] && echo "✅ Dockerfile.cross" || echo "❌ Dockerfile.cross"

# Edit configuration file
[no-cd]
config-edit FILE:
    @echo "✏️ Editing configuration: {{FILE}}"
    @${EDITOR:-nano} {{FILE}}

# Backup configuration
[no-cd]
config-backup:
    @echo "💾 Backing up configuration..."
    @mkdir -p backups/config-$(date +%Y%m%d-%H%M%S)
    @cp etc/*.toml backups/config-$(date +%Y%m%d-%H%M%S)/ 2>/dev/null || true
    @[ -f env ] && cp env backups/config-$(date +%Y%m%d-%H%M%S)/ || true
    @echo "✅ Configuration backed up to backups/config-$(date +%Y%m%d-%H%M%S)/"

# 📊 TOOLS INFORMATION

# Show tools help
[no-cd]
tools-help:
    @echo "🛠️ Tools Module Help"
    @echo "===================="
    @echo ""
    @echo "VERSION & VALIDATION:"
    @echo "  validate-nushell         - Check nushell version consistency"
    @echo "  fix-nushell             - Fix version mismatches"
    @echo "  update-nu-versions       - Update nu dependency versions"
    @echo "  list-nu-versions         - List current versions"
    @echo "  update-nushell           - Update nushell submodule"
    @echo ""
    @echo "PLUGIN MANAGEMENT:"
    @echo "  make-plugin NAME         - Create new plugin from template"
    @echo "  install-plugin PLUGIN    - Build and register plugin (alias: i)"
    @echo "  register-plugin PLUGIN   - Register plugin with nushell"
    @echo "  register-all-plugins     - Register all built plugins with nushell"
    @echo "  verify-plugins           - Verify plugin registration status"
    @echo "  install-local            - Install plugins from distribution locally (no sudo)"
    @echo "  install-system           - Install plugins to ~/.local/bin (no sudo)"
    @echo "  remove-plugin PLUGIN     - Remove plugin from workspace"
    @echo "  list-plugins             - List all plugins"
    @echo "  plugin-info PLUGIN       - Show plugin information"
    @echo ""
    @echo "DEVELOPMENT TOOLS:"
    @echo "  plugin PLUGIN CMD        - Run command on plugin"
    @echo "  check-plugin PLUGIN      - Check specific plugin"
    @echo "  watch PLUGIN             - Watch for changes (requires entr)"
    @echo "  interactive              - Interactive plugin selection (requires fzf)"
    @echo ""
    @echo "SYSTEM INFORMATION:"
    @echo "  env-info                 - Show environment configuration"
    @echo "  system-info              - Show system information"
    @echo "  validate                 - Validate setup and dependencies"
    @echo ""
    @echo "CLEANUP:"
    @echo "  clean                    - Clean all build artifacts"
    @echo "  clean-plugin PLUGIN      - Clean specific plugin"
    @echo "  clean-dist               - Clean distribution files"
    @echo "  clean-all                - Clean everything"
    @echo ""
    @echo "MAINTENANCE:"
    @echo "  update-deps              - Update all dependencies"
    @echo "  auto-fix                 - Run automatic fixes"
    @echo "  stats                    - Generate project statistics"
    @echo ""
    @echo "CONFIGURATION:"
    @echo "  config-list              - Show configuration files"
    @echo "  config-edit FILE         - Edit configuration file"
    @echo "  config-backup            - Backup configuration"
    @echo ""
    @echo "EXAMPLES:"
    @echo "  just make-plugin nu_plugin_myfeature"
    @echo "  just watch nu_plugin_clipboard"
    @echo "  just interactive"
    @echo "  just plugin nu_plugin_image 'cargo bench'"
