$ErrorActionPreference = "Stop"

$projectRoot = Split-Path -Parent $PSScriptRoot
$targetDirectory = Join-Path $projectRoot "application\worker\libs"
$baseUrl = "https://github.com/mapsforge/mapsforge/releases/download/0.29.0"
$artifacts = @(
    @{
        Name = "mapsforge-map-writer-0.29.0-jar-with-dependencies.jar"
        Sha256 = "B507829B5A562BE32E4FAB14C8A76FFD45CEBE99F6999CC955DE3FCB4ED22DBF"
    },
    @{
        Name = "mapsforge-poi-writer-0.29.0-jar-with-dependencies.jar"
        Sha256 = "A414872BD994B025BB8402034A80ADD23CA3CDBDE72F716886794E3B8D2AD701"
    }
)

New-Item -ItemType Directory -Force -Path $targetDirectory | Out-Null

foreach ($artifact in $artifacts) {
    $target = Join-Path $targetDirectory $artifact.Name
    if (Test-Path -LiteralPath $target) {
        $existingHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $target).Hash
        if ($existingHash -eq $artifact.Sha256) {
            Write-Host "Abhängigkeit geprüft: $($artifact.Name)"
            continue
        }
        throw "Prüfsumme einer vorhandenen Abhängigkeit ist falsch: $target"
    }

    $temporary = "$target.download"
    try {
        Write-Host "Lade offizielle Mapsforge-Abhängigkeit: $($artifact.Name)"
        Invoke-WebRequest -UseBasicParsing -Uri "$baseUrl/$($artifact.Name)" -OutFile $temporary
        $downloadHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $temporary).Hash
        if ($downloadHash -ne $artifact.Sha256) {
            throw "Prüfsummenfehler für $($artifact.Name): $downloadHash"
        }
        Move-Item -LiteralPath $temporary -Destination $target
    } finally {
        if (Test-Path -LiteralPath $temporary) {
            Remove-Item -LiteralPath $temporary
        }
    }
}
