#!/bin/bash
# KB Search — search across raw/ and wiki/ with context
# Usage: ./scripts/search.sh "query" [--wiki-only|--raw-only] [--regex] [--recent N]

set -euo pipefail

KB_DIR="$(cd "$(dirname "$0")/.." && pwd)"

if ! command -v rg &>/dev/null; then
    echo "❌ ripgrep (rg) is required. Install: apt install ripgrep / brew install ripgrep" >&2
    exit 1
fi

if [ $# -lt 1 ]; then
    echo "Usage: ./scripts/search.sh <query> [options]" >&2
    echo "" >&2
    echo "Options:" >&2
    echo "  --wiki-only    Search only wiki/ pages" >&2
    echo "  --raw-only     Search only raw/ files" >&2
    echo "  --regex        Treat query as regex (default: fixed string)" >&2
    echo "  --files-only   Show only matching file paths (no line context)" >&2
    echo "" >&2
    echo "Examples:" >&2
    echo "  ./scripts/search.sh NVIDIA" >&2
    echo "  ./scripts/search.sh 'k3s cluster' --wiki-only" >&2
    exit 1
fi

QUERY="$1"
shift

WIKI_ONLY=false
RAW_ONLY=false
USE_REGEX=false
FILES_ONLY=false

while [ $# -gt 0 ]; do
    case $1 in
        --wiki-only) WIKI_ONLY=true ;;
        --raw-only) RAW_ONLY=true ;;
        --regex) USE_REGEX=true ;;
        --files-only) FILES_ONLY=true ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1 ;;
    esac
    shift
done

if $WIKI_ONLY && $RAW_ONLY; then
    echo "Error: cannot use both --wiki-only and --raw-only" >&2
    exit 1
fi

cd "$KB_DIR"

# Build rg args
RG_ARGS=(-n --color=always --glob '*.md')
if $USE_REGEX; then
    RG_ARGS+=(-e "$QUERY")
else
    RG_ARGS+=(-F -e "$QUERY")
fi
if $FILES_ONLY; then
    RG_ARGS+=(-l)
fi

search() {
    local label="$1"
    local dir="$2"
    local prefix="$3"
    
    echo ""
    echo "--- $label ---"
    rg "${RG_ARGS[@]}" "$dir" 2>/dev/null | while IFS= read -r line; do
        echo "${prefix} ${line}"
    done || true
}

if $WIKI_ONLY; then
    search "Wiki Pages" "wiki/" "📘"
elif $RAW_ONLY; then
    search "Raw Files" "raw/" "📥"
else
    echo "🔍 Searching KB for: $QUERY"
    echo "================================"
    search "Wiki Pages" "wiki/" "📘"
    search "Raw Files" "raw/" "📥"
fi
