from ..core.base import BaseValidator

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

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) != 10:
            return False
            
        # Validate province code (first 2 digits)
        province = int(doc[:2])
        if not (1 <= province <= 24):
            return False
            
        # Third digit < 6 for natural persons
        if int(doc[2]) >= 6:
            return False
            
        base = doc[:-1]
        dv = int(doc[-1])
        
        # Modulo 10
        # Coefficients: 2, 1, 2, 1...
        total = 0
        for i, digit in enumerate(base):
            val = int(digit) * (2 if i % 2 == 0 else 1)
            if val >= 10:
                val -= 9
            total += val
            
        remainder = total % 10
        calculated_dv = 0 if remainder == 0 else 10 - remainder
        
        return dv == calculated_dv

    @classmethod
    def format(cls, doc: str) -> str:
        doc = cls.clean(doc)
        if len(doc) != 10:
             raise ValueError("CI must have 10 digits")
        return doc

    @classmethod
    def generate(cls) -> str:
        """Generates a valid CI."""
        import random
        # Province 01-24
        province = f"{random.randint(1, 24):02d}"
        # Third digit < 6
        third = str(random.randint(0, 5))
        # Next 6 digits
        body = "".join([str(random.randint(0, 9)) for _ in range(6)])
        base = province + third + body
        
        total = 0
        for i, digit in enumerate(base):
            val = int(digit) * (2 if i % 2 == 0 else 1)
            if val >= 10: val -= 9
            total += val
            
        remainder = total % 10
        dv = 0 if remainder == 0 else 10 - remainder
        
        return cls.format(base + str(dv))
