#!/bin/bash

# NexusAI 一键配置脚本 (Windows Git Bash) - 修复版
# 修复: Windows Git Bash heredoc 控制字符问题

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) 配置工具 (Git Bash)${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo ""

# ==================== 唯一交互：输入API Key ====================
echo -e "${CYAN}▶ 请输入您的 API Key:${NC}"
printf "  API Key: "
read 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. 清除旧的 Codex 配置
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/"
    [ -d ~/.config/codex ] && cp -r ~/.config/codex "$BACKUP_DIR/"
    echo "备份位置: $BACKUP_DIR"
fi
echo -e "${GREEN}完成${NC}"

# 2. 检查/安装 Codex
echo -n "  [2/3] 检查 Codex CLI... "
if command -v codex &> /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 @openai/codex >/dev/null 2>&1
    command -v codex &> /dev/null && echo -e "  [2/3] 检查 Codex CLI... ${GREEN}安装成功${NC}" || { echo -e "${RED}❌ 安装失败${NC}"; exit 1; }
fi

# 3. 写入配置（修复版：逐行写入避免控制字符）
echo -n "  [3/3] 写入配置... "
CODEX_DIR="$HOME/.codex"
mkdir -p "$CODEX_DIR"

# 使用逐行 echo 替代 heredoc，避免控制字符问题
CONFIG_FILE="$CODEX_DIR/config.toml"
> "$CONFIG_FILE"  # 清空文件
echo 'model_provider = "nexusai"' >> "$CONFIG_FILE"
echo 'model = "gpt-5.1-codex-max-xhigh"' >> "$CONFIG_FILE"
echo 'model_reasoning_effort = "high"' >> "$CONFIG_FILE"
echo 'disable_response_storage = true' >> "$CONFIG_FILE"
echo '' >> "$CONFIG_FILE"
echo '[model_providers.nexusai]' >> "$CONFIG_FILE"
echo 'name = "nexusai"' >> "$CONFIG_FILE"
echo 'base_url = "https://codex-relay.aihang365.com/v1"' >> "$CONFIG_FILE"
echo 'wire_api = "responses"' >> "$CONFIG_FILE"
echo 'requires_openai_auth = true' >> "$CONFIG_FILE"
echo '' >> "$CONFIG_FILE"
echo '[features]' >> "$CONFIG_FILE"
echo 'web_search_request = true' >> "$CONFIG_FILE"

# auth.json 同样逐行写入
AUTH_FILE="$CODEX_DIR/auth.json"
> "$AUTH_FILE"
echo '{' >> "$AUTH_FILE"
echo "  \"OPENAI_API_KEY\": \"$API_KEY\"" >> "$AUTH_FILE"
echo '}' >> "$AUTH_FILE"

# 验证配置文件（检查是否有控制字符）
if grep -q $'[\x00-\x1F]' "$CONFIG_FILE" 2>/dev/null; then
    echo -e "${RED}失败（检测到控制字符）${NC}"
    echo -e "${YELLOW}尝试备用方法...${NC}"
    # 备用：使用 printf
    printf '%s\n' \
        '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' > "$CONFIG_FILE"
fi

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

# ==================== 完成 ====================
echo ""
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}   ✅ 配置完成!${NC}"
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo ""
echo -e "  配置文件: ${CYAN}$CODEX_DIR/config.toml${NC}"
echo -e "  模型: ${CYAN}gpt-5.1-codex-max-xhigh${NC} (专业深度)"
echo ""
echo -e "${YELLOW}请执行以下命令开始使用:${NC}"
echo ""
echo -e "  ${CYAN}codex${NC}"
echo ""
echo -e "${YELLOW}如遇到问题，请检查:${NC}"
echo -e "  cat ~/.codex/config.toml"
echo ""
