from ..core.base import BaseValidator

class NIT(BaseValidator):
    """
    Validator for Colombian NIT (Número de Identificación Tributaria).
    Uses Modulo 11 algorithm with specific weights.
    """

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) < 2: # Minimum length? Usually 9-10 digits + DV
            return False
            
        base = doc[:-1]
        dv = int(doc[-1])
        
        # Weights: 3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71
        weights = [3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71]
        
        total = 0
        reversed_base = base[::-1]
        
        for i, digit in enumerate(reversed_base):
            if i < len(weights):
                total += int(digit) * weights[i]
                
        remainder = total % 11
        
        if remainder == 0 or remainder == 1:
            calculated_dv = remainder
        else:
            calculated_dv = 11 - remainder
            
        return dv == calculated_dv

    @classmethod
    def format(cls, doc: str) -> str:
        doc = cls.clean(doc)
        if len(doc) < 2:
             raise ValueError("Invalid NIT length")
        return f"{doc[:-1]}-{doc[-1]}"

    @classmethod
    def generate(cls) -> str:
        """Generates a valid NIT."""
        import random
        # 9 digits base usually
        base = "".join([str(random.randint(0, 9)) for _ in range(9)])
        
        weights = [3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71]
        total = 0
        reversed_base = base[::-1]
        for i, digit in enumerate(reversed_base):
            if i < len(weights):
                total += int(digit) * weights[i]
                
        remainder = total % 11
        if remainder == 0 or remainder == 1:
            dv = remainder
        else:
            dv = 11 - remainder
            
        return cls.format(base + str(dv))
