#!/usr/bin/env bash
set -euo pipefail

# The public Codex install instruction intentionally needs no Codex CLI. Codex
# App may not expose its bundled CLI to the shell that executes this script.
config_home="${CODEX_HOME:-$HOME/.codex}"
config_file="$config_home/config.toml"

# Re-running the installer must not create a second pending Agent or key.
if [ -f "$config_file" ] && grep -Eq '^\[mcp_servers\.hi\][[:space:]]*$' "$config_file" 2>/dev/null; then
  echo "Hi is already configured in $config_file; no new Agent or key was created."
  echo "Fully quit and relaunch Codex so it loads the Hi MCP tools."
  exit 0
fi

command -v curl >/dev/null 2>&1 || { echo "curl is required" >&2; exit 1; }

response="$(curl -fsS -X POST https://hi.hirey.ai/v1/agents/api-keys \
  -H 'content-type: application/json' \
  -d '{"agent_type":"codex","display_name":"Codex"}')"
if command -v plutil >/dev/null 2>&1; then
  config="$(printf '%s' "$response" | plutil -extract setup.codex_config_toml raw -o - -- - 2>/dev/null)" || config=""
elif command -v jq >/dev/null 2>&1; then
  config="$(printf '%s' "$response" | jq -er '.setup.codex_config_toml' 2>/dev/null)" || config=""
else
  echo "The installer needs macOS plutil or jq to read Hi's response." >&2
  exit 1
fi
if [ -z "$config" ]; then
  echo "Hi returned an invalid Codex configuration; no credential was written." >&2
  exit 1
fi

mkdir -p "$config_home"
touch "$config_file"
printf '\n%s\n' "$config" >> "$config_file"
chmod 600 "$config_file" 2>/dev/null || true
echo "Hi was added to $config_file."
echo "Fully quit and relaunch Codex, start a new task, and call hi_agent_status."
