$ErrorActionPreference = "Stop"
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$downloads = Join-Path ([Environment]::GetFolderPath("UserProfile")) "Downloads"
New-Item -ItemType Directory -Force -Path $downloads | Out-Null
Set-Location $repoRoot

Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Upstage Solar 자동 검증 데모" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host "Upstage Studio의 Secret key를 한 번 붙여넣으면 나머지는 자동으로 진행됩니다."
Write-Host "키는 화면, 파일, GitHub, 결과 영수증에 저장되지 않습니다."
Write-Host "완료 결과는 Downloads 폴더에 자동 저장됩니다."
Write-Host ""

$secureKey = Read-Host "Upstage Studio Secret key 붙여넣기" -AsSecureString
$plainKey = [System.Net.NetworkCredential]::new("", $secureKey).Password
if ([string]::IsNullOrWhiteSpace($plainKey)) {
    throw "Secret key가 비어 있습니다."
}

try {
    $env:UPSTAGE_API_KEY = $plainKey
    $env:DEMO_ALLOW_SAMPLE = "0"

    if (Get-Command py -ErrorAction SilentlyContinue) {
        & py -3 scripts/live_e2e_runner.py --repackage --export-dir $downloads --serve-seconds 1800
    }
    elseif (Get-Command python -ErrorAction SilentlyContinue) {
        & python scripts/live_e2e_runner.py --repackage --export-dir $downloads --serve-seconds 1800
    }
    else {
        throw "Python 3.11 이상을 찾지 못했습니다."
    }
    if ($LASTEXITCODE -ne 0) {
        throw "자동 검증이 실패했습니다. 위 오류문을 확인해 주세요."
    }
}
finally {
    Remove-Item Env:UPSTAGE_API_KEY -ErrorAction SilentlyContinue
    Remove-Item Env:DEMO_ALLOW_SAMPLE -ErrorAction SilentlyContinue
    $plainKey = $null
    $secureKey = $null
}
