#!/bin/bash
# ==========================================
# Codex CLI 配置脚本 (跨平台: Windows Git Bash / Mac / Linux)
# ==========================================

set -e

# 默认配置
DEFAULT_BASE_URL="https://clauderelay-lb.aihang365.com/openai"
DEFAULT_MODEL="gpt-5.2-codex"
DEFAULT_PROVIDER="claude-relay"

# 解析参数
BASE_URL="${1:-$DEFAULT_BASE_URL}"
MODEL="${3:-$DEFAULT_MODEL}"
PROVIDER="${4:-$DEFAULT_PROVIDER}"

# API Key: 参数 > 环境变量 > 用户输入
API_KEY="${2:-${CODEX_API_KEY:-${OPENAI_API_KEY:-}}}"

# 清理空白字符
API_KEY=$(echo "$API_KEY" | tr -d '[:space:]')

if [ -z "$API_KEY" ]; then
    echo "请输入 API Key (或设置环境变量 CODEX_API_KEY):"
    echo "  格式: sk-xxxxx (以 sk- 开头)"
    echo ""
    printf "> "
    read -r API_KEY </dev/tty
    # 清理: 移除空格、换行、不可见字符
    API_KEY=$(echo "$API_KEY" | tr -d '[:space:]' | tr -d '\000-\037')
fi

# 验证 API Key
if [ -z "$API_KEY" ]; then
    echo ""
    echo "错误: API Key 不能为空"
    exit 1
fi

if [[ ! "$API_KEY" =~ ^sk- ]]; then
    echo ""
    echo "警告: API Key 格式可能不正确 (通常以 sk- 开头)"
    echo "  输入的值: ${API_KEY:0:10}..."
    echo ""
    printf "是否继续? [y/N] "
    read -r CONFIRM </dev/tty
    if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
        echo "已取消"
        exit 1
    fi
fi

CONFIG_DIR="$HOME/.codex"

# ------------------------------------------
# 平台检测
# ------------------------------------------
detect_platform() {
    case "$(uname -s)" in
        Linux*)     PLATFORM="Linux" ;;
        Darwin*)    PLATFORM="Mac" ;;
        CYGWIN*|MINGW*|MSYS*) PLATFORM="Windows" ;;
        *)          PLATFORM="Unknown" ;;
    esac
    echo "$PLATFORM"
}

PLATFORM=$(detect_platform)

echo "=== Codex CLI 配置脚本 ==="
echo "平台: $PLATFORM"
echo ""

# ------------------------------------------
# 1. 检查并安装 Codex CLI
# ------------------------------------------
echo "[1/6] 检查 Codex 安装..."
if ! command -v codex &> /dev/null; then
    echo "  Codex 未安装，正在通过 npm 安装..."
    if command -v npm &> /dev/null; then
        npm install -g @openai/codex 2>/dev/null || npm install -g codex-cli 2>/dev/null
        if [ $? -eq 0 ]; then
            echo "  ✓ 安装完成"
        else
            echo "  ✗ 安装失败，请手动执行: npm install -g @openai/codex"
            exit 1
        fi
    else
        echo "  ✗ npm 未安装"
        case "$PLATFORM" in
            Windows)
                echo "  请从 https://nodejs.org 下载安装 Node.js"
                ;;
            Mac)
                echo "  请执行: brew install node"
                ;;
            Linux)
                echo "  请执行: apt install nodejs npm 或 yum install nodejs npm"
                ;;
        esac
        exit 1
    fi
else
    VERSION=$(codex --version 2>/dev/null || echo "unknown")
    echo "  ✓ Codex 已安装 (版本: $VERSION)"
fi

# ------------------------------------------
# 2. 备份旧配置
# ------------------------------------------
echo ""
echo "[2/6] 备份旧配置..."
mkdir -p "$CONFIG_DIR"

# 时间戳格式根据平台调整
if [ "$PLATFORM" = "Windows" ]; then
    TIMESTAMP=$(date +%Y%m%d_%H%M%S 2>/dev/null || echo "backup")
else
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
fi

if [ -f "$CONFIG_DIR/config.toml" ]; then
    cp "$CONFIG_DIR/config.toml" "$CONFIG_DIR/config.toml.bak_$TIMESTAMP"
    echo "  ✓ 备份 config.toml"
else
    echo "  - config.toml 不存在，跳过"
fi

if [ -f "$CONFIG_DIR/auth.json" ]; then
    cp "$CONFIG_DIR/auth.json" "$CONFIG_DIR/auth.json.bak_$TIMESTAMP"
    echo "  ✓ 备份 auth.json"
else
    echo "  - auth.json 不存在，跳过"
fi

# ------------------------------------------
# 3. 测试 API 连接并获取可用模型
# ------------------------------------------
echo ""
echo "[3/6] 测试 API 连接..."
echo "  URL: $BASE_URL/models"

if command -v curl &> /dev/null; then
    MODELS_RESPONSE=$(curl -s --connect-timeout 10 \
        -H "Authorization: Bearer $API_KEY" \
        "$BASE_URL/models" 2>/dev/null || echo '{"error":"connection failed"}')

    if echo "$MODELS_RESPONSE" | grep -q '"id"'; then
        echo "  ✓ API 连接成功"
        echo ""
        echo "  可用模型:"
        echo "$MODELS_RESPONSE" | grep -o '"id"[[:space:]]*:[[:space:]]*"[^"]*"' | \
            sed 's/"id"[[:space:]]*:[[:space:]]*"/    - /g; s/"$//g' | head -10
    elif echo "$MODELS_RESPONSE" | grep -q '"error"'; then
        echo "  ✗ API 连接失败"
        echo "  响应: $MODELS_RESPONSE"
    else
        echo "  ? API 响应异常: ${MODELS_RESPONSE:0:200}"
    fi
else
    echo "  ✗ curl 未安装，跳过 API 测试"
fi

# ------------------------------------------
# 4. 写入新配置
# ------------------------------------------
echo ""
echo "[4/6] 写入配置..."

cat > "$CONFIG_DIR/config.toml" <<EOF
model_provider = "$PROVIDER"
model = "$MODEL"
model_reasoning_effort = "high"
disable_response_storage = true

[model_providers.$PROVIDER]
name = "$PROVIDER"
base_url = "$BASE_URL"
wire_api = "responses"
requires_openai_auth = true

[features]
web_search_request = true
EOF

cat > "$CONFIG_DIR/auth.json" <<EOF
{
  "OPENAI_API_KEY": "$API_KEY"
}
EOF

echo "  ✓ config.toml 已写入"
echo "  ✓ auth.json 已写入"

# ------------------------------------------
# 5. 测试 Codex 调用
# ------------------------------------------
echo ""
echo "[5/6] 测试 Codex..."

if command -v codex &> /dev/null; then
    echo "  版本: $(codex --version 2>/dev/null || echo '获取失败')"
    echo "  帮助: $(codex --help 2>/dev/null | head -1 || echo '获取失败')"
else
    echo "  ✗ codex 命令不可用，可能需要重启终端"
fi

# ------------------------------------------
# 6. 总结
# ------------------------------------------
echo ""
echo "=========================================="
echo "           配置完成 ($PLATFORM)"
echo "=========================================="
echo "Base URL  : $BASE_URL"
echo "API Key   : ${API_KEY:0:8}...${API_KEY: -4}"
echo "Model     : $MODEL"
echo "Provider  : $PROVIDER"
echo "Config    : $CONFIG_DIR/config.toml"
echo "Auth      : $CONFIG_DIR/auth.json"
echo "=========================================="
echo ""
echo "使用方式:"
echo "  codex \"你的问题\""
echo "  codex exec --skip-git-repo-check \"问题\""
