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

echo ""
echo "============================================"
echo "  yangjinming.org - OpenClaw (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; }

echo ""
echo "[1/2] Installing OpenClaw..."
npm install -g openclaw 2>&1 | tail -3 || npm install -g @openclaw/cli 2>&1 | tail -3

echo ""
echo "[2/2] Writing OpenClaw config..."
mkdir -p "$HOME/.openclaw"
[ -f "$HOME/.openclaw/openclaw.json" ] && cp "$HOME/.openclaw/openclaw.json" "$HOME/.openclaw/openclaw.json.backup"

cat > "$HOME/.openclaw/openclaw.json" << JSON_EOF
{
  "models": {
    "mode": "merge",
    "providers": {
      "yangjinming": {
        "baseUrl": "https://yangjinming.org/anthropic",
        "apiKey": "$USER_KEY",
        "api": "anthropic-messages",
        "models": [
          { "id": "claude-opus-4-8", "name": "Claude Opus 4.8", "contextWindow": 200000, "maxTokens": 8192 },
          { "id": "claude-sonnet-4-6", "name": "Claude Sonnet 4.6", "contextWindow": 200000, "maxTokens": 8192 },
          { "id": "claude-haiku-4-5-20251001", "name": "Claude Haiku 4.5", "contextWindow": 200000, "maxTokens": 8192 }
        ]
      }
    }
  },
  "agents": { "defaults": { "model": { "primary": "yangjinming/claude-sonnet-4-6" } } }
}
JSON_EOF

echo ""
echo "[SUCCESS] Open NEW Terminal, try:"
echo "  openclaw chat --local"
echo "  openclaw dashboard"
read -p "Press Enter to exit..."
