[CmdletBinding()]
param(
    [string]$Root = ""
)

$ErrorActionPreference = "Stop"
if ([string]::IsNullOrWhiteSpace($Root)) {
    $Root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
}
$started = Get-Date
$pattern = '\b(?:GL|WGL)_[A-Z0-9_]+\b'
$allowed = @(
    "src/renderer_gl/",
    "src/rtt.cpp",
    "src/texture.cpp"
)
$violations = @()
$files = Get-ChildItem -Path (Join-Path $Root "src") -Recurse -File -Include *.c,*.cc,*.cpp,*.h,*.hpp

foreach ($file in $files) {
    $relative = $file.FullName.Substring($Root.Length).TrimStart('\', '/').Replace('\', '/')
    $isAllowed = $false
    foreach ($prefix in $allowed) {
        if ($relative.StartsWith($prefix)) {
            $isAllowed = $true
            break
        }
    }
    if ($isAllowed) {
        continue
    }

    $lineNumber = 0
    foreach ($line in Get-Content -LiteralPath $file.FullName) {
        $lineNumber += 1
        $trimmed = $line.TrimStart()
        if ($trimmed.StartsWith("//")) {
            continue
        }
        $matches = [regex]::Matches($line, $pattern)
        foreach ($match in $matches) {
            $violations += [ordered]@{
                file = $relative
                line = $lineNumber
                token = $match.Value
            }
        }
    }
}

$exitCode = if ($violations.Count -eq 0) { 0 } else { 1 }
$elapsed = [int]((Get-Date) - $started).TotalMilliseconds

[ordered]@{
    command = "check-renderer-boundary"
    exitCode = $exitCode
    violationCount = $violations.Count
    violations = @($violations | Select-Object -First 50)
    elapsedMs = $elapsed
} | ConvertTo-Json -Compress -Depth 4

exit $exitCode
