param(
    [string]$Version
)

$ErrorActionPreference = "Stop"
$projectRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$applicationDir = Join-Path $projectRoot "application"
$gradleWrapper = Join-Path $applicationDir "gradlew.bat"
$projectCache = Join-Path $projectRoot ".gradle-project-cache-security"
$env:GRADLE_USER_HOME = Join-Path $projectRoot ".gradle-user"

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"
$kotlinCache = Join-Path $projectRoot "build-security\.kotlin"
New-Item -ItemType Directory -Force -Path $reportDirectory | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $kotlinCache "sessions") | Out-Null

& $gradleWrapper -p $applicationDir --no-daemon --no-parallel --project-cache-dir $projectCache `
    '-Pmaptools.buildRoot=../build-security' `
    "-Pkotlin.project.persistent.dir=$kotlinCache" `
    dependencyUpdates `
    '-Drevision=release' `
    '-DoutputFormatter=json' `
    "-DoutputDir=$reportDirectory" `
    '-DreportfileName=dependency-updates'
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

$reportPath = Join-Path $reportDirectory "dependency-updates.json"
if (-not (Test-Path -LiteralPath $reportPath)) {
    throw "Der Abhängigkeitsbericht wurde nicht erzeugt: $reportPath"
}

Write-Host "Abhängigkeitsbericht erzeugt: $reportPath"
