@echo off
setlocal DisableDelayedExpansion

set "POWERSHELL_EXE=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
if not exist "%POWERSHELL_EXE%" set "POWERSHELL_EXE=pwsh"
set "TEMP_PS1=%TEMP%\setup_codex_everygpt_%RANDOM%%RANDOM%.ps1"

> "%TEMP_PS1%" echo $ErrorActionPreference = 'Stop'
>> "%TEMP_PS1%" echo function ConvertTo-PlainText {
>> "%TEMP_PS1%" echo     param([Security.SecureString]$SecureString)
>> "%TEMP_PS1%" echo     $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
>> "%TEMP_PS1%" echo     try {
>> "%TEMP_PS1%" echo         [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr)
>> "%TEMP_PS1%" echo     } finally {
>> "%TEMP_PS1%" echo         if ($ptr -ne [IntPtr]::Zero) {
>> "%TEMP_PS1%" echo             [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr)
>> "%TEMP_PS1%" echo         }
>> "%TEMP_PS1%" echo     }
>> "%TEMP_PS1%" echo }
>> "%TEMP_PS1%" echo function Write-Backup {
>> "%TEMP_PS1%" echo     param([string]$Path)
>> "%TEMP_PS1%" echo     if (Test-Path -LiteralPath $Path) {
>> "%TEMP_PS1%" echo         $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
>> "%TEMP_PS1%" echo         $backup = "$Path.bak.$stamp"
>> "%TEMP_PS1%" echo         Copy-Item -LiteralPath $Path -Destination $backup -Force
>> "%TEMP_PS1%" echo         Write-Host "Backed up $Path -^> $backup"
>> "%TEMP_PS1%" echo     }
>> "%TEMP_PS1%" echo }
>> "%TEMP_PS1%" echo function Get-CodexProcesses {
>> "%TEMP_PS1%" echo     Get-CimInstance Win32_Process ^| Where-Object {
>> "%TEMP_PS1%" echo         $_.Name -match '^(Codex^|Code X)(\.exe)?$' -or
>> "%TEMP_PS1%" echo         $_.ExecutablePath -match '(?i)\\(Codex^|Code X)\.exe$' -or
>> "%TEMP_PS1%" echo         $_.CommandLine -match '(?i)\\(Codex^|Code X)\.exe\b'
>> "%TEMP_PS1%" echo     }
>> "%TEMP_PS1%" echo }
>> "%TEMP_PS1%" echo function Stop-CodexIfRunning {
>> "%TEMP_PS1%" echo     $codexProcesses = @(Get-CodexProcesses)
>> "%TEMP_PS1%" echo     if ($codexProcesses.Count -eq 0) { return }
>> "%TEMP_PS1%" echo     Write-Host 'Detected running Code X/Codex. Stopping it before updating config...'
>> "%TEMP_PS1%" echo     foreach ($process in $codexProcesses) {
>> "%TEMP_PS1%" echo         try {
>> "%TEMP_PS1%" echo             Stop-Process -Id $process.ProcessId -Force -ErrorAction Stop
>> "%TEMP_PS1%" echo         } catch {
>> "%TEMP_PS1%" echo             Write-Warning "Failed to stop process $($process.Name) (PID $($process.ProcessId)): $($_.Exception.Message)"
>> "%TEMP_PS1%" echo         }
>> "%TEMP_PS1%" echo     }
>> "%TEMP_PS1%" echo     Start-Sleep -Seconds 2
>> "%TEMP_PS1%" echo     $remaining = @(Get-CodexProcesses)
>> "%TEMP_PS1%" echo     if ($remaining.Count -gt 0) {
>> "%TEMP_PS1%" echo         throw "Unable to stop Code X/Codex automatically. Please close it manually and rerun."
>> "%TEMP_PS1%" echo     }
>> "%TEMP_PS1%" echo     Write-Host 'Code X/Codex has exited.'
>> "%TEMP_PS1%" echo }
>> "%TEMP_PS1%" echo $homeDir = $HOME
>> "%TEMP_PS1%" echo if (-not $homeDir) { $homeDir = $env:USERPROFILE }
>> "%TEMP_PS1%" echo if (-not $homeDir) { throw "Cannot determine user home directory." }
>> "%TEMP_PS1%" echo $codexDir = Join-Path $homeDir '.codex'
>> "%TEMP_PS1%" echo $configPath = Join-Path $codexDir 'config.toml'
>> "%TEMP_PS1%" echo $authPath = Join-Path $codexDir 'auth.json'
>> "%TEMP_PS1%" echo New-Item -ItemType Directory -Path $codexDir -Force ^| Out-Null
>> "%TEMP_PS1%" echo Stop-CodexIfRunning
>> "%TEMP_PS1%" echo Write-Backup -Path $configPath
>> "%TEMP_PS1%" echo Write-Backup -Path $authPath
>> "%TEMP_PS1%" echo $apiKeySecure = Read-Host 'Enter EveryGPT API key' -AsSecureString
>> "%TEMP_PS1%" echo $apiKey = ConvertTo-PlainText -SecureString $apiKeySecure
>> "%TEMP_PS1%" echo if ([string]::IsNullOrWhiteSpace($apiKey)) { throw "API key cannot be empty." }
>> "%TEMP_PS1%" echo $configText = @"
>> "%TEMP_PS1%" echo model_provider = "custom"
>> "%TEMP_PS1%" echo model = "gpt-5.5"
>> "%TEMP_PS1%" echo review_model = "gpt-5.5"
>> "%TEMP_PS1%" echo model_reasoning_effort = "xhigh"
>> "%TEMP_PS1%" echo disable_response_storage = true
>> "%TEMP_PS1%" echo network_access = "enabled"
>> "%TEMP_PS1%" echo.
>> "%TEMP_PS1%" echo [model_providers.custom]
>> "%TEMP_PS1%" echo name = "EveryGPT"
>> "%TEMP_PS1%" echo base_url = "https://api.everygpt.site/v1"
>> "%TEMP_PS1%" echo wire_api = "responses"
>> "%TEMP_PS1%" echo requires_openai_auth = true
>> "%TEMP_PS1%" echo.
>> "%TEMP_PS1%" echo [features]
>> "%TEMP_PS1%" echo goals = true
>> "%TEMP_PS1%" echo "@
>> "%TEMP_PS1%" echo $authJson = @{ OPENAI_API_KEY = $apiKey } ^| ConvertTo-Json -Depth 3
>> "%TEMP_PS1%" echo [System.IO.File]::WriteAllText($configPath, $configText, [System.Text.UTF8Encoding]::new($false))
>> "%TEMP_PS1%" echo [System.IO.File]::WriteAllText($authPath, "$authJson`n", [System.Text.UTF8Encoding]::new($false))
>> "%TEMP_PS1%" echo try { attrib +h $codexDir 2^>^$null ^| Out-Null } catch {}
>> "%TEMP_PS1%" echo Write-Host "Wrote config: $configPath"
>> "%TEMP_PS1%" echo Write-Host "Wrote auth:   $authPath"
>> "%TEMP_PS1%" echo Write-Host "Detected OS:  Windows"

"%POWERSHELL_EXE%" -NoProfile -ExecutionPolicy Bypass -File "%TEMP_PS1%"
set "EXIT_CODE=%ERRORLEVEL%"
del "%TEMP_PS1%" >nul 2>nul
echo.
if "%EXIT_CODE%"=="0" (
  echo Completed. Press any key to close.
) else (
  echo Failed with exit code %EXIT_CODE%. Press any key to close.
)
pause >nul
exit /b %EXIT_CODE%
