$ErrorActionPreference = 'Stop'

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

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

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')
}

if (-not (Test-Path $distDir)) {
    New-Item -ItemType Directory -Path $distDir | Out-Null
}

Set-Location $projectRoot

Write-Host 'Running go test ./...' -ForegroundColor Cyan
go test ./...

Write-Host "Building $outFile" -ForegroundColor Green
go build -o $outFile ./cmd/qctextbuilder

Write-Host "Build complete: $outFile" -ForegroundColor Green
