package eu.gaudian.translator.model.grammar

/**
 * Formats the grammatical details of a word into a concise, user-friendly string
 * based on the rules defined in a CategoryConfig.
 *
 * @param details The grammatical feature object containing the raw data.
 * @param config The configuration for the specific category (e.g., "noun" in German).
 * @return A formatted string like "(der)" or "(reg. -er)".
 */
fun formatGrammarDetails(
    details: GrammaticalFeature,
    config: CategoryConfig?
): String {
    val formatter = config?.formatter ?: return details.category.replaceFirstChar { it.uppercase() }

    @Suppress("HardCodedStringLiteral") val placeholderRegex = Regex("\\{(\\w+)\\}")

    val hasDataForFormatter = placeholderRegex.findAll(formatter).any { matchResult ->
        val key = matchResult.groupValues[1]
        details.properties.containsKey(key)
    }

    if (!hasDataForFormatter) {
        return details.category.replaceFirstChar { it.uppercase() }
    }


    var result = formatter
    result = placeholderRegex.replace(result) { matchResult ->
        val key = matchResult.groupValues[1]
        val rawValue = details.properties[key] ?: ""
        val mappedValue = config.mappings?.get(key)?.get(rawValue)
        mappedValue ?: rawValue
    }

    return result
}