package dev.stave.lyrics
/**
* Parser for the LRC subtitle format as used by LRCLIB.
*
* Handles standard `[mm:ss.xx]text` lines, multi-timestamp lines
* (`[00:12.34][00:45.67]chorus`) which expand into multiple LrcLines with the same
* text, metadata tags (`[ar:…]`, `[ti:…]`) which are discarded, and malformed lines
* which are silently skipped.
*
* Returns lines sorted ascending by timestamp.
*/
object LrcParser {
// `[mm:ss.xx]` or `[mm:ss.xxx]`. mm can be 2+ digits for tracks over 99 minutes.
private val TIMESTAMP = Regex("""\[(\d{1,3}):(\d{2})(?:\.(\d{1,3}))?\]""")
// `[ar:…]`, `[ti:…]`, `[length:…]` — metadata tags we discard.
private val META_TAG = Regex("""\[[a-zA-Z]+:[^\]]*\]""")
fun parse(lrc: String): List<LrcLine> {
val out = mutableListOf<LrcLine>()
for (raw in lrc.lineSequence()) {
val line = raw.trim()
if (line.isBlank() || META_TAG.matchEntire(line) != null) continue
val stamps = TIMESTAMP.findAll(line).toList()
if (stamps.isEmpty()) continue
// Text is whatever comes after the last timestamp on the line.
val lastStamp = stamps.last()
val text = line.substring(lastStamp.range.last + 1).trim()
// Skip lines with empty text — some sources pad with empty timestamp
// markers to align timing with instrumental sections.
if (text.isBlank()) continue
for (m in stamps) {
val mm = m.groupValues[1].toIntOrNull() ?: continue
val ss = m.groupValues[2].toIntOrNull() ?: continue
val fracStr = m.groupValues[3]
// Normalize fractional to 3 digits. "34" → 340, "345" → 345, "" → 0.
val frac = if (fracStr.isBlank()) 0 else {
val padded = fracStr.padEnd(3, '0').take(3)
padded.toIntOrNull() ?: 0
}
val millis = (mm * 60_000L) + (ss * 1000L) + frac.toLong()
if (millis >= 0) out.add(LrcLine.at(millis, text))
}
}
return out.sortedBy { it.start }
}
}