#!/usr/bin/env bash
# albok-search — search the live Albok by hand, with the service address and token wired up.
#
#   scripts/albok-search <query...>                       hybrid search over every wing the token reads
#   scripts/albok-search --wing fleet/memory <query...>   one wing; --top-k N; --facet key=value; --json for the raw reply
#   scripts/albok-search read <object_id>                 the pristine bytes of a hit (any other albok verb passes through:
#                                                         sidecar, objects, facets, wings, buildings, status, health)
#
# Each hit prints score, wing, title, object id and the excerpt. Never threshold on the score: the null floor
# of hybrid search sits at ~0.031 and real hits at ~0.033; the ORDER carries the signal, the number does not.
# Environment (optional): ALBOK_SERVICE, ALBOK_TOKEN (else the token in NEMI_CONFIG, else the vault), NEMI_CONFIG.
set -u
ALBOK_SERVICE="${ALBOK_SERVICE:-http://albok.nh3.internal:8392}"
NEMI_CONFIG="${NEMI_CONFIG:-$HOME/.config/albok/nemi.yaml}"
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
albok() { if type -P albok >/dev/null 2>&1; then command albok "$@"; else uv --directory "$REPO" run -q albok "$@"; fi; }

[ $# -eq 0 ] && { sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }

TOKEN="${ALBOK_TOKEN:-}"
[ -z "$TOKEN" ] && [ -r "$NEMI_CONFIG" ] && TOKEN="$(python3 -c 'import sys,yaml;print(yaml.safe_load(open(sys.argv[1]))["service"]["token"])' "$NEMI_CONFIG" 2>/dev/null)"
[ -z "$TOKEN" ] && command -v secret >/dev/null 2>&1 && TOKEN="$(secret get albok/token-nemi 2>/dev/null)"
[ -z "$TOKEN" ] && { echo "albok-search: no token (set ALBOK_TOKEN, or point NEMI_CONFIG at nemi.yaml)" >&2; exit 2; }
export ALBOK_SERVICE ALBOK_TOKEN="$TOKEN"

case "$1" in
  read|sidecar|objects|facets|wings|buildings|status|health) albok "$@"; exit $? ;;
esac
# options go to `albok search`; every other word is part of the one query (no quoting needed)
OPTS=(); WORDS=(); RAW=0
while [ $# -gt 0 ]; do
  case "$1" in
    --wing|--top-k|--facet)
      [ $# -ge 2 ] || { echo "albok-search: $1 needs a value" >&2; exit 2; }
      OPTS+=("$1" "$2"); shift 2 ;;
    --wing=*|--top-k=*|--facet=*|--include-tombstoned) OPTS+=("$1"); shift ;;
    --json) RAW=1; shift ;;
    *) WORDS+=("$1"); shift ;;
  esac
done
[ ${#WORDS[@]} -eq 0 ] && { echo "albok-search: no query words" >&2; exit 2; }
QUERY="${WORDS[*]}"
if [ $RAW -eq 1 ]; then albok search --json ${OPTS[@]+"${OPTS[@]}"} "$QUERY"; exit $?; fi

OUT="$(albok search --json ${OPTS[@]+"${OPTS[@]}"} "$QUERY")" || { printf '%s\n' "$OUT" >&2; exit 1; }
python3 - "$OUT" <<'PY'
import json, sys, textwrap
r = json.loads(sys.argv[1]).get("results") or []
if not r:
    print("no hits (an empty answer, not an outage: the service replied)"); sys.exit(0)
for i, h in enumerate(r, 1):
    also = h.get("also_in") or []
    print(f"{i:>2}. {h.get('score', 0):.3f}  {h.get('wing')}  {h.get('title') or ''}")
    print(f"    object {h.get('object_id')}" + (f"   also in {len(also)} linked object(s)" if also else ""))
    ex = " ".join((h.get("excerpt") or "").split())
    for line in textwrap.wrap(ex, 110)[:4]: print(f"    {line}")
    print()
print(f"{len(r)} hits.  Read one: scripts/albok-search read <object id>   sidecar: scripts/albok-search sidecar <object id>")
PY
