package de.arxsilex.maptools.converter.core.mtci

import de.arxsilex.maptools.converter.core.GeoBounds
import java.nio.file.Path

fun main(arguments: Array<String>) {
    require(arguments.size >= 6) {
        "Aufruf: MtciSpatialCli <mtci-verzeichnis> <west> <south> <east> <north> <bericht.json> [ausgabe-mtci]"
    }
    val directory = Path.of(arguments[0]).toAbsolutePath().normalize()
    val bounds = GeoBounds(
        west = arguments[1].toDouble(),
        south = arguments[2].toDouble(),
        east = arguments[3].toDouble(),
        north = arguments[4].toDouble(),
    )
    val report = Path.of(arguments[5]).toAbsolutePath().normalize()
    println("MTCI-SELECT phase=nodes status=started bounds=$bounds")
    val selection = MtciSpatialSelector.analyze(directory, bounds, onProgress = { progress ->
        println(
            "MTCI-SELECT phase=${progress.phase.name.lowercase()} " +
                "visited=${progress.visitedObjects} selected=${progress.selectedObjects}",
        )
    })
    MtciSpatialSelector.writeSummary(selection, report)
    println(
        "MTCI-SELECT status=completed elapsedMs=${selection.elapsedMillis} " +
            "nodesInside=${selection.nodesInsideBounds.size} requiredNodes=${selection.requiredNodeIds.size} " +
            "ways=${selection.selectedWayIds.size} relations=${selection.selectedRelationIds.size} report=$report",
    )
    arguments.getOrNull(6)?.let { materializedPath ->
        println("MTCI-MATERIALIZE status=started output=$materializedPath")
        val materialized = MtciSelectionMaterializer.materialize(
            sourceDirectory = directory,
            selection = selection,
            outputDirectory = Path.of(materializedPath),
            onProgress = { progress ->
                println(
                    "MTCI-MATERIALIZE phase=${progress.phase.name.lowercase()} " +
                        "written=${progress.writtenObjects}/${progress.expectedObjects}",
                )
            },
        )
        println(
            "MTCI-MATERIALIZE status=completed elapsedMs=${materialized.elapsedMillis} " +
                "bytes=${materialized.outputBytes} missingNodes=${materialized.missingSourceNodes} " +
                "missingWays=${materialized.missingSourceWays} missingRelations=${materialized.missingSourceRelations} " +
                "omittedRelationMembers=${materialized.omittedRelationMembers}",
        )
    }
}
