#!/bin/bash
# Shim placed on a woken agent's PATH so it can just call `comms`.
# Resolves to the daemon's venv python running the CLI, following symlinks so it
# works whether called directly or via ~/.local/bin/comms.
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
REPO="$(cd -P "$(dirname "$SOURCE")/.." && pwd)"
# Which Python runs the CLI, in this order:
#   1.  the checkout's own .venv (a developer's, or a host installed before the
#       venv moved out of the release folder);
#   2.  the interpreter record beside this release folder, which the service
#       installer writes and the broker keeps current (scripts/release_layout.sh);
#       an installed `comms` runs from <store>/releases/<version>, and an update
#       lays that folder down with no environment in it;
#   3.  savi-comms-venv beside this folder, for `comms` run from the unpacked
#       folder itself.
PY="$REPO/.venv/bin/python"
if [ ! -x "$PY" ] && [ -f "$(dirname "$REPO")/interpreter" ]; then
  PY="$(head -n 1 "$(dirname "$REPO")/interpreter" | tr -d '\r\n')"
fi
[ -x "$PY" ] || PY="$(dirname "$REPO")/savi-comms-venv/bin/python"
if [ ! -x "$PY" ]; then
  echo "comms:  no Python environment was found for $REPO, so nothing ran." >&2
  echo "        Looked in $REPO/.venv, the record $(dirname "$REPO")/interpreter, and $(dirname "$REPO")/savi-comms-venv." >&2
  echo "        Running the service installer again writes the record." >&2
  exit 127
fi
# `comms mcp` is the stdio MCP server (comms_mcp.py, docs/MCP-CONNECTOR.md).  It
# never loads the CLI, so it never resolves a workspace token file:  it acts only
# on the session's own SAVI_COMMS_TOKEN.
if [ "${1:-}" = "mcp" ]; then
  shift
  exec "$PY" "$REPO/comms_mcp.py" "$@"
fi
exec "$PY" "$REPO/comms_cli.py" "$@"
