#!/usr/bin/env bash
# Launch the Clio MCP server over stdio from the checkout this plugin was installed from.
#
# Codex materializes a plugin into $CODEX_HOME/plugins/cache/<marketplace>/<plugin>/<version>/,
# so this script cannot reach the backend by walking up from its own location. It instead reads
# the marketplace `source` that install.sh recorded in config.toml, which is the one absolute
# path the install already required — nothing machine-specific is committed.
set -euo pipefail

MARKETPLACE=clio-local

# stdout carries JSON-RPC frames; every diagnostic goes to stderr.
die() {
    printf 'clio-mcp: %s\n' "$1" >&2
    exit 1
}

resolve_backend() {
    if [[ -n "${VINCENT_BACKEND_DIR:-}" ]]; then
        printf '%s' "$VINCENT_BACKEND_DIR"
        return
    fi

    local config="${CODEX_HOME:-$HOME/.codex}/config.toml"
    [[ -f $config ]] || die "no config.toml at $config — run mcp-plugin/install.sh"

    local source
    source=$(awk -v section="[marketplaces.$MARKETPLACE]" '
        $0 == section { found = 1; next }
        /^\[/ { found = 0 }
        found && /^[[:space:]]*source[[:space:]]*=/ {
            sub(/^[^=]*=[[:space:]]*"/, ""); sub(/"[[:space:]]*$/, ""); print; exit
        }
    ' "$config")
    [[ -n $source ]] || die "[marketplaces.$MARKETPLACE] missing from $config — run mcp-plugin/install.sh"

    printf '%s' "${source%/}/../backend"
}

backend=$(resolve_backend)
[[ -d $backend ]] || die "backend directory not found: $backend"
backend=$(cd -- "$backend" && pwd)
[[ -f "$backend/mcp_server.py" ]] || die "no mcp_server.py in $backend — is the checkout intact?"

uv=${VINCENT_UV:-$(command -v uv || true)}
if [[ -z $uv ]]; then
    for candidate in "$HOME/.local/bin/uv" /opt/homebrew/bin/uv /usr/local/bin/uv; do
        [[ -x $candidate ]] && uv=$candidate && break
    done
fi
[[ -n $uv ]] || die "uv not found on PATH — set VINCENT_UV to its absolute path"

export VINCENT_MCP_ENABLED="${VINCENT_MCP_ENABLED:-1}"
export VINCENT_MCP_API_BASE_URL="${VINCENT_MCP_API_BASE_URL:-https://api-vincent.myclio.ca:8888}"

# --no-sync reuses the existing environment instead of resolving dependencies on every launch.
exec "$uv" --directory "$backend" run --no-sync python mcp_server.py
