package dev.castarr.tv.data

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

/**
 * Resolves club crests at runtime from Wikipedia's page summary. The badges
 * are trademarks, so they are fetched and cached on the device rather than
 * shipped with the app — nothing copyrighted lives in the repository.
 */
class Crests(context: Context) {

    private val prefs = context.getSharedPreferences("crests", Context.MODE_PRIVATE)

    /** Cached crest URL for a club, fetched once and then reused. */
    suspend fun urlFor(article: String): String? = withContext(Dispatchers.IO) {
        prefs.getString(article, null)?.takeIf { it.isNotEmpty() }?.let {
            return@withContext it
        }
        val resolved = runCatching { fetch(article) }
            .onFailure { Log.w(TAG, "crest lookup failed for $article: $it") }
            .getOrNull()
        if (resolved != null) {
            Log.i(TAG, "crest for $article: $resolved")
            prefs.edit().putString(article, resolved).apply()
        } else {
            // Deliberately not cached: a single failed lookup (no network
            // yet at start-up) must not hide the crest forever.
            Log.w(TAG, "no crest for $article")
        }
        resolved
    }

    private fun fetch(article: String): String? {
        val encoded = URLEncoder.encode(article, "UTF-8").replace("+", "%20")
        val connection = URL("$SUMMARY$encoded").openConnection() as HttpURLConnection
        return try {
            connection.connectTimeout = 10_000
            connection.readTimeout = 10_000
            connection.setRequestProperty("User-Agent", USER_AGENT)
            connection.setRequestProperty("Accept", "application/json")
            val body = connection.inputStream.bufferedReader().use { it.readText() }
            JSONObject(body).optJSONObject("thumbnail")?.optString("source")
                ?.takeIf { it.isNotEmpty() }
                // Drop the analytics query the API appends.
                ?.substringBefore("?")
        } finally {
            connection.disconnect()
        }
    }

    private companion object {
        const val TAG = "Crests"
        const val SUMMARY = "https://de.wikipedia.org/api/rest_v1/page/summary/"
        const val USER_AGENT = "Castarr TV (private use)"
    }
}
