#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
CACHE_DIR="$SKILL_DIR/cache"

usage() {
  cat <<'EOF'
Usage: search-docs.sh <query> [--kind all|sql|function|operator] [--limit <n>] [--version <x.y.z>]

Search cached MatrixOne documentation indexes. Requires fetch-index.sh to have
been run first for the requested version.

Environment:
  MO_DOCS_VERSION    Doc version (default: 3.0.13), overridden by --version.
EOF
  exit 0
}

QUERY=""
KIND="all"
LIMIT=8
VERSION="${MO_DOCS_VERSION:-3.0.13}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --kind)   KIND="$2"; shift 2 ;;
    --limit)  LIMIT="$2"; shift 2 ;;
    --version) VERSION="$2"; shift 2 ;;
    -h|--help) usage ;;
    *) QUERY="$1"; shift ;;
  esac
done

if [[ -z "$QUERY" ]]; then
  echo "Error: query is required" >&2
  usage
fi

if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Error: invalid version '$VERSION'" >&2
  exit 1
fi

case "$KIND" in
  all|sql|function|operator) ;;
  *) echo "Error: kind must be one of all, sql, function, operator" >&2; exit 1 ;;
esac

INDEX_DIR="$CACHE_DIR/v${VERSION}"
KIND_MAP='sql:llms-sql.txt function:llms-func.txt operator:llms-op.txt'

FILES_TO_SEARCH=()
if [[ "$KIND" == "all" ]]; then
  FILES_TO_SEARCH=("$INDEX_DIR/llms-sql.txt" "$INDEX_DIR/llms-func.txt" "$INDEX_DIR/llms-op.txt")
else
  KIND_KEY="$KIND"
  case "$KIND" in
    sql)      FILENAME="llms-sql.txt" ;;
    function) FILENAME="llms-func.txt" ;;
    operator) FILENAME="llms-op.txt" ;;
  esac
  FILES_TO_SEARCH=("$INDEX_DIR/$FILENAME")
fi

for f in "${FILES_TO_SEARCH[@]}"; do
  if [[ ! -f "$f" ]]; then
    echo "Error: index file not found: $f" >&2
    echo "Run: bash skills/matrixone-docs/scripts/fetch-index.sh --version $VERSION" >&2
    exit 1
  fi
done

# Parse index lines format:
# - [Title](URL) [compatibility]: optional summary
# Match against lowercase query in title, summary, compatibility.
QUERY_LC=$(echo "$QUERY" | tr '[:upper:]' '[:lower:]')
COUNT=0

search_file() {
  local file="$1"
  local tag="$2"
  while IFS= read -r line; do
    [[ $COUNT -ge $LIMIT ]] && return
    # Only process lines starting with "- [title](url) [compat]"
    [[ "$line" == "- ["* ]] || continue

    # Extract title: everything between "- [" and "]("
    local title
    title=$(echo "$line" | sed -n 's/^- \[\(.*\)\](\(.*\)) \[\(.*\)\].*$/\1/p')
    [[ -n "$title" ]] || continue

    # Extract url: between "](" and ")"
    local url
    url=$(echo "$line" | sed -n 's/^- \[.*\](\(.*\)) \[.*\].*$/\1/p')
    [[ -n "$url" ]] || continue

    # Extract compatibility: between "] [" and "]"
    local compat
    compat=$(echo "$line" | sed -n 's/^- \[.*\](.*) \[\(.*\)\].*$/\1/p')

    # Extract optional summary: after the compat bracket
    local summary
    summary=$(echo "$line" | sed -n 's/^- \[.*\](.*) \[.*\]: \(.*\)$/\1/p')

    local haystack
    haystack=$(echo "$title $compat $summary" | tr '[:upper:]' '[:lower:]')
    if [[ "$haystack" != *"$QUERY_LC"* ]]; then
      continue
    fi

    # Extract doc_path from URL: strip https://docs.matrixorigin.cn/en/v26.x.y.z/
    local prefix="https://docs.matrixorigin.cn/en/v26.${VERSION}/"
    local doc_path="${url#$prefix}"

    echo "---"
    echo "title:       $title"
    echo "kind:        $tag"
    echo "compatibility: $compat"
    [[ -n "$summary" ]] && echo "summary:     $summary"
    echo "url:         $url"
    echo "doc_path:    $doc_path"
    COUNT=$((COUNT + 1))
  done < "$file"
}

if [[ "$KIND" == "all" ]]; then
  search_file "${FILES_TO_SEARCH[0]}" "sql"
  search_file "${FILES_TO_SEARCH[1]}" "function"
  search_file "${FILES_TO_SEARCH[2]}" "operator"
else
  search_file "${FILES_TO_SEARCH[0]}" "$KIND"
fi

if [[ $COUNT -eq 0 ]]; then
  echo "No results found for '$QUERY' (kind=$KIND, version=$VERSION)" >&2
  exit 1
fi
