@file:OptIn(InternalSerializationApi::class)

package aza.instant

import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.parameter
import io.ktor.http.HttpHeaders
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class NominatimResponse(val display_name: String, val address: Address)
@Serializable
data class Address(
    val quarter: String? = null,
    val city: String? = null,
    val state: String? = null,
    val province: String? = null,
    val country: String? = null,
)

private val client = HttpClient(CIO) { // Use the engine you prefer
    install(ContentNegotiation) {
        json(Json {
            ignoreUnknownKeys = true
            isLenient = true
        })
    }
}

suspend fun getAddress(latitude: Double, longitude: Double): NominatimResponse? {
    return client.get("https://nominatim.openstreetmap.org/reverse") {
        parameter("lat", latitude)
        parameter("lon", longitude)
        parameter("format", "jsonv2")
        header(HttpHeaders.AcceptLanguage, "en-US")
    }.body()
}