import math
import re

WORDS_REGEX = re.compile(r'[A-Za-z\u0410-\u044f\u0401\u0451\d-]+([^A-Za-z\u0410-\u044f\u0401\u0451\d-]+)?')

def count_words(text: str) -> int:
    """Count words in text using Glvrd's regex."""
    if not text:
        return 0
    return len(WORDS_REGEX.findall(text.strip()))

def calculate_score(text: str, findings: list[dict]) -> int | float:
    """Calculate Glvrd score using cubic formula.

    Formula: floor((1 - weighted_stopwords / total_words)^3 * 100) / 10
    Each finding contributes weight/100 to weighted_stopwords.
    """
    words = count_words(text)
    if words == 0:
        return 0
    stopwords = sum(f.get("weight", 100) / 100 for f in findings)
    penalties = sum(f.get("penalty", 0) for f in findings)
    score_raw = math.floor((1 - stopwords / words) ** 3 * 100) - penalties
    score_raw = max(0, min(100, score_raw))
    if score_raw % 10 == 0:
        return score_raw // 10
    return round(score_raw / 10, 1)

def score_color(score: float) -> str:
    if score >= 7.5:
        return "green"
    if score >= 5:
        return "orange"
    return "red"
