from ..core.base import BaseValidator

class CI(BaseValidator):
    """
    Validator for Uruguayan Cédula de Identidad (CI).
    Uses Modulo 10 algorithm.
    """

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) < 7 or len(doc) > 8:
            return False
            
        # Pad to 8 digits if 7 (add leading zero)
        if len(doc) == 7:
            doc = "0" + doc
            
        # Weights: 2, 9, 8, 7, 6, 3, 4
        weights = [2, 9, 8, 7, 6, 3, 4]
        
        sum_val = sum(int(doc[i]) * weights[i] for i in range(7))
        
        remainder = sum_val % 10
        digit = 0 if remainder == 0 else 10 - remainder
        
        return int(doc[7]) == digit

    @classmethod
    def format(cls, doc: str) -> str:
        doc = cls.clean(doc)
        if len(doc) < 7 or len(doc) > 8:
             raise ValueError("Invalid CI length")
        
        # Format usually X.XXX.XXX-X
        if len(doc) == 7:
            # If 7 digits total: 123.456-7
            return f"{doc[:-1]}-{doc[-1]}"
        else: # 8 digits
            return f"{doc[0]}.{doc[1:4]}.{doc[4:7]}-{doc[7]}"

    @classmethod
    def generate(cls) -> str:
        """Generates a valid CI."""
        import random
        # 7 digits
        body = "".join([str(random.randint(0, 9)) for _ in range(7)])
        
        # Weights: 2, 9, 8, 7, 6, 3, 4
        weights = [2, 9, 8, 7, 6, 3, 4]
        sum_val = sum(int(body[i]) * weights[i] for i in range(7))
        
        remainder = sum_val % 10
        digit = 0 if remainder == 0 else 10 - remainder
        
        return cls.format(body + str(digit))
