package com.correx.core.tasks

/**
 * A task reference parsed from a commit message: the task key, and whether it was named with a
 * closing keyword (close/fix/resolve …) — which drives the task to DONE rather than IN_PROGRESS.
 */
data class CommitTaskRef(val key: String, val closing: Boolean)

/**
 * Extracts task references from a commit message. A closing keyword before a key ("fixes auth-12")
 * marks it closing; any other key mention ("see auth-12") is a plain reference; the closing form
 * wins when a key appears both ways. Keys are matched loosely (`<word>-<n>`), which is safe because
 * [GitTaskSync] only acts on keys that resolve to a real task — unknown matches are ignored.
 */
object CommitTaskParser {
    private const val KEY = "[A-Za-z][A-Za-z0-9_]*-\\d+"
    private val CLOSING = Regex("(?i)\\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\b\\s+#?($KEY)")
    private val MENTION = Regex("\\b($KEY)\\b")

    fun parse(message: String): List<CommitTaskRef> {
        val byKey = LinkedHashMap<String, Boolean>()
        CLOSING.findAll(message).forEach { byKey[it.groupValues[1]] = true }
        MENTION.findAll(message).forEach { byKey.putIfAbsent(it.groupValues[1], false) }
        return byKey.map { (key, closing) -> CommitTaskRef(key, closing) }
    }
}
