from collections import Counter
import unicodedata
from .constants import SCRIPT_TO_LANG


def detect_language_distribution(text: str) -> dict:
    if not text:
        return {}
    
    char_counts = Counter()
    
    for char in text:
        if not char.isalnum():
            continue
            
        try:
            script = unicodedata.name(char).split()[0]
            if script in SCRIPT_TO_LANG:
                lang = SCRIPT_TO_LANG[script]
                char_counts[lang] += 1
        except (ValueError, IndexError):
            continue
    
    total = sum(char_counts.values())
    if total == 0:
        return {}

    return {
        lang: {
            "chars": count,
            "percent": round(count / total, 3)
        }
        for lang, count in char_counts.items()
    }