from ..core.base import BaseValidator

class CNH(BaseValidator):
    """
    Validator for Brazilian CNH (Carteira Nacional de Habilitação).
    """

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) != 11:
            return False
            
        if doc == doc[0] * 11:
            return False

        # First digit
        sum_val = 0
        for i in range(9):
            sum_val += int(doc[i]) * (9 - i)
            
        remainder = sum_val % 11
        digit1 = 0 if remainder <= 1 else 11 - remainder
        
        # Adjust for special case where digit1 > 9 (though logic usually handles it, 
        # standard CNH algo has specific rules if result is > 9, but modulo 11 usually 
        # keeps it within bounds or treats 10 as 0 in some variants. 
        # The standard CNH rule: if calculated digit > 9, it becomes 0 and adds to next calculation?
        # Actually, standard CNH: if remainder is 0 or 1, digit is 0. Else 11-remainder.
        # Let's stick to the researched algorithm:
        # DV1: weights 9 to 1. Remainder. If rem <= 1, DV1=0. Else 11-rem.
        
        if int(doc[9]) != digit1:
            # There is a variation where if DV1 calculation results in > 9 (not possible with mod 11 logic above unless we don't mod?),
            # wait, 11-remainder can be 10 if remainder is 1. But we handled remainder <= 1 -> 0.
            # So 11-remainder is max 9 (when remainder is 2).
            return False

        # Second digit
        sum_val = 0
        # Weights 1 to 9
        for i in range(9):
            sum_val += int(doc[i]) * (1 + i)
            
        remainder = sum_val % 11
        digit2 = 0 if remainder <= 1 else 11 - remainder

        return int(doc[10]) == digit2

    @classmethod
    def format(cls, doc: str) -> str:
        doc = cls.clean(doc)
        if len(doc) != 11:
            raise ValueError("CNH must have 11 digits")
        return doc # CNH usually doesn't have a standard punctuation format like CPF
