package com.radiola.data.local

import android.content.Context
import com.radiola.data.local.dto.LocalGroupDto
import com.radiola.data.local.dto.LocalStationsResponse
import com.radiola.domain.model.Station
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.serialization.json.Json
import java.io.BufferedReader
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class LocalStationDataSource @Inject constructor(
    @ApplicationContext private val context: Context,
    private val json: Json
) {

    private var cachedResponse: LocalStationsResponse? = null

    fun loadStations(): List<Station> {
        android.util.Log.d("LocalStationDS", "loadStations() called")
        val response = getResponse()
        android.util.Log.d("LocalStationDS", "Parsed: ${response.stations.size} stations, ${response.groups.size} groups")
        val groupMap = response.groups.associateBy { it.id }

        return response.stations
            .filter { it.enabled && !it.notWorked && it.stream != null }
            .map { dto ->
                val group = groupMap[dto.groupId]
                val prefix = generatePrefix(dto.name)
                // Определяем сеть: только станции Radio Record можно обогащать
                // обложками из Record API. Остальные сети — свой источник.
                val isRecord = dto.site?.contains("radiorecord", ignoreCase = true) == true
                Station(
                    id = dto.id,
                    name = dto.name,
                    prefix = prefix,
                    streamUrl = dto.stream!!,
                    coverUrl = StationLogos.forName(dto.name) ?: StationLogos.forSite(dto.site) ?: "",
                    genre = group?.name ?: "",
                    tags = listOfNotNull(group?.name?.takeIf { it.isNotBlank() }),
                    sortOrder = dto.id,
                    source = if (isRecord) "record" else "local",
                    qualities = dto.qualities.orEmpty().map {
                        com.radiola.domain.model.StreamQuality(it.bitrate, it.url, it.type)
                    }
                )
            }
    }

    fun loadGroups(): List<LocalGroupDto> {
        return getResponse().groups.filter { it.name.isNotBlank() }
    }

    fun getGroupNames(): List<String> {
        return loadGroups().map { it.name }
    }

    private fun getResponse(): LocalStationsResponse {
        android.util.Log.d("LocalStationDS", "getResponse() called")
        cachedResponse?.let { return it }
        val text = context.assets.open("stations.json").bufferedReader().use(BufferedReader::readText)
        val parsed = json.decodeFromString(LocalStationsResponse.serializer(), text)
        cachedResponse = parsed
        return parsed
    }

    private fun generatePrefix(name: String): String {
        return name.lowercase()
            .replace(Regex("[^a-z0-9а-яё]+"), "_")
            .trim('_')
            .take(30)
    }

    private fun generateCoverUrl(groupName: String, stationName: String): String {
        // Placeholder: return empty for now; Record API will override with real covers when available
        return ""
    }
}
