/*
 * Copyright (C) 2026 Memby contributors
 *
 * SPDX-License-Identifier: GPL-2.0-only
 */

package com.ponzischeme89.memby.ui.settings

/** One release as the About page shows it. */
internal data class ReleaseNote(
    val version: String,
    val date: String,
    val changes: List<String>,
)

private val HeadingPattern = Regex("""^##\s+v?(\d+\.\d+\.\d+)\s*(?:[—–-]\s*(.+))?$""")

/**
 * Parses CHANGELOG.md into the release list. Pure so it can be unit-tested, and
 * deliberately forgiving: anything that is not a `## <version>` heading or a `- ` bullet
 * under one is prose (the file's own format notes) and is skipped rather than rendered.
 *
 * Order is the file's own — newest first by convention, never re-sorted here, because a
 * version string is not reliably comparable once a release carries a suffix.
 */
internal fun parseChangelog(markdown: String): List<ReleaseNote> {
    val releases = mutableListOf<ReleaseNote>()
    var version: String? = null
    var date = ""
    var changes = mutableListOf<String>()

    fun flush() {
        version?.let { releases += ReleaseNote(it, date, changes.toList()) }
    }

    markdown.lineSequence().forEach { rawLine ->
        val line = rawLine.trim()
        val heading = HeadingPattern.find(line)
        when {
            heading != null -> {
                flush()
                version = heading.groupValues[1]
                date = heading.groupValues[2].trim()
                changes = mutableListOf()
            }
            version == null -> Unit
            line.startsWith("- ") || line.startsWith("* ") -> changes += line.drop(2).trim()
            // A wrapped bullet continues the previous one rather than starting a new
            // entry: the file is written to a column width, not to one line per change.
            line.isNotEmpty() && changes.isNotEmpty() ->
                changes[changes.lastIndex] = "${changes.last()} $line"
        }
    }
    flush()
    return releases
}

/** The catalogue Memby ships with, parsed once. */
internal val MembyReleaseHistory: List<ReleaseNote> by lazy {
    parseChangelog(com.ponzischeme89.memby.BuildConfig.CHANGELOG_TEXT)
}
