from ..core.base import BaseValidator

class RUC(BaseValidator):
    """
    Validator for Peruvian RUC.
    Uses Modulo 11 algorithm.
    """

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) != 11:
            return False
            
        base = doc[:-1]
        dv = int(doc[-1])
        
        # 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(base[i]) * weights[i] for i in range(10))
        
        remainder = sum_val % 11
        calculated_dv = 11 - remainder
        
        if calculated_dv == 10:
            calculated_dv = 0
        elif calculated_dv == 11:
            calculated_dv = 1
            
        return dv == calculated_dv

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

    @classmethod
    def generate(cls) -> str:
        """Generates a valid RUC."""
        import random
        # Prefix 10, 15, 17, 20
        prefix = random.choice(['10', '15', '17', '20'])
        # 8 random digits
        body = "".join([str(random.randint(0, 9)) for _ in range(8)])
        base = prefix + body
        
        weights = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
        sum_val = sum(int(base[i]) * weights[i] for i in range(10))
        
        remainder = sum_val % 11
        dv = 11 - remainder
        if dv == 10: dv = 0
        elif dv == 11: dv = 1
        
        return cls.format(base + str(dv))
