#!/bin/bash

# REMnux Tool Finder - Fuzzy search through all available tools
# Usage: find-tool [search_term]

TOOLS_DB="/opt/remnux-docs/tools.db"
DOCS_DIR="/opt/remnux-docs"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

show_help() {
    echo -e "${CYAN}🔍 REMnux Tool Finder${NC}"
    echo ""
    echo "Usage:"
    echo "  find-tool [search_term]    - Search for tools"
    echo "  find-tool --list          - List all available tools"
    echo "  find-tool --categories     - Show tool categories"
    echo "  find-tool --interactive    - Interactive fuzzy search (requires fzf)"
    echo ""
    echo "Examples:"
    echo "  find-tool pdf              - Find all PDF-related tools"
    echo "  find-tool javascript       - Find JavaScript analysis tools"
    echo "  find-tool parser           - Find all parsers"
    echo "  find-tool --interactive    - Browse all tools interactively"
}

list_categories() {
    echo -e "${CYAN}📂 Available Tool Categories:${NC}"
    if [[ -f "$TOOLS_DB" ]]; then
        awk -F'|' '/^[^#]/ {print $3}' "$TOOLS_DB" | sort -u | while read -r category; do
            count=$(awk -F'|' -v cat="$category" '/^[^#]/ && $3 == cat {count++} END {print count+0}' "$TOOLS_DB")
            echo -e "  ${GREEN}•${NC} $category (${YELLOW}$count tools${NC})"
        done
    else
        echo -e "${RED}❌ Tools database not found. Run container build to initialize.${NC}"
    fi
}

list_all_tools() {
    echo -e "${CYAN}🛠️  All Available Tools:${NC}"
    if [[ -f "$TOOLS_DB" ]]; then
        awk -F'|' '/^[^#]/ {printf "%-20s %s\n", $1, $2}' "$TOOLS_DB" | sort
    else
        echo -e "${RED}❌ Tools database not found.${NC}"
    fi
}

search_tools() {
    local search_term="$1"
    
    if [[ -z "$search_term" ]]; then
        echo -e "${RED}❌ Please provide a search term${NC}"
        show_help
        return 1
    fi

    if [[ ! -f "$TOOLS_DB" ]]; then
        echo -e "${RED}❌ Tools database not found.${NC}"
        return 1
    fi

    echo -e "${CYAN}🔍 Searching for: ${YELLOW}$search_term${NC}"
    echo ""

    # Search in tool names, descriptions, categories, and usage hints (5 fields now)
    local matches=$(awk -F'|' -v term="$search_term" '
        /^[^#]/ && (tolower($1) ~ tolower(term) || tolower($2) ~ tolower(term) || tolower($3) ~ tolower(term) || tolower($4) ~ tolower(term)) {
            print $0
        }' "$TOOLS_DB")

    if [[ -z "$matches" ]]; then
        echo -e "${YELLOW}⚠️  No tools found matching '$search_term'${NC}"
        echo ""
        echo -e "💡 Try broader terms like: ${GREEN}pdf${NC}, ${GREEN}malware${NC}, ${GREEN}javascript${NC}, ${GREEN}analysis${NC}"
        return 0
    fi

    local count=0
    echo "$matches" | while IFS='|' read -r name description category usage available; do
        count=$((count + 1))
        echo -e "${GREEN}🔧 $name${NC}"
        echo -e "   Description: $description"
        echo -e "   Category: $category"
        if [[ -n "$usage" && "$usage" != " " ]]; then
            echo -e "   Usage: $usage"
        fi
        
        # Use availability status from database instead of checking command
        if [[ "$available" == "✓" ]]; then
            echo -e "   ${GREEN}✓ Available${NC}"
        else
            echo -e "   ${YELLOW}⚠ Check path or alternative name${NC}"
        fi
        echo ""
    done

    local match_count=$(echo "$matches" | wc -l)
    echo -e "${CYAN}📊 Found $match_count tool(s) matching '$search_term'${NC}"
}

interactive_search() {
    if ! command -v fzf >/dev/null 2>&1; then
        echo -e "${YELLOW}⚠️  fzf not found. Falling back to simple search.${NC}"
        echo "Type search term and press Enter (or 'quit' to exit):"
        while read -r -p "🔍 Search: " term; do
            if [[ "$term" == "quit" || "$term" == "exit" ]]; then
                break
            fi
            search_tools "$term"
            echo "---"
        done
        return
    fi

    echo -e "${CYAN}🎯 Interactive Tool Search${NC}"
    echo -e "Use ${GREEN}↑/↓${NC} to navigate, ${GREEN}Enter${NC} to select, ${GREEN}Ctrl+C${NC} to exit"
    echo ""

    local selected=$(awk -F'|' '/^[^#]/ {printf "%-20s │ %-30s │ %s\n", $1, $2, $3}' "$TOOLS_DB" | \
                     fzf --header="REMnux Tools - Select to see details" \
                         --header-lines=0 \
                         --preview='echo {} | cut -d"│" -f1 | xargs -I{} awk -F"|" -v tool="{}" "BEGIN{IGNORECASE=1} \$1 ~ tool {print \"🔧 Tool: \" \$1; print \"📝 Description: \" \$2; print \"📂 Category: \" \$3; if(\$4) print \"💡 Usage: \" \$4}" /opt/remnux-docs/tools.db' \
                         --preview-window=right:50%:wrap)

    if [[ -n "$selected" ]]; then
        local tool_name=$(echo "$selected" | cut -d'│' -f1 | xargs)
        echo -e "${GREEN}Selected tool: $tool_name${NC}"
        
        # Show detailed info
        search_tools "$tool_name"
        
        # Try to show help for the tool
        echo -e "${CYAN}📖 Quick Help:${NC}"
        if command -v "$tool_name" >/dev/null 2>&1; then
            echo "Running: $tool_name --help"
            timeout 3s "$tool_name" --help 2>/dev/null | head -10 || echo "No help available or timeout"
        else
            echo "Tool may be available under a different name or path"
        fi
    fi
}

# Main logic
case "${1:-}" in
    --help|-h|help)
        show_help
        ;;
    --list|-l)
        list_all_tools
        ;;
    --categories|-c)
        list_categories
        ;;
    --interactive|-i)
        interactive_search
        ;;
    "")
        show_help
        ;;
    *)
        search_tools "$1"
        ;;
esac