package de.arxsilex.maptools.converter.worker

import de.arxsilex.maptools.converter.core.GeoBounds
import java.nio.file.Files
import kotlin.io.path.createTempFile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class CropRequestTest {
    @Test
    fun `parses multiple disjoint selection areas and their envelope`() {
        val input = Files.createTempFile("crop-multi-input", ".osm.pbf")
        val output = input.resolveSibling("crop-multi-output.osm.pbf")
        try {
            val request = CropRequest.parse(
                arrayOf(
                    "crop", "--input", input.toString(), "--output", output.toString(),
                    "--areas", "7.0,49.0,7.2,49.2;8.0,50.0,8.3,50.4",
                ),
            )

            assertEquals(2, request.areas.size)
            assertEquals(GeoBounds(7.0, 49.0, 8.3, 50.4), request.bounds)
        } finally {
            Files.deleteIfExists(output)
            Files.deleteIfExists(input)
        }
    }
    @Test
    fun `parses validated crop request and builds complete dependency pipeline`() {
        val input = createTempFile(suffix = ".osm.pbf")
        val output = input.resolveSibling("result-${System.nanoTime()}.osm.pbf")
        try {
            val request = CropRequest.parse(
                arrayOf(
                    "crop", "--input", input.toString(), "--output", output.toString(),
                    "--cache-dir", output.resolveSibling("cache").toString(),
                    "--temp-dir", output.resolveSibling("session-temp").toString(),
                    "--west", "8.0", "--south", "50.0", "--east", "9.0", "--north", "51.0",
                ),
            )

            assertEquals(8.0, request.bounds.west)
            assertEquals(output.resolveSibling("session-temp"), request.temporaryDirectory)
            val osmosis = request.osmosisArguments(output.resolveSibling("temporary.pbf")).toList()
            assertTrue("completeWays=yes" in osmosis)
            assertTrue("completeRelations=yes" in osmosis)
            assertTrue("clipIncompleteEntities=false" in osmosis)
        } finally {
            Files.deleteIfExists(input)
        }
    }

    @Test
    fun `rejects output equal to input`() {
        val input = createTempFile(suffix = ".osm.pbf")
        try {
            assertFailsWith<IllegalArgumentException> {
                CropRequest.parse(
                    arrayOf(
                        "crop", "--input", input.toString(), "--output", input.toString(),
                        "--temp-dir", input.resolveSibling("session-temp").toString(),
                        "--west", "8", "--south", "50", "--east", "9", "--north", "51",
                    ),
                )
            }
        } finally {
            Files.deleteIfExists(input)
        }
    }
}
