package eu.gaudian.translator.utils

object StringHelper {
    // Strict sentence detection: starts with capital, ends with . ! ?, and contains a space
    fun isSentenceStrict(text: String): Boolean {
        val trimmed = text.trim()
        if (trimmed.isEmpty()) return false
        val startsWithCapital = trimmed.first().isUpperCase()
        val endsWithPunctuation = trimmed.endsWith('.') || trimmed.endsWith('!') || trimmed.endsWith('?')
        val hasMultipleWords = trimmed.contains(" ")
        return hasMultipleWords && startsWithCapital && endsWithPunctuation
    }

    // Loose sentence detection for exercises: either looks like a sentence or is very long
    fun isSentenceLoose(text: String): Boolean {
        val trimmed = text.trim()
        if (trimmed.isEmpty()) return false
        val hasMultipleWords = trimmed.contains(" ")
        val endsWithPunctuation = trimmed.endsWith('.') || trimmed.endsWith('!') || trimmed.endsWith('?')
        val tooLong = trimmed.length > 15
        return (hasMultipleWords && endsWithPunctuation) || tooLong
    }

    // Build a regex to remove any of the provided leading articles followed by space
    @Suppress("HardCodedStringLiteral", "RegExpUnnecessaryNonCapturingGroup")
    fun buildLeadingArticlesRegex(articles: Collection<String>): Regex {
        val cleaned = articles.filter { it.isNotBlank() }.joinToString("|") { Regex.escape(it.trim()) }
        return if (cleaned.isEmpty()) Regex("^$") else Regex("^(?:$cleaned)\\s+", RegexOption.IGNORE_CASE)
    }

    fun removeLeadingArticles(text: String, articles: Collection<String>): String {
        val pattern = buildLeadingArticlesRegex(articles)
        return text.replace(pattern, "")
    }

    fun removeLeadingArticlesOneOf(text: String, articles: Collection<String>): String {
        // remove only the first matching leading article once
        val pattern = buildLeadingArticlesRegex(articles)
        return text.replaceFirst(pattern, "")
    }

    // Normalize answers: lowercase, trim, remove parenthetical info
    fun normalizeAnswer(answer: String): String {
        @Suppress("HardCodedStringLiteral")
        return answer.lowercase().trim().replace(Regex("\\s*\\(.*?\\)"), "").trim()
    }

    fun possibleAnswersFromSlash(answer: String): List<String> {
        return answer.split('/').map { it.trim() }.filter { it.isNotEmpty() }
    }
}