#!/bin/bash

# OpenAI Codex (NexusAI) 一键配置脚本 (macOS) v2.3
# 备用: curl -fsSL http://scripts-china.aihang365.com/setup-codex-nexusai-mac.sh | bash
# 版本: v2.3 (2025-12-07)

set -e

BASE_URL="https://codex-relay.aihang365.com/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}   OpenAI Codex (NexusAI) 配置工具 (macOS) v2.3${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo ""

# ==================== 强制删除旧配置 ====================
echo -e "${YELLOW}▶ 检测到旧配置，强制清除...${NC}"
# 备份旧配置
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/"
    [ -d ~/.config/codex ] && cp -r ~/.config/codex "$BACKUP_DIR/"
    echo "备份位置: $BACKUP_DIR"
fi
echo -e "${GREEN}✓ 旧配置已清除${NC}"
echo ""

# ==================== 唯一交互：输入API Key ====================
echo -e "${CYAN}▶ 请输入您的 API Key:${NC}"
printf "  API Key: "

# 禁用括号粘贴模式
printf '\e[?2004l' >&2

read -r API_KEY
# 强力清除所有可能的控制字符和空白
API_KEY=$(echo "$API_KEY" | tr -d '\000-\037\177' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

if [ -z "$API_KEY" ]; then
    echo -e "${RED}❌ API Key不能为空${NC}"
    exit 1
fi
echo -e "${GREEN}✓ API Key 已接收（长度: ${#API_KEY}）${NC}"
echo ""

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

# 1. 创建配置目录
echo -n "  [1/4] 创建配置目录... "
CODEX_DIR="$HOME/.codex"
mkdir -p "$CODEX_DIR"
echo -e "${GREEN}完成${NC}"

# 2. 检查/安装 Codex
echo -n "  [2/4] 检查 Codex CLI... "
if command -v codex &> /dev/null; then
    CODEX_VERSION=$(codex --version 2>&1 | head -1)
    echo -e "${GREEN}已安装 ($CODEX_VERSION)${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 @openai/codex >/dev/null 2>&1 || sudo npm install -g @openai/codex >/dev/null 2>&1
    if command -v codex &> /dev/null; then
        echo -e "  [2/4] 检查 Codex CLI... ${GREEN}安装成功${NC}"
    else
        echo -e "${RED}❌ 安装失败${NC}"
        exit 1
    fi
fi

# 3. 写入 config.toml
echo -n "  [3/4] 写入 config.toml... "

cat > "$CODEX_DIR/config.toml" << 'TOML'
model_provider = "nexusai"
model = "gpt-5.1-codex-max-xhigh"
model_reasoning_effort = "high"
disable_response_storage = true

[model_providers.nexusai]
name = "nexusai"
base_url = "https://codex-relay.aihang365.com/v1"
wire_api = "responses"
requires_openai_auth = true

[features]
web_search_request = true
TOML

chmod 600 "$CODEX_DIR/config.toml" 2>/dev/null || true
echo -e "${GREEN}完成${NC}"

# 4. 写入 auth.json
echo -n "  [4/4] 写入 auth.json... "
cat > "$CODEX_DIR/auth.json" << JSON
{
  "OPENAI_API_KEY": "$API_KEY"
}
JSON

chmod 600 "$CODEX_DIR/auth.json" 2>/dev/null || true
echo -e "${GREEN}完成${NC}"

# ==================== 验证配置 ====================
echo ""
echo -e "${CYAN}▶ 验证配置文件...${NC}"

# 验证 config.toml
if [ -f "$CODEX_DIR/config.toml" ]; then
    CONFIG_LINES=$(wc -l < "$CODEX_DIR/config.toml" | tr -d ' ')
    echo -e "  ${GREEN}✓ config.toml 正常 ($CONFIG_LINES 行)${NC}"
else
    echo -e "  ${RED}✗ config.toml 不存在${NC}"
fi

# 验证 auth.json
if [ -f "$CODEX_DIR/auth.json" ]; then
    echo -e "  ${GREEN}✓ auth.json 正常${NC}"
    if command -v jq &> /dev/null; then
        jq . "$CODEX_DIR/auth.json" >/dev/null 2>&1 && echo -e "  ${GREEN}✓ JSON 格式正确${NC}" || echo -e "  ${YELLOW}⚠️  JSON 格式可能有误${NC}"
    fi
else
    echo -e "  ${RED}✗ auth.json 不存在${NC}"
fi

# ==================== 完成 ====================
echo ""
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}   ✓ 配置完成！(v2.3)${NC}"
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo ""
echo "📦 安装信息:"
echo -e "   配置目录: ${CYAN}$CODEX_DIR${NC}"
echo -e "   默认模型: ${CYAN}gpt-5.1-codex-max-xhigh${NC} (专业深度)"
echo -e "   脚本版本: ${CYAN}v2.3${NC}"
echo ""
echo "🚀 开始使用:"
echo -e "   ${CYAN}codex${NC}"
echo ""
echo "💡 切换模型:"
echo -e "   在 codex 中输入: ${CYAN}/model${NC}"
echo ""
echo ""

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

if command -v codex &> /dev/null; then
    echo -e "${YELLOW}测试 Codex 连接（10秒超时）...${NC}"

    TEST_RESPONSE=$(timeout 10 codex "Hello, reply with: Codex is working!" 2>&1 || echo "TIMEOUT")

    if echo "$TEST_RESPONSE" | grep -qi "working"; then
        echo -e "${GREEN}✓ Codex 测试成功${NC}"
    elif echo "$TEST_RESPONSE" | grep -q "TIMEOUT"; then
        echo -e "${YELLOW}⚠️  测试超时（可能需要等待模型响应）${NC}"
    else
        echo -e "${YELLOW}⚠️  测试未通过，请手动验证: ${CYAN}codex \"test\"${NC}"
    fi
fi

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}   配置完成！开始使用:${NC}"
echo -e "${CYAN}   codex \"你的问题\"${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
# 禁用括号粘贴模式（确保终端干净）
printf '\e[?2004l'
