#!/bin/bash

# NexusAI 一键配置脚本 (Linux 专用)
# 版本: v2.3
# 更新日期: 2025-12-07

VERSION="v2.3"
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) 配置工具 (Linux) ${VERSION}${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" | sed 's/\x1b\[[0-9;]*[a-zA-Z]//g' | tr -d '\000-\037\177' | xargs)

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>/dev/null || echo "未知版本")
    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. 写入配置（使用 printf 避免任何控制字符）
echo -n "  [3/4] 写入 config.toml... "
CONFIG_FILE="$CODEX_DIR/config.toml"
> "$CONFIG_FILE"  # 清空文件
printf 'model_provider = "nexusai"\n' >> "$CONFIG_FILE"
printf 'model = "gpt-5.1-codex-max-xhigh"\n' >> "$CONFIG_FILE"
printf 'model_reasoning_effort = "high"\n' >> "$CONFIG_FILE"
printf 'disable_response_storage = true\n' >> "$CONFIG_FILE"
printf '\n' >> "$CONFIG_FILE"
printf '[model_providers.nexusai]\n' >> "$CONFIG_FILE"
printf 'name = "nexusai"\n' >> "$CONFIG_FILE"
printf 'base_url = "https://codex-relay.aihang365.com/v1"\n' >> "$CONFIG_FILE"
printf 'wire_api = "responses"\n' >> "$CONFIG_FILE"
printf 'requires_openai_auth = true\n' >> "$CONFIG_FILE"
printf '\n' >> "$CONFIG_FILE"
printf '[features]\n' >> "$CONFIG_FILE"
printf 'web_search_request = true\n' >> "$CONFIG_FILE"
echo -e "${GREEN}完成${NC}"

# 4. 写入 auth.json（使用 printf 确保 JSON 格式正确）
echo -n "  [4/4] 写入 auth.json... "
AUTH_FILE="$CODEX_DIR/auth.json"
> "$AUTH_FILE"  # 清空文件
printf '{\n' >> "$AUTH_FILE"
printf '  "OPENAI_API_KEY": "%s"\n' "$API_KEY" >> "$AUTH_FILE"
printf '}\n' >> "$AUTH_FILE"
echo -e "${GREEN}完成${NC}"

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

# 验证 config.toml
if [ -f "$CONFIG_FILE" ]; then
    if cat "$CONFIG_FILE" | od -c | grep -qE '\\0|\\00[0-1]'; then
        echo -e "  ${RED}✗ config.toml 包含控制字符${NC}"
        exit 1
    else
        echo -e "  ${GREEN}✓ config.toml 正常 ($(wc -l < "$CONFIG_FILE") 行)${NC}"
    fi
fi

# 验证 auth.json
if [ -f "$AUTH_FILE" ]; then
    if cat "$AUTH_FILE" | od -c | grep -qE '\\0|\\00[0-1]'; then
        echo -e "  ${RED}✗ auth.json 包含控制字符${NC}"
        exit 1
    else
        echo -e "  ${GREEN}✓ auth.json 正常${NC}"
    fi
    
    # JSON 格式验证
    if command -v python3 &> /dev/null; then
        if python3 -c "import json; json.load(open('$AUTH_FILE'))" 2>/dev/null; then
            echo -e "  ${GREEN}✓ JSON 格式正确${NC}"
        else
            echo -e "  ${RED}✗ JSON 格式错误${NC}"
            echo -e "${YELLOW}文件内容:${NC}"
            cat "$AUTH_FILE"
            exit 1
        fi
    fi
fi

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

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

# 测试 codex 命令
if command -v codex &> /dev/null; then
    echo -e "${YELLOW}测试 Codex 连接（5秒超时）...${NC}"
    
    # 创建测试脚本
    TEST_RESPONSE=$(timeout 10 codex "Hello, reply with: Codex is working!" 2>&1 || echo "TIMEOUT")
    
    if echo "$TEST_RESPONSE" | grep -qi "working\|codex"; then
        echo -e "${GREEN}✓ Codex 测试成功${NC}"
        echo -e "${CYAN}响应预览:${NC}"
        echo "$TEST_RESPONSE" | head -3
    elif echo "$TEST_RESPONSE" | grep -qi "TIMEOUT"; then
        echo -e "${YELLOW}⚠️  测试超时（可能需要等待模型响应）${NC}"
    else
        echo -e "${YELLOW}⚠️  无法自动测试，请手动运行: ${CYAN}codex \"test\"${NC}"
    fi
else
    echo -e "${RED}✗ codex 命令不可用${NC}"
fi

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