#!/usr/bin/env bash
#
# codex — ClaudeAll shim that:
#   1. Sources ~/.codex/.env (and ~/.claude/.env as fallback) so MCP servers
#      see CONTEXT7_API_KEY / EXA_API_KEY / Z_AI_API_KEY / TELEGRAM_* / etc.
#   2. Forwards all args to the REAL codex binary further down PATH.
#
# Bypass this shim entirely:
#   command -v codex -a       # see all codex binaries
#   /usr/local/bin/codex ...  # call the real one directly

set -u

# ─── Source env files (most-specific first) ───────────────────────────────
load_env() {
    local f="$1"
    if [ -f "$f" ]; then
        set -a
        # shellcheck disable=SC1090
        . "$f" 2>/dev/null || true
        set +a
    fi
}
load_env "$HOME/.claude/.env"
load_env "$HOME/.codex/.env"

# ─── Find the REAL codex binary (skip ourselves) ──────────────────────────
SELF="$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"

REAL_CODEX=""
IFS=':' read -ra DIRS <<< "$PATH"
for dir in "${DIRS[@]}"; do
    candidate="$dir/codex"
    [ -x "$candidate" ] || continue
    candidate_real="$(readlink -f "$candidate" 2>/dev/null || realpath "$candidate" 2>/dev/null || echo "$candidate")"
    if [ "$candidate_real" = "$SELF" ]; then
        continue
    fi
    REAL_CODEX="$candidate"
    break
done

if [ -z "$REAL_CODEX" ]; then
    echo "❌ ClaudeAll codex shim: real codex binary not found in PATH." >&2
    echo "   Install: npm install -g @openai/codex" >&2
    exit 127
fi

exec "$REAL_CODEX" "$@"
