param(
    [double]$MinLineRate = 0.90,
    [double]$MinBranchRate = 0.70,
    [string]$ResultsRoot = "RpgRoller.Tests/TestResults"
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

if (-not (Test-Path $ResultsRoot)) {
    throw "Coverage results folder not found: $ResultsRoot"
}

$coverageFile = Get-ChildItem -Path $ResultsRoot -Recurse -Filter "coverage.cobertura.xml" |
    Sort-Object LastWriteTimeUtc -Descending |
    Select-Object -First 1

if ($null -eq $coverageFile) {
    throw "No coverage.cobertura.xml found under $ResultsRoot"
}

[xml]$xml = Get-Content -Path $coverageFile.FullName
$coverage = $xml.coverage

if ($null -eq $coverage) {
    throw "Coverage XML is missing root coverage node: $($coverageFile.FullName)"
}

[double]$lineRate = [double]$coverage.'line-rate'
[double]$branchRate = [double]$coverage.'branch-rate'

$linePercent = [Math]::Round($lineRate * 100, 2)
$branchPercent = [Math]::Round($branchRate * 100, 2)
$minLinePercent = [Math]::Round($MinLineRate * 100, 2)
$minBranchPercent = [Math]::Round($MinBranchRate * 100, 2)

Write-Host "Coverage source: $($coverageFile.FullName)"
Write-Host ("Line coverage:   {0}% (required >= {1}%)" -f $linePercent, $minLinePercent)
Write-Host ("Branch coverage: {0}% (required >= {1}%)" -f $branchPercent, $minBranchPercent)

if ($lineRate -lt $MinLineRate -or $branchRate -lt $MinBranchRate) {
    throw "Coverage thresholds failed."
}
