package xyz.cottongin.radio247.data.api

import android.net.Uri
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject

object SomaFmApi {
    private const val CHANNELS_URL = "https://somafm.com/channels.json"

    /**
     * Fetches live listener counts from SomaFM.
     * Returns a map of channel id (e.g. "groovesalad") to listener count.
     */
    suspend fun fetchListenerCounts(client: OkHttpClient): Map<String, Int> =
        withContext(Dispatchers.IO) {
            val request = Request.Builder()
                .url(CHANNELS_URL)
                .header("Accept", "application/json")
                .build()

            val response = client.newCall(request).execute()
            val body = response.use { it.body?.string() } ?: return@withContext emptyMap()

            val json = JSONObject(body)
            val channels = json.getJSONArray("channels")
            val result = mutableMapOf<String, Int>()

            for (i in 0 until channels.length()) {
                val channel = channels.getJSONObject(i)
                val id = channel.getString("id")
                val listeners = channel.optInt("listeners", 0)
                result[id] = listeners
            }
            result
        }

    /**
     * Extracts the SomaFM stream ID from a station URL.
     * e.g. "https://ice1.somafm.com/groovesalad-256-mp3" -> "groovesalad"
     */
    fun extractStreamId(stationUrl: String): String? {
        val path = Uri.parse(stationUrl).lastPathSegment ?: return null
        val id = path.substringBefore('-')
        return id.ifEmpty { null }
    }
}
