#!/usr/bin/env bash
# Launch the ha-mcp stdio server. Referenced by the repo-root .mcp.json.
#
# Picks the venv at services/ha-mcp/.venv when it exists (see README.md,
# "Install"), otherwise falls back to the system python3 — which works only
# if the `mcp` SDK is installed there. Never prints to stdout: stdout is the
# JSON-RPC channel and any stray byte breaks the protocol.
set -euo pipefail

SERVICE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_PY="$SERVICE_DIR/.venv/bin/python"

if [[ -x "$VENV_PY" ]]; then
    PY="$VENV_PY"
else
    PY="$(command -v python3)"
fi

if ! "$PY" -c "import mcp" 2>/dev/null; then
    echo "ha-mcp: the 'mcp' SDK is not importable by $PY — see services/ha-mcp/README.md, 'Install'" >&2
    exit 1
fi

export PYTHONPATH="$SERVICE_DIR/src${PYTHONPATH:+:$PYTHONPATH}"
exec "$PY" -m ha_mcp.server "$@"
