param(
    [string]$Version
)

$ErrorActionPreference = "Stop"
$projectRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$applicationDir = Join-Path $projectRoot "application"

if (-not $Version) {
    $versionLine = Get-Content (Join-Path $applicationDir "gradle.properties") |
        Where-Object { $_ -match '^maptoolsVersion=' } |
        Select-Object -First 1
    if (-not $versionLine) { throw "maptoolsVersion fehlt in application/gradle.properties." }
    $Version = ($versionLine -split '=', 2)[1].Trim()
}

$reportDirectory = Join-Path $projectRoot "security\reports\$Version"
$releaseSecurityDirectory = Join-Path $projectRoot "release\$Version\security"
$platforms = @("windows-x64", "linux-x64")

& (Join-Path $PSScriptRoot "audit-dependencies.ps1") -Version $Version
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& (Join-Path $PSScriptRoot "collect-toolchain.ps1") -Version $Version
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

foreach ($platform in $platforms) {
    $sbomPath = Join-Path $reportDirectory "ArxSilex-MapTools-Converter-$Version-$platform.cdx.json"
    $osvReport = Join-Path $reportDirectory "ArxSilex-MapTools-Converter-$Version-$platform-osv.json"
    if (-not (Test-Path -LiteralPath $sbomPath)) {
        throw "SBOM fehlt für ${platform}: $sbomPath"
    }
    & (Join-Path $PSScriptRoot "audit-sbom.ps1") -SbomPath $sbomPath -ReportPath $osvReport
}

New-Item -ItemType Directory -Force -Path $releaseSecurityDirectory | Out-Null
Copy-Item -LiteralPath (Join-Path $reportDirectory "dependency-updates.json") -Destination $releaseSecurityDirectory -Force
Copy-Item -LiteralPath (Join-Path $reportDirectory "toolchain.json") -Destination $releaseSecurityDirectory -Force
foreach ($platform in $platforms) {
    Copy-Item -LiteralPath (Join-Path $reportDirectory "ArxSilex-MapTools-Converter-$Version-$platform.cdx.json") -Destination $releaseSecurityDirectory -Force
    Copy-Item -LiteralPath (Join-Path $reportDirectory "ArxSilex-MapTools-Converter-$Version-$platform-osv.json") -Destination $releaseSecurityDirectory -Force
}
if (Test-Path -LiteralPath (Join-Path $reportDirectory "toolchain-linux.txt")) {
    Copy-Item -LiteralPath (Join-Path $reportDirectory "toolchain-linux.txt") -Destination $releaseSecurityDirectory -Force
}

Write-Host "Release-Sicherheitsprüfung erfolgreich: $releaseSecurityDirectory"
