#!/bin/bash
# DeepClaw Mac 一键安装脚本
set -e

DEEPCLAW_API="https://api.yfwis.cn/v1"
DEEPCLAW_SITE="https://deepclaw.yfwis.cn"
OPENCLAW_CONFIG="$HOME/.openclaw/openclaw.json"
GATEWAY_PORT=18789

echo ""
echo "🦞 DeepClaw 安装程序"
echo "================================"
echo ""

# 1. 检查/安装 Node.js
if ! command -v node &>/dev/null; then
  echo "⏳ 正在安装 Node.js..."
  curl -fsSL https://fnm.vercel.app/install | bash
  export PATH="$HOME/.fnm:$PATH"
  eval "$(fnm env)"
  fnm install 22
  fnm use 22
  echo "✅ Node.js 安装完成"
else
  echo "✅ Node.js $(node --version)"
fi

# 2. 安装 DeepClaw 核心引擎
if ! command -v openclaw &>/dev/null; then
  echo "⏳ 正在安装 DeepClaw 核心引擎..."
  npm install -g openclaw 2>/dev/null || sudo npm install -g openclaw
  echo "✅ DeepClaw 核心引擎安装完成"
else
  echo "✅ DeepClaw 核心引擎已就绪"
fi

# 3. 注册账号
echo ""
read -p "📧 请输入邮箱（注册DeepClaw账号，免费领2000算力）: " EMAIL
if [ -z "$EMAIL" ]; then
  echo "❌ 邮箱不能为空"
  exit 1
fi

echo "⏳ 正在注册账号..."
RESPONSE=$(curl -s -X POST "$DEEPCLAW_SITE/api/register" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"$EMAIL\"}")

API_KEY=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('data',{}).get('apiKey',''))" 2>/dev/null)
SUCCESS=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(str(d.get('success',False)).lower())" 2>/dev/null)

if [ "$SUCCESS" != "true" ] || [ -z "$API_KEY" ]; then
  MSG=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('message',''))" 2>/dev/null)
  echo "⚠️  $MSG"
  read -p "🔑 请输入已有的 API Key: " API_KEY
fi

if [ -z "$API_KEY" ]; then
  echo "❌ 无法获取 API Key"
  exit 1
fi

echo "✅ 账号就绪，API Key: ${API_KEY:0:12}..."

# 4. 写入配置
echo "⏳ 正在配置 DeepClaw..."
mkdir -p "$HOME/.openclaw"

python3 - "$OPENCLAW_CONFIG" "$API_KEY" "$DEEPCLAW_API" "$GATEWAY_PORT" << 'PYEOF'
import json, sys, os

config_file, api_key, base_url, port = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4])
config = {}
if os.path.exists(config_file):
  try:
    with open(config_file) as f:
      config = json.load(f)
  except: pass

config.setdefault('models', {}).setdefault('providers', {})
config['models']['providers']['anthropic'] = {
  "baseUrl": base_url, "apiKey": api_key,
  "models": [{"id":"claude-sonnet-4-6","name":"claude-sonnet-4-6","api":"anthropic-messages","reasoning":True,"input":["text","image"],"cost":{"input":0.0024,"output":0.012},"contextWindow":200000,"maxTokens":8192}]
}
config['models']['providers']['openai'] = {
  "baseUrl": base_url, "apiKey": api_key,
  "models": [{"id":"gpt-5-nano","name":"gpt-5-nano","api":"openai-responses","reasoning":False,"input":["text","image"],"cost":{"input":0.00005,"output":0.0004},"contextWindow":128000,"maxTokens":8192}]
}
config.setdefault('agents', {}).setdefault('defaults', {})['model'] = 'anthropic/claude-sonnet-4-6'
config['gateway'] = {"port": port, "mode": "local", "auth": {"mode": "none"}}

with open(config_file, 'w') as f:
  json.dump(config, f, indent=2, ensure_ascii=False)
print("ok")
PYEOF

# 5. 设置开机自启
PLIST="$HOME/Library/LaunchAgents/ai.deepclaw.gateway.plist"
NODE_PATH=$(which node)
OPENCLAW_PATH=$(which openclaw)

cat > "$PLIST" << PLISTEOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>ai.deepclaw.gateway</string>
  <key>ProgramArguments</key>
  <array>
    <string>$NODE_PATH</string>
    <string>$OPENCLAW_PATH</string>
    <string>gateway</string>
    <string>--port</string>
    <string>$GATEWAY_PORT</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>/tmp/deepclaw.log</string>
  <key>StandardErrorPath</key><string>/tmp/deepclaw-error.log</string>
</dict>
</plist>
PLISTEOF

launchctl unload "$PLIST" 2>/dev/null || true
launchctl load "$PLIST"

echo "✅ 开机自启配置完成"

# 6. 启动并打开浏览器
sleep 2
open "http://localhost:$GATEWAY_PORT"

echo ""
echo "🎉 DeepClaw 安装完成！"
echo ""
echo "   浏览器已自动打开 http://localhost:$GATEWAY_PORT"
echo "   API Key: $API_KEY"
echo "   剩余算力: 20,000（免费赠送）"
echo ""
echo "   充值算力: $DEEPCLAW_SITE/#pricing"
echo ""
