package de.hackernet.wireguardtv.util

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL

/**
 * Service zum Abrufen der öffentlichen IP und Geolocation
 */
object IpGeoService {
    private const val TAG = "IpGeoService"

    data class IpInfo(
        val ip: String,
        val countryCode: String,
        val countryName: String,
        val city: String? = null
    ) {
        val flag: String
            get() = countryCodeToFlag(countryCode)
    }

    /**
     * Holt die öffentliche IP und Geo-Infos
     * Nutzt ip-api.com (kostenlos, kein API-Key nötig)
     */
    suspend fun getPublicIpInfo(): IpInfo? = withContext(Dispatchers.IO) {
        try {
            val url = URL("http://ip-api.com/json/?fields=status,country,countryCode,city,query")
            val connection = url.openConnection() as HttpURLConnection
            connection.connectTimeout = 5000
            connection.readTimeout = 5000
            connection.requestMethod = "GET"

            if (connection.responseCode == 200) {
                val response = connection.inputStream.bufferedReader().readText()
                val json = JSONObject(response)

                if (json.getString("status") == "success") {
                    IpInfo(
                        ip = json.getString("query"),
                        countryCode = json.getString("countryCode"),
                        countryName = json.getString("country"),
                        city = json.optString("city", null)
                    )
                } else {
                    null
                }
            } else {
                null
            }
        } catch (e: Exception) {
            Log.e(TAG, "Fehler beim Abrufen der IP-Info: ${e.message}")
            null
        }
    }

    /**
     * Konvertiert einen 2-Buchstaben Ländercode in ein Emoji-Flag
     * z.B. "DE" -> "🇩🇪", "US" -> "🇺🇸"
     */
    private fun countryCodeToFlag(countryCode: String): String {
        if (countryCode.length != 2) return ""

        val firstChar = Character.codePointAt(countryCode.uppercase(), 0) - 0x41 + 0x1F1E6
        val secondChar = Character.codePointAt(countryCode.uppercase(), 1) - 0x41 + 0x1F1E6

        return String(Character.toChars(firstChar)) + String(Character.toChars(secondChar))
    }
}
