#!/bin/bash

# 版本: v2.3
# 更新日期: 2025-12-07
# Claude Relay 一键配置脚本 (macOS/Linux)
# 备用: curl -fsSL https://scripts-china.aihang365.com/setup-cc-relay-linux.sh | bash

set -e

SERVERS=(
    "https://clauderelay-lb.aihang365.com/api"
    "https://japan.clauderelay.aihang365.com/api"
    "https://relay-main.aihang365.com/api"
    "https://relay-1.aihang365.com/api"
)

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

clear
echo ""
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo -e "${CYAN}   Claude Code (Relay) 配置工具 v2.3${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo ""

# ==================== 唯一交互：输入API Key ====================
echo -e "${CYAN}▶ 请输入您的 API Key (cr_开头):${NC}"
printf "  API Key: "
read -r API_KEY < /dev/tty
API_KEY=$(echo "$API_KEY" | xargs)

[ -z "$API_KEY" ] && echo -e "${RED}❌ API Key不能为空${NC}" && exit 1

# ==================== 以下全自动 ====================
echo ""
echo -e "${CYAN}▶ 自动配置中，请稍候...${NC}"
echo ""

# 1. 备份旧配置
echo -n "  [1/5] 备份旧配置... "
BACKUP_DIR=~/.claude_backup_$(date +%Y%m%d_%H%M%S)
if [ -d ~/.claude ] || [ -d ~/.config/claude ] || [ -f ~/.anthropic_auth_token ]; then
    mkdir -p "$BACKUP_DIR"
    [ -d ~/.claude ] && cp -r ~/.claude "$BACKUP_DIR/" && echo -e "${GREEN}✓ ~/.claude 已备份${NC}"
    [ -d ~/.config/claude ] && cp -r ~/.config/claude "$BACKUP_DIR/" && echo -e "${GREEN}✓ ~/.config/claude 已备份${NC}"
    [ -f ~/.anthropic_auth_token ] && cp ~/.anthropic_auth_token "$BACKUP_DIR/" && echo -e "${GREEN}✓ Token 已备份${NC}"
    echo -e "${GREEN}备份位置: $BACKUP_DIR${NC}"
else
    echo -e "${YELLOW}无需备份${NC}"
fi
echo -e "${GREEN}完成${NC}"

# 2. 检查/安装 Claude Code
echo -n "  [2/5] 检查 Claude Code... "
if command -v claude &> /dev/null; then
    echo -e "${GREEN}已安装${NC}"
else
    echo -e "${YELLOW}安装中...${NC}"
    if ! command -v npm &> /dev/null; then
        echo -e "${RED}❌ 请先安装 Node.js: https://nodejs.org/${NC}"
        exit 1
    fi
    npm install -g @anthropic-ai/claude-code >/dev/null 2>&1 || sudo npm install -g @anthropic-ai/claude-code >/dev/null 2>&1
    command -v claude &> /dev/null && echo -e "  [2/5] 检查 Claude Code... ${GREEN}安装成功${NC}" || { echo -e "${RED}❌ 安装失败${NC}"; exit 1; }
fi

# 3. 检测最快服务器
echo -n "  [3/5] 检测最快服务器... "
FASTEST_URL=""
FASTEST_TIME=99999
for url in "${SERVERS[@]}"; do
    START=$(date +%s%3N 2>/dev/null || python3 -c "import time;print(int(time.time()*1000))")
    if curl -s -f -m 3 "${url}/health" >/dev/null 2>&1; then
        END=$(date +%s%3N 2>/dev/null || python3 -c "import time;print(int(time.time()*1000))")
        TIME=$((END - START))
        [ "$TIME" -lt "$FASTEST_TIME" ] && FASTEST_TIME=$TIME && FASTEST_URL="$url"
    fi
done
[ -z "$FASTEST_URL" ] && echo -e "${RED}失败${NC}" && exit 1
echo -e "${GREEN}${FASTEST_URL} (${FASTEST_TIME}ms)${NC}"

# 4. 验证 API Key
echo -n "  [4/5] 验证 API Key... "
if curl -s -f -m 10 -H "x-api-key: $API_KEY" -H "anthropic-version: 2023-06-01" "${FASTEST_URL}/v1/models" >/dev/null 2>&1; then
    echo -e "${GREEN}有效${NC}"
else
    echo -e "${RED}无效${NC}" && exit 1
fi

# 5. 配置环境变量
echo -n "  [5/5] 配置环境变量... "
SHELL_CONFIG="$HOME/.zshrc"
[ "$SHELL" = "/bin/bash" ] && SHELL_CONFIG="$HOME/.bashrc"
[ "$(uname)" = "Darwin" ] && [ "$SHELL" = "/bin/bash" ] && SHELL_CONFIG="$HOME/.bash_profile"
touch "$SHELL_CONFIG"

# 清理旧配置并写入新配置
if [ "$(uname)" = "Darwin" ]; then
    sed -i '' '/ANTHROPIC_BASE_URL/d;/ANTHROPIC_AUTH_TOKEN/d;/# Claude Relay/d' "$SHELL_CONFIG" 2>/dev/null || true
else
    sed -i '/ANTHROPIC_BASE_URL/d;/ANTHROPIC_AUTH_TOKEN/d;/# Claude Relay/d' "$SHELL_CONFIG" 2>/dev/null || true
fi
cat >> "$SHELL_CONFIG" << EOF

# Claude Relay 配置
export ANTHROPIC_BASE_URL="$FASTEST_URL"
export ANTHROPIC_AUTH_TOKEN="$API_KEY"
EOF
echo -e "${GREEN}完成${NC}"

# ==================== 完成 ====================
echo ""
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}   ✅ 配置完成!${NC}"
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo ""
echo -e "${YELLOW}请执行以下命令开始使用:${NC}"
echo ""
echo -e "  ${CYAN}source $SHELL_CONFIG && claude${NC}"
echo ""

# ==================== 自动测试 ====================
echo ""
echo -e "${CYAN}▶ 运行自动测试...${NC}"
echo ""

# 重新加载环境变量
source "$SHELL_CONFIG" 2>/dev/null || true

if command -v claude &> /dev/null; then
    echo -e "${YELLOW}测试 Claude Code 连接...${NC}"
    
    # 测试 claude 命令（使用 -p 参数）
    TEST_RESPONSE=$(timeout 15 claude -p "Hello, reply with: Claude is working!" 2>&1 || echo "TIMEOUT")
    
    if echo "$TEST_RESPONSE" | grep -qi "working\|claude\|hello"; then
        echo -e "${GREEN}✓ Claude Code 测试成功${NC}"
        echo -e "${CYAN}响应预览:${NC}"
        echo "$TEST_RESPONSE" | head -3
    elif echo "$TEST_RESPONSE" | grep -qi "TIMEOUT"; then
        echo -e "${YELLOW}⚠️  测试超时，请手动运行: ${CYAN}claude -p \"test\"${NC}"
    else
        echo -e "${YELLOW}⚠️  无法自动测试${NC}"
        echo -e "   手动测试: ${CYAN}source $SHELL_CONFIG && claude -p \"test\"${NC}"
    fi
else
    echo -e "${RED}✗ claude 命令不可用${NC}"
    echo -e "   请先执行: ${CYAN}source $SHELL_CONFIG${NC}"
fi

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}   配置完成！开始使用:${NC}"
echo -e "${CYAN}   source $SHELL_CONFIG${NC}"
echo -e "${CYAN}   claude -p \"你的问题\"${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
