#!/bin/sh
# Economic MCP launcher for Codex and Claude Code. Finds the signed Economic
# binary (standalone CLI or the one inside Economic.app); installs the verified
# CLI from economic.run on first use if neither is present.
set -eu
pick() {
  for c in "${ECONOMIC_BIN:-}" "$HOME/.local/bin/economic" "/Applications/Economic.app/Contents/Helpers/economic" "$HOME/Applications/Economic.app/Contents/Helpers/economic" "/opt/homebrew/bin/economic" "/usr/local/bin/economic"; do
    [ -n "$c" ] && [ -x "$c" ] || continue
    v=$("$c" version 2>/dev/null || true)
    case "$v" in "economic "[1-9]*) printf '%s' "$c"; return 0;; esac
  done
  return 1
}
bin=$(pick || true)
if [ -z "$bin" ]; then
  printf '%s\n' "Economic is not installed; installing the signed CLI from https://economic.run/install.sh ..." >&2
  /usr/bin/curl -fsSL https://economic.run/install.sh | ECONOMIC_QUIET=1 /bin/sh >&2 || true
  bin=$(pick || true)
fi
if [ -z "$bin" ]; then
  printf '%s\n' "Economic could not be installed automatically. Install it with: curl -fsSL https://economic.run/install.sh | sh" >&2
  exit 1
fi
# A normal plugin launched inside Economic must retain that exact turn, role and
# helper. It must not open an owner conversation in a different selected economy.
if [ -n "${ECONOMIC_TURN:-}" ]; then
  [ -n "${ECONOMIC_CAPABILITY:-}" ] || { printf '%s\n' "Economic turn capability is missing; no owner fallback was used." >&2; exit 1; }
  role=${ECONOMIC_ROLE:-worker}
  case "$role" in worker|harness) ;; *) printf '%s\n' "Invalid inherited Economic role." >&2; exit 1;; esac
  exec "$bin" mcp --role "$role" --turn "$ECONOMIC_TURN"
fi
exec "$bin" mcp --role host
