from ..core.base import BaseValidator

class Renavam(BaseValidator):
    """
    Validator for Brazilian Renavam.
    """

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) != 11:
            # Pad with zeros if 9 digits (old format)
            if len(doc) == 9:
                doc = "00" + doc
            else:
                return False
        
        # Reverse without the check digit
        base_num = doc[:10][::-1]
        
        weights = [2, 3, 4, 5, 6, 7, 8, 9, 2, 3]
        sum_val = sum(int(base_num[i]) * weights[i] for i in range(10))
        
        remainder = (sum_val * 10) % 11
        digit = 0 if remainder == 10 else remainder

        return int(doc[10]) == digit

    @classmethod
    def format(cls, doc: str) -> str:
        doc = cls.clean(doc)
        if len(doc) == 9:
            doc = "00" + doc
        if len(doc) != 11:
            raise ValueError("Renavam must have 11 digits (or 9 for old format)")
        return f"{doc[:4]}.{doc[4:10]}-{doc[10]}"
