package com.example.notesai.util

/**
 * Utility untuk convert markdown text ke plain text
 */
object MarkdownStripper {

    /**
     * Strip semua markdown formatting dan return plain text
     */
    fun stripMarkdown(text: String): String {
        var result = text

        // 1. Remove code blocks (```...```)
        result = result.replace(Regex("""```[\s\S]*?```"""), "")

        // 2. Remove inline code (`...`)
        result = result.replace(Regex("""`([^`]+)`"""), "$1")

        // 3. Remove bold (**...**)
        result = result.replace(Regex("""\*\*([^*]+)\*\*"""), "$1")

        // 4. Remove italic (*...*)
        result = result.replace(Regex("""\*([^*]+)\*"""), "$1")

        // 5. Remove strikethrough (~~...~~)
        result = result.replace(Regex("""~~([^~]+)~~"""), "$1")

        // 6. Remove headers (# ## ### etc)
        result = result.replace(Regex("""^#{1,6}\s+""", RegexOption.MULTILINE), "")

        // 7. Remove links [text](url) → text
        result = result.replace(Regex("""\[([^\]]+)\]\([^)]+\)"""), "$1")

        // 8. Remove images ![alt](url) → alt
        result = result.replace(Regex("""!\[([^\]]*)\]\([^)]+\)"""), "$1")

        // 9. Remove horizontal rules (---, ***, ___)
        result = result.replace(Regex("""^[-*_]{3,}$""", RegexOption.MULTILINE), "")

        // 10. Remove blockquotes (> ...)
        result = result.replace(Regex("""^>\s+""", RegexOption.MULTILINE), "")

        // 11. Remove unordered list markers (-, *, +)
        result = result.replace(Regex("""^[\s]*[-*+]\s+""", RegexOption.MULTILINE), "")

        // 12. Remove ordered list markers (1. 2. 3.)
        result = result.replace(Regex("""^[\s]*\d+\.\s+""", RegexOption.MULTILINE), "")

        // 13. Clean up extra whitespace
        result = result.replace(Regex("""\n{3,}"""), "\n\n") // Max 2 consecutive newlines
        result = result.trim()

        return result
    }

    /**
     * Get preview text (first N characters, stripped)
     */
    fun getPlainPreview(text: String, maxLength: Int = 100): String {
        val plain = stripMarkdown(text)
        return if (plain.length > maxLength) {
            plain.take(maxLength).trim() + "..."
        } else {
            plain
        }
    }
}