$ErrorActionPreference = "Stop"

$siteRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).ProviderPath
$python = "C:\Users\jason\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe"
$chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"
$port = 8793
$pdfPath = Join-Path $siteRoot "Resume_Jason_Eugene_Garrison.pdf"
$docxPath = Join-Path $siteRoot "Resume_Jason_Eugene_Garrison.docx"
$chromeProfile = Join-Path $env:TEMP ("resume-pdf-" + [Guid]::NewGuid().ToString("N"))

if (-not (Test-Path $python)) {
    throw "Bundled Python was not found at $python"
}

if (-not (Test-Path $chrome)) {
    throw "Chrome was not found at $chrome"
}

& $python (Join-Path $PSScriptRoot "generate-resume-docx.py") $siteRoot $docxPath
if ($LASTEXITCODE -ne 0) {
    throw "DOCX generation failed with exit code $LASTEXITCODE"
}

$server = $null
try {
    if (Test-Path -LiteralPath $pdfPath) {
        Remove-Item -LiteralPath $pdfPath -Force
    }

    $server = Start-Process -FilePath $python `
        -ArgumentList @("-m", "http.server", "$port", "--bind", "127.0.0.1", "--directory", $siteRoot) `
        -WorkingDirectory $env:TEMP `
        -WindowStyle Hidden `
        -PassThru

    $url = "http://127.0.0.1:$port/index.html?print=$(Get-Date -Format yyyyMMddHHmmss)"

    $ready = $false
    for ($i = 0; $i -lt 30; $i++) {
        try {
            $response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 2
            if ($response.StatusCode -eq 200 -and $response.Content -match "Jason Eugene Garrison") {
                $ready = $true
                break
            }
        } catch {
            Start-Sleep -Milliseconds 500
        }
    }

    if (-not $ready) {
        throw "Local resume preview server was not reachable at $url"
    }

    $chromeProcess = Start-Process -FilePath $chrome `
        -ArgumentList @(
            "--headless=new",
            "--disable-gpu",
            "--disable-background-networking",
            "--disable-sync",
            "--metrics-recording-only",
            "--no-first-run",
            "--no-default-browser-check",
            "--no-pdf-header-footer",
            "--user-data-dir=$chromeProfile",
            "--print-to-pdf=$pdfPath",
            $url
        ) `
        -Wait `
        -PassThru `
        -NoNewWindow

    if ($chromeProcess.ExitCode -ne 0) {
        throw "PDF generation failed with exit code $($chromeProcess.ExitCode)"
    }

    if (-not (Test-Path -LiteralPath $pdfPath) -or (Get-Item -LiteralPath $pdfPath).Length -lt 1024) {
        throw "PDF generation did not produce a valid output file."
    }
}
finally {
    if ($server -and -not $server.HasExited) {
        Stop-Process -Id $server.Id -Force
    }
    if (Test-Path -LiteralPath $chromeProfile) {
        Remove-Item -LiteralPath $chromeProfile -Recurse -Force
    }
}

& (Join-Path $PSScriptRoot "publish-permissions.ps1")

Write-Host "Updated $pdfPath"
Write-Host "Updated $docxPath"
