#!/usr/bin/env bash
# kb — search the operator's personal Worldtree knowledge base.
#
# The KB is a ~7,600-file markdown tree inside a Docker volume on corviduo-dev.
# It is NOT reachable through the Worldtree HTTP API: `/search` there searches
# conversation MESSAGES, not notes, and returns a clean empty result for a note
# that plainly exists — a false negative with no error attached. (2026-09-14: a
# search for "shrimp" returned 0 hits; so did "the" and "a", which is the only
# reason the empty result was recognised as an empty ACCOUNT rather than an
# empty KB.) So this reads the files directly. Deterministic, ~0.9s, no tokens.
#
# Usage:
#   kb <query>              search titles, keywords and body; notes first
#   kb -c <query>           also show the matching body lines
#   kb -n <N> <query>       cap results per group (default 12)
#   kb --notes <query>      personal notes only (skip the ingested library)
#   kb --library <query>    ingested books/fiction/papers only
#   kb cat <path>           print a note (path as printed by a search)
#   kb ls [subdir]          list the tree
#
# Env: KB_HOST (default corviduo-dev), KB_ROOT (default the volume mountpoint).
set -euo pipefail

KB_HOST="${KB_HOST:-corviduo-dev}"
KB_USER="${KB_USER:-infra-ops}"
KB_ROOT="${KB_ROOT:-/var/lib/docker/volumes/worldtree-personal_worldtree-kb/_data}"
# readlink -f, not dirname of $0: this is installed on PATH as a SYMLINK
# (~/.local/bin/kb -> scripts/kb, same shape as `booth`), and resolving the
# LINK's directory looks for the payload in ~/.local/bin where it is not.
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
PAYLOAD="${SELF%/*}/kb-search.py"

[ $# -gt 0 ] || { sed -n '2,20p' "$SELF" | sed 's/^# \{0,1\}//'; exit 0; }
[ -f "$PAYLOAD" ] || { echo "kb: missing payload $PAYLOAD" >&2; exit 1; }

# One round trip: the payload runs remotely under sudo (the volume is root-owned)
# and does all the ranking there, so a search is one ssh handshake, not N.
exec ssh -o BatchMode=yes -o ConnectTimeout=10 "${KB_USER}@${KB_HOST}" \
     "sudo -n python3 - $(printf '%q ' "$KB_ROOT" "$@")" < "$PAYLOAD"
