#!/bin/bash
# Chimera MCP wrapper for Hermes.
# Durable wrapper rule (DF-CHIMERA-V2-1): resolve the repo root from this
# script's own location — never hardcode a path into another venv (the
# hermes-agent venv does not install chimera-deliberation; a hardcoded path
# there dies at exec and every real MCP client fails).
#
# Venv-agnostic resolution (QA-CHIMERA-V2-12): the fresh-install path runs
# `pip install -e .[dev]` into a bootstrap venv and syncs the repo WITHOUT
# .venv, so the repo-local binary may be missing — or present with a DEAD
# interpreter (a synced venv carries absolute shebangs pointing at the build
# machine's python). Resolution order:
#   1. $ROOT/.venv/bin/chimera-mcp when executable with a live interpreter
#      (dev checkout — behavior unchanged);
#   2. otherwise `chimera-mcp` from PATH (whatever the environment installed);
#   3. otherwise exit 1 naming both attempted paths.
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VENV_BIN="$ROOT/.venv/bin/chimera-mcp"
VENV_PY="$ROOT/.venv/bin/python3"

# Live = the entry point is executable AND the venv's own interpreter
# exists. A synced-in venv keeps chimera-mcp's executable bit while its
# shebang points at the build machine's python — if .venv/bin/python3 is
# gone (broken symlink), every script in the venv is dead with it.
venv_bin_live() {
  [ -x "$VENV_PY" ] && [ -x "$VENV_BIN" ]
}

if venv_bin_live; then
  # Honor CHIMERA_CONFIG when set (standard env override, used by tests and
  # CI); otherwise pass the repo config explicitly so find_config_path's
  # CWD-walk can never pick a wrong chimera.yaml.
  exec "$VENV_BIN" "${CHIMERA_CONFIG:-$ROOT/chimera.yaml}"
fi

# Fresh-install / bootstrap-venv case: use whatever the environment put on PATH.
PATH_BIN="$(command -v chimera-mcp 2>/dev/null || true)"
if [ -n "$PATH_BIN" ] && [ -x "$PATH_BIN" ]; then
  exec "$PATH_BIN" "${CHIMERA_CONFIG:-$ROOT/chimera.yaml}"
fi

echo "chimera-mcp-hermes: no usable chimera-mcp MCP server found. Attempted:" >&2
echo "  1. $VENV_BIN (missing, or dead: interpreter $VENV_PY does not resolve to an executable)" >&2
echo "  2. chimera-mcp on PATH (not found via command -v)" >&2
echo "Fix: create the repo venv and install into it (.venv/bin/pip install -e '.[mcp]')," >&2
echo "     or pip install chimera-deliberation so chimera-mcp lands on PATH." >&2
exit 1
