$ErrorActionPreference = 'Stop'
$packageDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$mcpExe = Join-Path $packageDir '骐成工作台MCPV1.5.2.exe'
if (-not (Test-Path -LiteralPath $mcpExe)) {
    throw '找不到骐成工作台MCPV1.5.2.exe，请解压完整软件包后再运行。'
}
$codexConfigHome = Join-Path $env:USERPROFILE '.codex'
$configPath = Join-Path $codexConfigHome 'config.toml'
New-Item -ItemType Directory -Force -Path $codexConfigHome | Out-Null
$escaped = $mcpExe.Replace('\', '\\').Replace('"', '\"')
$block = "`n[mcp_servers.qicheng]`ncommand = `"$escaped`"`n"
$content = if (Test-Path -LiteralPath $configPath) {
    Get-Content -Raw -LiteralPath $configPath
} else {
    ''
}
if ($content -match '(?ms)^\[mcp_servers\.qicheng\].*?(?=^\[|\z)') {
    $content = [regex]::Replace(
        $content,
        '(?ms)^\[mcp_servers\.qicheng\].*?(?=^\[|\z)',
        $block.TrimStart()
    )
} else {
    $content += $block
}
Set-Content -LiteralPath $configPath -Value $content -Encoding utf8
Write-Host '骐成工作台 MCP V1.5.2 已写入 Codex 配置，请重启 Codex。' -ForegroundColor Green
