#!/usr/bin/env bash
# v1.0 (2026-07-11): A1100 Frente 2 (indice semantico). Wrapper del venv machine-local del indice.
# Resuelve el python del venv (~/.betyy-cache/indice-venv) y despacha a ingesta/buscar/config.
# Falla ruidoso si el venv no existe (apunta al setup); el indice es derivado/desechable.
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CACHE="${BETYY_CACHE_DIR:-$HOME/.betyy-cache}"
VENV="${BETYY_INDICE_VENV:-$CACHE/indice-venv}"
PY="$VENV/bin/python"

if [ ! -x "$PY" ]; then
  echo "ERROR: venv del indice ausente en $VENV" >&2
  echo "  corre primero: bash $DIR/setup.sh" >&2
  exit 2
fi

cmd="${1:-}"
shift || true
case "$cmd" in
  build|reindex|stats)
    exec "$PY" "$DIR/ingesta.py" "$cmd" "$@" ;;
  buscar|query|search)
    exec "$PY" "$DIR/buscar.py" "$@" ;;
  config|diag)
    exec "$PY" "$DIR/config.py" "$@" ;;
  frescura)
    exec "$PY" -c "import sys; sys.path.insert(0,'$DIR'); import frescura; print(frescura.sello_legible())" ;;
  ""|-h|--help|help)
    cat <<EOF
betyy-indice: indice semantico de descubrimiento (read-only, local, desechable).
  betyy-indice build [--full] [--source memorias|normas|handoffs]   construye/reindexa
  betyy-indice reindex                                              reindex incremental (por hash)
  betyy-indice stats                                                estado del indice + frescura
  betyy-indice buscar "consulta" [-k N] [--umbral F] [--humano|--json]   consulta punteros
  betyy-indice config                                              diagnostico de paths/fuentes
  betyy-indice frescura                                            sello de frescura
EOF
    ;;
  *)
    echo "comando desconocido: $cmd (usa 'betyy-indice help')" >&2
    exit 2 ;;
esac
