$ErrorActionPreference = 'Stop'

$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$envFile = Join-Path $projectRoot '.env.local'
$distDir = Join-Path $projectRoot 'dist'
$exeFile = Join-Path $distDir 'qctextbuilder.exe'

if (-not (Test-Path $envFile)) {
    throw "Missing .env.local at $envFile"
}

if (-not (Test-Path $exeFile)) {
    throw "Missing built executable at $exeFile. Run .\build-local.ps1 first."
}

Get-Content $envFile | ForEach-Object {
    $line = $_.Trim()
    if (-not $line -or $line.StartsWith('#')) { return }

    $parts = $line -split '=', 2
    if ($parts.Count -ne 2) { return }

    $name = $parts[0].Trim()
    $value = $parts[1]
    [System.Environment]::SetEnvironmentVariable($name, $value, 'Process')
}

Write-Host "Starting QC Text Builder on $env:HTTP_ADDR using $exeFile" -ForegroundColor Green
Set-Location $projectRoot

& $exeFile
