#!/bin/bash
# Start Codex CLI on macOS with the pairing copied by the editor tab.
set +x
set -eu

fail() { printf '%s\n' "$1" >&2; exit 1; }
command -v pbpaste >/dev/null || fail 'This launcher reads the macOS clipboard with pbpaste.'
command -v codex >/dev/null || fail 'Install Codex CLI, then run this launcher again.'

# The clipboard supplies the pairing, never the choice of trusted relay.
relay=${1:-https://world-geometry-mcp.nick-fisher.workers.dev}
[[ $# -le 1 && $relay =~ ^(https://[a-zA-Z0-9.-]+(:[0-9]+)?|http://(127\.0\.0\.1|localhost)(:[0-9]+)?)$ ]] ||
  fail 'Use an HTTPS relay origin, or localhost for development.'
read_pairing() {
  local line
  endpoint=''
  token=''
  while IFS= read -r line || [[ -n $line ]]; do
    line=${line%$'\r'}
    case "$line" in
      'Endpoint: '*)
        [[ -z $endpoint ]] || fail 'Copy one pairing from the editor.'
        endpoint=${line#Endpoint: }
        ;;
      'Authorization: Bearer '*)
        [[ -z $token ]] || fail 'Copy one pairing from the editor.'
        token=${line#Authorization: Bearer }
        ;;
    esac
  done < <(pbpaste)
}
read_pairing
if [[ -z $endpoint && -t 0 ]]; then
  printf 'Select Copy agent instructions in the editor, then press Return here.\n' >&2
  IFS= read -r
  read_pairing
fi
[[ $token =~ ^[a-f0-9]{64}$ ]] || fail 'Select Copy agent instructions in the editor, then run this launcher again.'
digest=$(printf '%s' "$token" | /usr/bin/shasum -a 256)
case "$endpoint" in
  "$relay/mcp/${digest%% *}")
    server=town_plot
    prompt='Use the town_plot MCP tools. Call refresh_pairing and get_plot, then ask what I want to build. While building, renew at refreshAt and use add_mesh for my requested geometry.'
    ;;
  "$relay/chess/mcp/${digest%% *}")
    server=chess_set
    prompt='Use the chess_set MCP tools. Call refresh_pairing and get_set, then ask what pieces I want to design. Renew at refreshAt while editing. I will preview and publish the set.'
    ;;
  *) fail 'The copied pairing does not match this relay. Copy fresh instructions from the editor.' ;;
esac

export GEOMETRY_AGENT_TOKEN="$token"
exec codex --no-daemon \
  -c "mcp_servers.$server.url=\"$endpoint\"" \
  -c "mcp_servers.$server.bearer_token_env_var=\"GEOMETRY_AGENT_TOKEN\"" \
  -c "mcp_servers.$server.required=true" \
  "$prompt"
