package xyz.cottongin.radio247.data.importing

object PlsParser {
    fun parse(content: String): List<ParsedStation> {
        val lines = content.replace("\r\n", "\n").split("\n")
        val entries = mutableMapOf<Int, MutableMap<String, String>>()

        for (line in lines) {
            val trimmed = line.trim()
            if (trimmed.isEmpty() || trimmed.equals("[playlist]", ignoreCase = true)) continue
            if (trimmed.startsWith("NumberOfEntries=", ignoreCase = true)) continue
            if (trimmed.startsWith("Version=", ignoreCase = true)) continue

            val eqIndex = trimmed.indexOf('=')
            if (eqIndex < 0) continue

            val key = trimmed.substring(0, eqIndex).trim()
            val value = trimmed.substring(eqIndex + 1).trim()

            val keyLower = key.lowercase()
            when {
                keyLower.startsWith("file") -> {
                    val num = parseIndex(keyLower, "file")
                    if (num != null) {
                        entries.getOrPut(num) { mutableMapOf() }["url"] = value
                    }
                }
                keyLower.startsWith("title") -> {
                    val num = parseIndex(keyLower, "title")
                    if (num != null) {
                        entries.getOrPut(num) { mutableMapOf() }["name"] = value
                    }
                }
            }
        }

        return entries.keys.sorted().mapNotNull { index ->
            val entry = entries[index]!!
            val url = (entry["url"] ?: return@mapNotNull null).trim()
            if (url.isBlank()) return@mapNotNull null
            val name = entry["name"] ?: deriveNameFromUrl(url)
            ParsedStation(name = name, url = url)
        }
    }

    private fun parseIndex(key: String, prefix: String): Int? {
        val suffix = key.removePrefix(prefix)
        return suffix.toIntOrNull()
    }
}
