#!/bin/bash
set -euo pipefail

PROFILE_DIR=${HERMES_HOME:-/home/teleo/.hermes/profiles/leoclean}
KB_TOOL="$PROFILE_DIR/bin/kb_tool.py"
SCRIPT_PATH=${BASH_SOURCE[0]}
SCRIPT_DIR=${SCRIPT_PATH%/*}
if [ "$SCRIPT_DIR" = "$SCRIPT_PATH" ]; then
  SCRIPT_DIR=.
fi
SCRIPT_DIR="$(cd "$SCRIPT_DIR" && pwd)"
CLOUDSQL_TOOL="$SCRIPT_DIR/cloudsql_memory_tool.py"
MODE=${TELEO_KB_MODE:-auto}
COMMAND=${1:-}

cloudsql_supported() {
  case "$COMMAND" in
    status|search|context|show|evidence|edges|propose-core-change|propose-edge|list-proposals|search-proposals|show-proposal|decision-matrix-status) 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
    echo "teleo-kb: command '$COMMAND' is not supported by the Cloud SQL backend" >&2
    exit 64
  fi
  if [ ! -x "$CLOUDSQL_TOOL" ]; then
    echo "teleo-kb: Cloud SQL tool is missing or not executable: $CLOUDSQL_TOOL" >&2
    exit 69
  fi
  if [ ! -x /usr/bin/python3 ]; then
    echo "teleo-kb: required Cloud SQL dependency is unavailable: /usr/bin/python3" >&2
    exit 69
  fi
  if ! command -v psql >/dev/null 2>&1; then
    echo "teleo-kb: required Cloud SQL dependency is unavailable: psql" >&2
    exit 69
  fi
  extra_args=()
  while IFS= read -r arg; do
    [ -n "$arg" ] && extra_args+=("$arg")
  done < <(cloudsql_args)
  if [ "${#extra_args[@]}" -gt 0 ]; then
    exec /usr/bin/python3 "$CLOUDSQL_TOOL" "$@" "${extra_args[@]}"
  fi
  exec /usr/bin/python3 "$CLOUDSQL_TOOL" "$@"
}

case "$MODE" in
  cloudsql)
    run_cloudsql "$@"
    ;;
  local)
    exec /usr/bin/python3 "$KB_TOOL" --local "$@"
    ;;
  remote)
    exec /usr/bin/python3 "$KB_TOOL" "$@"
    ;;
  auto)
    # Canonical commands must fail closed on Cloud SQL errors. Falling through
    # to a different local database would make source-of-truth behavior depend
    # on health-check latency or host package state.
    if cloudsql_supported; then
      run_cloudsql "$@"
    fi
    if command -v docker >/dev/null 2>&1; then
      exec /usr/bin/python3 "$KB_TOOL" --local "$@"
    fi
    exec /usr/bin/python3 "$KB_TOOL" "$@"
    ;;
  *)
    echo "Unsupported TELEO_KB_MODE=$MODE; expected auto, cloudsql, local, or remote" >&2
    exit 64
    ;;
esac
