param(
    [Parameter(Mandatory = $true)]
    [string]$CandidateViewsJson,

    [Parameter(Mandatory = $true)]
    [string]$OutputRoot,

    [string]$ExtractorProject = "tools\drawing-diagnostics\AutoCadDwgExtractor\AutoCadDwgExtractor.csproj",

    [string]$ProgId = "AutoCAD.Application.23.1",

    [int]$MaxEntities = 200000,

    [switch]$Visible
)

$ErrorActionPreference = "Stop"

$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..\..\..")
$candidateViewsPath = Resolve-Path $CandidateViewsJson
$outputRootPath = New-Item -ItemType Directory -Force -Path $OutputRoot
$extractorPath = Join-Path $repoRoot $ExtractorProject

Write-Host "Building AutoCAD extractor..."
dotnet build $extractorPath | Out-Host
if ($LASTEXITCODE -ne 0) {
    throw "AutoCAD extractor build failed."
}

$extractorProjectDir = Split-Path -Parent $extractorPath
$extractorBuildDir = Join-Path -Path $extractorProjectDir -ChildPath "bin\Debug"
$extractorDll = Get-ChildItem -Path $extractorBuildDir -Recurse -Filter "AutoCadDwgExtractor.dll" |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1
if (-not $extractorDll) {
    throw "AutoCadDwgExtractor.dll not found."
}
Write-Host "Using extractor: $($extractorDll.FullName)"

$candidates = Get-Content -LiteralPath $candidateViewsPath -Raw | ConvertFrom-Json
$exported = @($candidates | Where-Object { $_.dwg_path -and (Test-Path -LiteralPath $_.dwg_path) })
$total = $exported.Count
$current = 0

foreach ($candidate in $exported) {
    $current++
    $name = if ($candidate.name) { $candidate.name } else { "candidate_$($candidate.index)" }
    $safeName = ($name -replace '[\\/:*?"<>|]', '_')
    $candidateOutput = Join-Path $outputRootPath.FullName ("{0:D2}_{1}" -f [int]$candidate.index, $safeName)
    New-Item -ItemType Directory -Force -Path $candidateOutput | Out-Null
    $signaturePath = Join-Path $candidateOutput "main-view-signature.json"
    $logPath = Join-Path $candidateOutput "extractor.log"

    if (Test-Path -LiteralPath $signaturePath) {
        Write-Host "[$current/$total] signature exists, skip: $signaturePath"
        continue
    }

    Write-Host "[$current/$total] extracting candidate DWG: $($candidate.dwg_path)"
    & dotnet $extractorDll.FullName `
        --drawing-path $candidate.dwg_path `
        --output-dir $candidateOutput `
        --prog-id $ProgId `
        --visible $Visible.IsPresent `
        --close-after-extract true `
        --max-entities $MaxEntities `
        --main-view-seed-mode solidworks-candidate *> $logPath
    if ($LASTEXITCODE -ne 0) {
        throw "Candidate $($candidate.index) extraction failed. See log: $logPath"
    }
    if (-not (Test-Path -LiteralPath $signaturePath)) {
        throw "Candidate $($candidate.index) did not produce signature: $signaturePath"
    }
    Write-Host "[$current/$total] extraction completed: $candidateOutput"
}

@{
    ok = $true
    candidate_views_json = $candidateViewsPath.Path
    output_root = $outputRootPath.FullName
    extracted_count = $exported.Count
} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $outputRootPath.FullName "batch-summary.json") -Encoding UTF8
