param(
    [string]$AgentRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path,
    [string]$ProgId = "AutoCAD.Application.23.1",
    [int]$PollMs = 1000
)

$ErrorActionPreference = "Stop"
$bridgeProject = Join-Path $AgentRoot "tools\drawing-diagnostics\AutoCadDwgBridge\AutoCadDwgBridge.csproj"
$bridgeDll = Join-Path $AgentRoot "tools\drawing-diagnostics\AutoCadDwgBridge\bin\Debug\net10.0\AutoCadDwgBridge.dll"
$extractorDll = Join-Path $AgentRoot "tools\drawing-diagnostics\AutoCadDwgExtractor\bin\Debug\net10.0\AutoCadDwgExtractor.dll"
$queueDir = Join-Path $AgentRoot "runtime\dwg-draft\bridge"

if (-not (Test-Path $bridgeDll) -or -not (Test-Path $extractorDll)) {
    dotnet build $bridgeProject
    dotnet build (Join-Path $AgentRoot "tools\drawing-diagnostics\AutoCadDwgExtractor\AutoCadDwgExtractor.csproj")
}

try {
    $acad = [Runtime.InteropServices.Marshal]::GetActiveObject($ProgId)
    Write-Host "AutoCAD COM active: $($acad.Name)"
}
catch {
    Write-Warning "AutoCAD COM is not active for $ProgId. Open AutoCAD in this same desktop user session before submitting extraction jobs."
}

dotnet $bridgeDll `
    --agent-root $AgentRoot `
    --queue-dir $queueDir `
    --extractor-dll $extractorDll `
    --prog-id $ProgId `
    --poll-ms $PollMs
