from ..core.base import BaseValidator

class CUIT(BaseValidator):
    """
    Validator for Argentine CUIT/CUIL (Código Único de Identificación Tributaria/Laboral).
    """

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) != 11:
            return False
            
        # Weights: 5, 4, 3, 2, 7, 6, 5, 4, 3, 2
        weights = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
        
        sum_val = sum(int(doc[i]) * weights[i] for i in range(10))
        
        remainder = sum_val % 11
        
        calculated_digit = 11 - remainder
        if calculated_digit == 11:
            calculated_digit = 0
        elif calculated_digit == 10:
            calculated_digit = 9
            
        return int(doc[10]) == calculated_digit

    @classmethod
    def format(cls, doc: str) -> str:
        doc = cls.clean(doc)
        if len(doc) != 11:
             raise ValueError("CUIT/CUIL must have 11 digits")
        return f"{doc[:2]}-{doc[2:10]}-{doc[10]}"

    @classmethod
    def generate(cls) -> str:
        """Generates a valid CUIT."""
        import random
        # Prefixes: 20, 23, 24, 27, 30, 33, 34
        prefix = random.choice(['20', '23', '24', '27', '30', '33', '34'])
        # 8 random digits
        body = "".join([str(random.randint(0, 9)) for _ in range(8)])
        doc = prefix + body
        
        weights = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
        sum_val = sum(int(doc[i]) * weights[i] for i in range(10))
        remainder = sum_val % 11
        
        calculated_digit = 11 - remainder
        if calculated_digit == 11: calculated_digit = 0
        elif calculated_digit == 10: calculated_digit = 9
        
        return cls.format(doc + str(calculated_digit))

    @classmethod
    def get_type(cls, doc: str) -> str:
        """
        Returns the type of CUIT (Empresa or Pessoa Física).
        """
        doc = cls.clean(doc)
        if not cls.validate(doc):
            return None
            
        prefix = doc[:2]
        if prefix in ['20', '23', '24', '27']:
            return "Pessoa Física"
        elif prefix in ['30', '33', '34']:
            return "Empresa"
        else:
            return "Outros"

# Alias for CUIL
CUIL = CUIT
