#!/bin/bash
cd "$(dirname "$0")"

echo ""
echo "============================================"
echo "  yangjinming.org - Codex (Mac)"
echo "============================================"
echo ""

if ! command -v node &> /dev/null; then
    echo "[ERROR] Install Node.js first: brew install node"
    read -p "Press Enter to exit..."
    exit 1
fi

read -p "Enter your API Key (sk-...): " USER_KEY
[ -z "$USER_KEY" ] && { echo "[ERROR] Key empty"; read; exit 1; }

SHELL_CONFIG="$HOME/.zshrc"
[ "$SHELL" = "/bin/bash" ] && SHELL_CONFIG="$HOME/.bash_profile"
touch "$SHELL_CONFIG"

echo ""
echo "[1/3] Installing @openai/codex..."
npm install -g @openai/codex 2>&1 | tail -3

echo ""
echo "[2/3] Writing $HOME/.codex/config.toml..."
mkdir -p "$HOME/.codex"
[ -f "$HOME/.codex/config.toml" ] && cp "$HOME/.codex/config.toml" "$HOME/.codex/config.toml.backup"

cat > "$HOME/.codex/config.toml" << TOML_EOF
model = "claude4.8"
model_provider = "custom"
sandbox_mode = "danger-full-access"
approval_policy = "never"

[model_providers.custom]
name = "custom"
wire_api = "responses"
requires_openai_auth = true
base_url = "https://yangjinming.org/openai/v1"
TOML_EOF

echo ""
echo "[3/3] Setting OPENAI_API_KEY in $SHELL_CONFIG..."
grep -v "OPENAI_API_KEY\|yangjinming.org Codex" "$SHELL_CONFIG" > "$SHELL_CONFIG.tmp" 2>/dev/null || true
mv "$SHELL_CONFIG.tmp" "$SHELL_CONFIG" 2>/dev/null || true
cat >> "$SHELL_CONFIG" << ENV_EOF

# yangjinming.org Codex (added by setup script)
export OPENAI_API_KEY="$USER_KEY"
ENV_EOF

echo ""
echo "[SUCCESS] Open NEW Terminal, run: codex"
read -p "Press Enter to exit..."
