package com.a2i.forwarder.core

object CodeExtractor {
    private val patterns = listOf(
        Regex("""(?:验证码|校验码|动态码|验证代码|verification code|\bcode\b|密码|passcode|pin)\D{0,8}?(\d{4,8})""", RegexOption.IGNORE_CASE),
        Regex("""(\d{4,8})\D{0,4}(?:验证码|校验码|动态码|验证代码|code)""", RegexOption.IGNORE_CASE),
        Regex("""(\d{4,8})"""),
    )

    fun extract(text: String): String? {
        // 如果文本被脱敏（全是 *****），跳过
        if (text.isBlank() || isRedacted(text)) return null
        for (p in patterns) {
            val m = p.find(text) ?: continue
            val code = m.groupValues.getOrNull(1) ?: continue
            if (code.length in 4..8) return code
        }
        return null
    }

    private fun isRedacted(text: String): Boolean {
        val asteriskCount = text.count { it == '*' }
        return asteriskCount >= 3 && asteriskCount.toDouble() / text.length > 0.6
    }
}
