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

PROFILE_DIR=/home/teleo/.hermes/profiles/leoclean
KB_TOOL="$PROFILE_DIR/bin/kb_tool.py"
CLOUDSQL_TOOL="$PROFILE_DIR/bin/cloudsql_memory_tool.py"
MODE=${TELEO_KB_MODE:-auto}
COMMAND=${1:-}
CLOUDSQL_STATUS_TIMEOUT=${TELEO_CLOUDSQL_STATUS_TIMEOUT_SECONDS:-30}

cloudsql_supported() {
  case "$COMMAND" in
    status|search|context|show|evidence|edges|propose-core-change|propose-edge|list-proposals|show-proposal) return 0 ;;
    *) return 1 ;;
  esac
}

cloudsql_args() {
  if [ "${TELEO_MEMORY_INCLUDE_EXCERPTS:-}" = "1" ]; then
    case "$COMMAND" in
      search|context|show|evidence|edges) printf '%s\n' "--include-excerpts" ;;
    esac
  fi
}

run_cloudsql() {
  if cloudsql_supported; then
    extra_args=()
    while IFS= read -r arg; do
      [ -n "$arg" ] && extra_args+=("$arg")
    done < <(cloudsql_args)
    exec python3 "$CLOUDSQL_TOOL" "$@" "${extra_args[@]}"
  fi
  exec python3 "$KB_TOOL" "$@"
}

case "$MODE" in
  cloudsql)
    run_cloudsql "$@"
    ;;
  local)
    exec python3 "$KB_TOOL" --local "$@"
    ;;
  remote)
    exec python3 "$KB_TOOL" "$@"
    ;;
  auto)
    if [ -x "$CLOUDSQL_TOOL" ] && command -v psql >/dev/null 2>&1 && command -v gcloud >/dev/null 2>&1; then
      if cloudsql_supported; then
        if timeout "${CLOUDSQL_STATUS_TIMEOUT}s" python3 "$CLOUDSQL_TOOL" status --format json --redacted >/dev/null 2>&1; then
          run_cloudsql "$@"
        fi
      fi
    fi
    if command -v docker >/dev/null 2>&1; then
      exec python3 "$KB_TOOL" --local "$@"
    fi
    exec python3 "$KB_TOOL" "$@"
    ;;
  *)
    echo "Unsupported TELEO_KB_MODE=$MODE; expected auto, cloudsql, local, or remote" >&2
    exit 64
    ;;
esac
