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

$ErrorActionPreference = 'Stop'
$BuildDir = [System.IO.Path]::GetFullPath($BuildDir)

function Assert-FileContains([string] $Path, [string] $Pattern, [string] $Description) {
    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
        throw "Missing generated version input: $Path"
    }
    $text = [System.IO.File]::ReadAllText($Path)
    if (-not [regex]::IsMatch($text, $Pattern)) {
        throw "$Description does not resolve to $ExpectedVersion in $Path"
    }
}

$escaped = [regex]::Escape($ExpectedVersion)
$commaVersion = [regex]::Escape(($ExpectedVersion -replace '\.', ',')) + ',0'
Assert-FileContains (Join-Path $BuildDir 'CMakeCache.txt') `
    ("(?m)^CMAKE_PROJECT_VERSION:STATIC=" + $escaped + "`r?$") 'CMake PROJECT_VERSION'
$parts=$ExpectedVersion.Split('.')
$versionCode='0x{0:x}' -f (([int]$parts[0] -shl 16)+([int]$parts[1] -shl 8)+[int]$parts[2])

foreach($target in @('DeepPluck','DeepPluckTests','DeepPluckToneAudit','DeepPluckBenchmark','DeepPluckPresetAudit','DeepPluckPresetGenerator','DeepPluckPresetAudition')) {
    $libraryCode=Join-Path $BuildDir "${target}_artefacts/JuceLibraryCode"
    Assert-FileContains (Join-Path $libraryCode 'Info.txt') `
        "(?:^|\x1e)VERSION\x1f$escaped\x1e" "$target JUCE target version"
    Assert-FileContains (Join-Path $libraryCode 'Info.txt') `
        "(?:^|\x1e)BUILD_VERSION\x1f$escaped\x1e" "$target JUCE build version"
    Assert-FileContains (Join-Path $libraryCode "${target}_resources.rc") `
        "FILEVERSION\s+$commaVersion\s" "$target Windows FileVersion input"
    Assert-FileContains (Join-Path $libraryCode "${target}_resources.rc") `
        "PRODUCTVERSION\s+$commaVersion\s" "$target Windows ProductVersion input"
    foreach ($configuration in @('Debug', 'Release')) {
        $definitions=Join-Path $libraryCode "$configuration/Defs.txt"
        Assert-FileContains $definitions ('JucePlugin_VersionString="'+$escaped+'"') "$target $configuration plugin version"
        Assert-FileContains $definitions ('JucePlugin_Version='+$escaped+';') "$target $configuration numeric plugin version"
        Assert-FileContains $definitions ('JucePlugin_VersionCode='+[regex]::Escape($versionCode)+';') "$target $configuration version code"
        Assert-FileContains $definitions "(?:^|\x1e)VERSION\x1f$escaped\x1e" "$target $configuration target version"
    }
}

Write-Host "PASS: all seven generated Debug and Release targets resolve exactly to $ExpectedVersion"
