package xyz.cottongin.radio247.data.importing

object M3uParser {
    fun parse(content: String): List<ParsedStation> {
        val result = mutableListOf<ParsedStation>()
        val lines = content.replace("\r\n", "\n").split("\n")

        var currentName: String? = null
        var currentArtworkUrl: String? = null

        for (line in lines) {
            val trimmed = line.trim()
            when {
                trimmed.isEmpty() -> continue
                trimmed == "#EXTM3U" -> continue
                trimmed.startsWith("#EXTINF:") -> {
                    val commaIndex = trimmed.indexOf(',')
                    currentName = if (commaIndex >= 0 && commaIndex < trimmed.length - 1) {
                        trimmed.substring(commaIndex + 1).trim()
                    } else {
                        null
                    }
                }
                trimmed.startsWith("#EXTIMG:") -> {
                    currentArtworkUrl = trimmed.substring(8).trim().takeIf { it.isNotEmpty() }
                }
                trimmed.startsWith("#") -> continue
                else -> {
                    val url = trimmed
                    if (url.isBlank()) continue
                    val name = currentName ?: deriveNameFromUrl(url)
                    result.add(ParsedStation(name = name, url = url, artworkUrl = currentArtworkUrl))
                    currentName = null
                    currentArtworkUrl = null
                }
            }
        }

        return result
    }
}
