#!/bin/bash

# Codex (美国服务器) 一键配置脚本
# 版本: v1.1-USA
# 更新日期: 2025-12-09
# 下载: curl -fsSL http://82.29.54.80/setup-codex-usa.sh | bash

set -e

# 使用Caddy反向代理地址（80端口）
API_BASE_URL="http://82.29.54.80/v1"

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}   Codex (美国服务器) 配置工具 v1.1${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo ""

# 唯一交互：输入API Key
echo -e "${CYAN}▶ 请输入您的 API Key:${NC}"
printf "  API Key: "
read -r API_KEY
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/3] 备份旧配置... "
BACKUP_DIR=~/.codex_backup_$(date +%Y%m%d_%H%M%S)
if [ -d ~/.codex ] || [ -d ~/.config/codex ]; then
    mkdir -p "$BACKUP_DIR"
    [ -d ~/.codex ] && cp -r ~/.codex "$BACKUP_DIR/" && echo -e "${GREEN}✓ ~/.codex 已备份${NC}"
    [ -d ~/.config/codex ] && cp -r ~/.config/codex "$BACKUP_DIR/" && echo -e "${GREEN}✓ ~/.config/codex 已备份${NC}"
    echo -e "${GREEN}备份位置: $BACKUP_DIR${NC}"
else
    echo -e "${YELLOW}无需备份${NC}"
fi
echo -e "${GREEN}完成${NC}"

# 2. 验证API连接
echo -n "  [2/3] 验证API连接... "
if curl -s -f -m 10 "http://82.29.54.80/health" >/dev/null 2>&1; then
    echo -e "${GREEN}连接成功${NC}"
else
    echo -e "${RED}连接失败${NC}"
    echo -e "${YELLOW}提示: 请检查网络连接或联系管理员${NC}"
    exit 1
fi

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

# 清除旧配置
if [ "$(uname)" = "Darwin" ]; then
    sed -i '' '/OPENAI_BASE_URL.*82.29.54.80/d;/OPENAI_API_KEY.*# Codex USA/d;/# Codex USA/d' "$SHELL_CONFIG" 2>/dev/null || true
else
    sed -i '/OPENAI_BASE_URL.*82.29.54.80/d;/OPENAI_API_KEY.*# Codex USA/d;/# Codex USA/d' "$SHELL_CONFIG" 2>/dev/null || true
fi

# 添加新配置
cat >> "$SHELL_CONFIG" << ENVEOF

# Codex USA (82.29.54.80)
export OPENAI_BASE_URL="$API_BASE_URL"
export OPENAI_API_KEY="$API_KEY"  # Codex USA
ENVEOF

echo -e "${GREEN}完成${NC}"

echo ""
echo -e "${GREEN}✅ 配置成功！${NC}"
echo ""
echo -e "${CYAN}服务器地址: ${GREEN}$API_BASE_URL${NC}"
echo -e "${CYAN}可用模型:${NC}"
echo -e "  - ${GREEN}gpt-5-codex-medium${NC} (推荐)"
echo -e "  - ${GREEN}gpt-5-codex-high${NC}"
echo -e "  - ${GREEN}gpt-5.1-codex-max-xhigh${NC}"
echo ""
echo -e "${YELLOW}⚠️  请运行以下命令使配置生效:${NC}"
echo -e "  ${CYAN}source $SHELL_CONFIG${NC}"
echo ""
echo -e "${CYAN}测试命令:${NC}"
echo -e "  ${GREEN}curl -X POST \$OPENAI_BASE_URL/chat/completions \\${NC}"
echo -e "  ${GREEN}  -H 'Content-Type: application/json' \\${NC}"
echo -e "  ${GREEN}  -H 'Authorization: Bearer \$OPENAI_API_KEY' \\${NC}"
echo -e "  ${GREEN}  -d '{\"model\": \"gpt-5-codex-medium\", \"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]}'${NC}"
echo ""
