package xyz.cottongin.radio247.service

import xyz.cottongin.radio247.data.db.StationPreferenceDao
import xyz.cottongin.radio247.data.db.StationStreamDao
import xyz.cottongin.radio247.data.model.Station
import xyz.cottongin.radio247.data.prefs.RadioPreferences
import kotlinx.coroutines.flow.first
import org.json.JSONArray

class StreamResolver(
    private val streamDao: StationStreamDao,
    private val preferences: RadioPreferences,
    private val stationPreferenceDao: StationPreferenceDao
) {
    /**
     * Returns an ordered list of stream URLs to try for the given station.
     * For SomaFM stations: orders by quality preference (per-station or global).
     * For user-added stations: returns the single stored URL.
     */
    suspend fun resolveUrls(station: Station): List<String> {
        val streams = streamDao.getStreamsForStation(station.id)
        if (streams.isEmpty()) return listOf(station.url)

        val pref = stationPreferenceDao.getByStationId(station.id)
        val qualityJson = pref?.qualityOverride
            ?: station.qualityOverride
            ?: preferences.qualityPreference.first()
        val order = parseOrder(qualityJson)
        val sorted = streams.sortedBy { stream ->
            val key = "${stream.bitrate}-${if (stream.ssl) "ssl" else "nossl"}"
            val idx = order.indexOf(key)
            if (idx >= 0) idx else Int.MAX_VALUE
        }
        return sorted.map { it.url }
    }

    private fun parseOrder(json: String): List<String> {
        return try {
            val arr = JSONArray(json)
            (0 until arr.length()).map { arr.getString(it) }
        } catch (_: Exception) {
            DEFAULT_ORDER
        }
    }

    companion object {
        val DEFAULT_ORDER = listOf("256-ssl", "256-nossl", "128-ssl", "128-nossl")
        val DEFAULT_ORDER_JSON = JSONArray(DEFAULT_ORDER).toString()
    }
}
