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"
$reportPath = Join-Path $reportDirectory "toolchain.json"
New-Item -ItemType Directory -Force -Path $reportDirectory | Out-Null

$javaCommand = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME "bin\java.exe" } else { "java" }
$javaVersion = (& $javaCommand -version 2>&1 | Out-String).Trim()
$gradleVersion = (& (Join-Path $applicationDir "gradlew.bat") -p $applicationDir --version 2>&1 | Out-String).Trim()
$gradleVersion = $gradleVersion -replace '(?m)^Daemon JVM:\s+.*$', 'Daemon JVM: configured JDK (see java field)'

$androidStudioInfoPath = "C:\Program Files\Android\Android Studio\product-info.json"
$androidStudio = $null
if (Test-Path -LiteralPath $androidStudioInfoPath) {
    $productInfo = Get-Content -Raw -LiteralPath $androidStudioInfoPath | ConvertFrom-Json
    $androidStudio = [ordered]@{
        name = $productInfo.name
        buildNumber = $productInfo.buildNumber
        dataDirectoryName = $productInfo.dataDirectoryName
    }
}

$localArtifacts = @()
$localArtifactDirectory = Join-Path $applicationDir "worker\libs"
if (Test-Path -LiteralPath $localArtifactDirectory) {
    $localArtifacts = Get-ChildItem -LiteralPath $localArtifactDirectory -Filter "*.jar" -File | ForEach-Object {
        [ordered]@{
            name = $_.Name
            size = $_.Length
            sha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant()
        }
    }
}

$report = [ordered]@{
    schemaVersion = 1
    product = "ArxSilex MapTools Converter"
    version = $Version
    collectedAt = (Get-Date).ToUniversalTime().ToString("o")
    operatingSystem = [System.Runtime.InteropServices.RuntimeInformation]::OSDescription
    architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()
    powershell = $PSVersionTable.PSVersion.ToString()
    java = $javaVersion
    gradle = $gradleVersion
    androidStudio = $androidStudio
    localArtifacts = @($localArtifacts)
    baseline = "security/toolchain-baseline.yml"
}

$report | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $reportPath -Encoding utf8
Write-Host "Werkzeugkettenbericht erzeugt: $reportPath"
