[CmdletBinding()]
param(
    [string]$Dataset = "hessenPbf",
    [switch]$SkipHash,
    [switch]$ScanBlocks,
    [switch]$DecodeObjects,
    [switch]$BuildPreview
)

$ErrorActionPreference = "Stop"

$projectRoot = Split-Path -Parent $PSScriptRoot
$configPath = Join-Path $projectRoot "test-data\local-datasets.properties"
$applicationDir = Join-Path $projectRoot "application"
$gradleWrapper = Join-Path $applicationDir "gradlew.bat"
$projectCache = Join-Path $projectRoot ".gradle-project-cache"
$env:GRADLE_USER_HOME = Join-Path $projectRoot ".gradle-user"

if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) {
    throw "Lokale Konfiguration fehlt: $configPath"
}
if (-not $env:JAVA_HOME) {
    throw "JAVA_HOME ist nicht gesetzt. Bitte Microsoft OpenJDK 25 konfigurieren."
}

$properties = [System.Collections.Specialized.OrderedDictionary]::new()
$reader = [System.IO.File]::OpenText($configPath)
try {
    while (($line = $reader.ReadLine()) -ne $null) {
        $trimmed = $line.Trim()
        if (-not $trimmed -or $trimmed.StartsWith("#")) { continue }
        $separator = $trimmed.IndexOf("=")
        if ($separator -le 0) { continue }
        $key = $trimmed.Substring(0, $separator).Trim()
        $value = $trimmed.Substring($separator + 1).Trim().Replace("\\", "\")
        $properties[$key] = $value
    }
}
finally {
    $reader.Dispose()
}

if (-not $properties.Contains($Dataset)) {
    throw "Datensatz '$Dataset' ist in $configPath nicht eingetragen."
}

$datasetPath = [string]$properties[$Dataset]
if (-not (Test-Path -LiteralPath $datasetPath -PathType Leaf)) {
    throw "Testdatei nicht gefunden: $datasetPath"
}

$file = Get-Item -LiteralPath $datasetPath
Write-Output "Datensatz: $Dataset"
Write-Output "Datei: $($file.FullName)"
Write-Output "Größe: $($file.Length) Byte"
Write-Output "Geändert: $($file.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss'))"
if (-not $SkipHash) {
    $hash = Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256
    Write-Output "SHA-256: $($hash.Hash)"
}

$gradleTask = if ($BuildPreview) { ":core:previewPbf" } elseif ($DecodeObjects) { ":core:decodePbf" } elseif ($ScanBlocks) { ":core:scanPbf" } else { ":core:inspectPbf" }
$gradleArguments = @(
    "-p", $applicationDir,
    "--project-cache-dir", $projectCache,
    $gradleTask,
    "-PpbfFile=$($file.FullName)"
)
if ($ScanBlocks -and -not $DecodeObjects) {
    $indexFile = Join-Path $projectRoot "build\test-data-index\$Dataset.mtcidx"
    $gradleArguments += "-PindexFile=$indexFile"
}
& $gradleWrapper @gradleArguments
exit $LASTEXITCODE
