#!/bin/bash

# Comprehensive Help System for File Analysis Container
# Integrates find-tool, navi, cheat, tldr for offline documentation

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

show_main_help() {
    echo -e "${CYAN}📚 File Analysis Container Help System${NC}"
    echo -e "${CYAN}======================================${NC}"
    echo ""
    echo -e "${GREEN}🔍 Tool Discovery:${NC}"
    echo "  help tools [term]          - Search for analysis tools"
    echo "  help tools --interactive   - Browse tools interactively" 
    echo "  help tools --list          - List all available tools"
    echo ""
    echo -e "${GREEN}📖 Command Examples:${NC}"
    echo "  help cheat <tool>          - Show cheat sheet for specific tool"
    echo "  help examples              - Browse all command examples interactively"
    echo "  help quick <command>       - Quick examples (tldr style)"
    echo ""
    echo -e "${GREEN}🎯 Analysis Workflows:${NC}"
    echo "  help pdf                   - PDF analysis workflow"
    echo "  help malware               - Malware analysis workflow"  
    echo "  help forensics             - System forensics workflow"
    echo ""
    echo -e "${GREEN}💡 Quick Access:${NC}"
    echo "  help --all                 - Show everything available"
    echo "  help --offline             - Verify offline capabilities"
    echo ""
    echo -e "${YELLOW}Examples:${NC}"
    echo "  help tools pdf             # Find PDF analysis tools"
    echo "  help cheat pdfid.py        # Show pdfid.py examples"
    echo "  help quick tar             # Quick tar examples"
    echo "  help examples              # Browse all examples"
}

search_tools() {
    echo -e "${CYAN}🔍 Searching analysis tools...${NC}"
    if [ "$1" = "--interactive" ]; then
        find-tool --interactive
    elif [ "$1" = "--list" ]; then
        find-tool --list
    elif [ -n "$1" ]; then
        find-tool "$1"
    else
        find-tool
    fi
}

show_cheat() {
    local tool="$1"
    if [ -z "$tool" ]; then
        echo -e "${YELLOW}Available cheat sheets:${NC}"
        echo "  pdf-analysis    - PDF analysis tools"
        echo "  malware         - Malware analysis tools"
        echo "  system          - System utilities"
        echo ""
        echo "Usage: help cheat <tool_name>"
        echo "Example: help cheat pdfid.py"
        return
    fi

    # First try cheat command for standard tools
    if command -v cheat >/dev/null 2>&1; then
        if cheat "$tool" 2>/dev/null; then
            return
        fi
    fi

    # Then try our custom categories
    case "$tool" in
        pdf*|PDF*)
            echo -e "${CYAN}📄 PDF Analysis Commands:${NC}"
            if [ -f "/opt/cheatsheets/pdf-analysis.cheat" ]; then
                grep -v "^#" /opt/cheatsheets/pdf-analysis.cheat | grep -v "^%" | grep -v "^\$" | grep -v "^$"
            fi
            ;;
        malware*|capa*|box-js*|oledump*)
            echo -e "${CYAN}🦠 Malware Analysis Commands:${NC}"
            if [ -f "/opt/cheatsheets/malware-analysis.cheat" ]; then
                grep -v "^#" /opt/cheatsheets/malware-analysis.cheat | grep -v "^%" | grep -v "^\$" | grep -v "^$"
            fi
            ;;
        system*|7z*|mc*|forensic*)
            echo -e "${CYAN}🛠️ System Utilities Commands:${NC}"
            if [ -f "/opt/cheatsheets/system-utilities.cheat" ]; then
                grep -v "^#" /opt/cheatsheets/system-utilities.cheat | grep -v "^%" | grep -v "^\$" | grep -v "^$"
            fi
            ;;
        *)
            echo -e "${YELLOW}⚠️ No specific cheat sheet found for '$tool'${NC}"
            echo ""
            echo -e "Try one of these:"
            echo -e "  ${GREEN}help cheat pdf${NC}      - PDF analysis"
            echo -e "  ${GREEN}help cheat malware${NC}  - Malware analysis"  
            echo -e "  ${GREEN}help cheat system${NC}   - System utilities"
            echo -e "  ${GREEN}help quick $tool${NC}    - Quick examples"
            ;;
    esac
}

show_examples() {
    if command -v navi >/dev/null 2>&1; then
        echo -e "${CYAN}🎯 Browsing command examples interactively...${NC}"
        echo -e "Use ${GREEN}Ctrl+R${NC} in shell or run ${GREEN}navi${NC} directly"
        navi --fzf
    else
        echo -e "${YELLOW}⚠️ Navi not available, showing static examples${NC}"
        show_cheat "pdf"
    fi
}

show_quick() {
    local command="$1"
    if [ -z "$command" ]; then
        echo -e "${YELLOW}Usage: help quick <command>${NC}"
        echo "Example: help quick tar"
        return
    fi

    if command -v tldr >/dev/null 2>&1; then
        echo -e "${CYAN}📖 Quick examples for: $command${NC}"
        tldr "$command" 2>/dev/null || {
            echo -e "${YELLOW}⚠️ No tldr page found for '$command'${NC}"
            echo "Try: help cheat $command"
        }
    else
        echo -e "${YELLOW}⚠️ tldr not available${NC}"
        show_cheat "$command"
    fi
}

show_workflow() {
    local workflow="$1"
    case "$workflow" in
        pdf)
            echo -e "${CYAN}📄 PDF Analysis Workflow:${NC}"
            echo ""
            echo -e "${GREEN}1. Initial Analysis:${NC}"
            echo "   pdfid.py sample.pdf              # Quick overview"
            echo "   file sample.pdf                  # Verify file type"
            echo ""
            echo -e "${GREEN}2. Deep Analysis:${NC}"  
            echo "   pdf-parser.py sample.pdf         # Structure analysis"
            echo "   peepdf -i sample.pdf             # Interactive analysis"
            echo ""
            echo -e "${GREEN}3. Extract Suspicious Content:${NC}"
            echo "   pdf-parser.py -o [obj_id] sample.pdf  # Extract objects"
            echo "   pdftk sample.pdf unpack_files    # Extract embedded files"
            echo ""
            echo -e "${GREEN}4. Safe Rendering:${NC}"
            echo "   pdftk sample.pdf cat output safe.pdf  # Flatten PDF"
            echo "   convert sample.pdf sample.png    # Convert to image"
            ;;
        malware)
            echo -e "${CYAN}🦠 Malware Analysis Workflow:${NC}"
            echo ""
            echo -e "${GREEN}1. File Identification:${NC}"
            echo "   file sample.exe                  # Identify file type"
            echo "   exiftool sample.exe              # Extract metadata"
            echo ""
            echo -e "${GREEN}2. Capability Analysis:${NC}"
            echo "   capa sample.exe                  # Detect capabilities"
            echo "   strings sample.exe | head -50   # Extract strings"
            echo ""
            echo -e "${GREEN}3. Document Analysis:${NC}"
            echo "   oledump.py sample.doc            # Office documents"
            echo "   box-js sample.js                # JavaScript analysis"
            echo ""
            echo -e "${GREEN}4. Data Analysis:${NC}"
            echo "   vd sample.csv                    # Interactive data exploration"
            echo "   unfurl_cli.py suspicious-url     # URL analysis"
            ;;
        forensics)
            echo -e "${CYAN}🔍 System Forensics Workflow:${NC}"
            echo ""
            echo -e "${GREEN}1. File System Analysis:${NC}"
            echo "   find /data -type f -mtime -1     # Recent files"
            echo "   ls -la /data                     # File permissions"
            echo ""
            echo -e "${GREEN}2. Content Analysis:${NC}"
            echo "   grep -r 'suspicious' /data/      # Text search"
            echo "   xxd suspicious_file | head       # Hex analysis"
            echo ""
            echo -e "${GREEN}3. Archive Analysis:${NC}"
            echo "   7z l archive.zip                 # List contents"
            echo "   7z x archive.zip -o./extract/    # Extract safely"
            echo ""
            echo -e "${GREEN}4. Verification:${NC}"
            echo "   md5sum * > checksums.md5         # Create checksums"
            echo "   md5sum -c checksums.md5          # Verify integrity"
            ;;
        *)
            echo -e "${YELLOW}Available workflows:${NC}"
            echo "  help pdf       - PDF analysis"
            echo "  help malware   - Malware analysis"
            echo "  help forensics - System forensics"
            ;;
    esac
}

show_all() {
    echo -e "${CYAN}📚 Complete Help Overview${NC}"
    echo -e "${CYAN}=========================${NC}"
    echo ""
    
    echo -e "${PURPLE}🛠️ Available Tools:${NC}"
    find-tool --categories
    echo ""
    
    echo -e "${PURPLE}📖 Help Commands:${NC}"
    echo "  help                    - This help"
    echo "  help tools [term]       - Search tools"
    echo "  help cheat <tool>       - Command examples"
    echo "  help quick <cmd>        - Quick examples"
    echo "  help examples           - Browse examples"
    echo "  navi --fzf             - Interactive cheat sheets"
    echo ""
    
    echo -e "${PURPLE}🎯 Analysis Workflows:${NC}"
    echo "  help pdf               - PDF analysis"
    echo "  help malware           - Malware analysis" 
    echo "  help forensics         - System forensics"
}

check_offline() {
    echo -e "${CYAN}🔌 Offline Capability Check${NC}"
    echo -e "${CYAN}===========================${NC}"
    echo ""
    
    local all_good=true
    
    echo -e "${GREEN}Documentation Tools:${NC}"
    for tool in find-tool navi cheat tldr; do
        if command -v "$tool" >/dev/null 2>&1; then
            echo -e "  ✅ $tool - available"
        else
            echo -e "  ❌ $tool - missing"
            all_good=false
        fi
    done
    
    echo ""
    echo -e "${GREEN}Documentation Files:${NC}"
    for file in "/opt/remnux-docs/tools.db" "/opt/cheatsheets/pdf-analysis.cheat" "/opt/cheatsheets/malware-analysis.cheat"; do
        if [ -f "$file" ]; then
            echo -e "  ✅ $file - available"
        else
            echo -e "  ❌ $file - missing"
            all_good=false
        fi
    done
    
    echo ""
    if $all_good; then
        echo -e "${GREEN}🎉 All offline help systems are working!${NC}"
    else
        echo -e "${YELLOW}⚠️ Some help systems are not available${NC}"
    fi
}

# Main command router
case "${1:-}" in
    tools)
        shift
        search_tools "$@"
        ;;
    cheat)
        shift
        show_cheat "$1"
        ;;
    examples)
        show_examples
        ;;
    quick)
        shift
        show_quick "$1"
        ;;
    pdf|malware|forensics)
        show_workflow "$1"
        ;;
    --all)
        show_all
        ;;
    --offline)
        check_offline
        ;;
    --help|-h|"")
        show_main_help
        ;;
    *)
        echo -e "${YELLOW}Unknown option: $1${NC}"
        echo ""
        show_main_help
        ;;
esac