from ..core.base import BaseValidator

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

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) < 5:
            return False
            
        base = doc[:-1]
        dv = int(doc[-1])
        
        # Calculate DV
        k = 2
        total = 0
        for digit in reversed(base):
            total += int(digit) * k
            k += 1
            
        remainder = total % 11
        calculated_dv = 0 if remainder > 1 else 0 # Wait, standard rule:
        # If remainder > 1, DV = 11 - remainder
        # If remainder = 0, DV = 0
        # If remainder = 1, DV = 0? Or 1?
        # Research says: 
        # If remainder > 1: result = 11 - remainder
        # If remainder == 0: result = 0
        # If remainder == 1: result = 0 (some sources say this)
        
        if remainder > 1:
            calculated_dv = 11 - remainder
        else:
            calculated_dv = 0
            
        return dv == calculated_dv

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

    @classmethod
    def generate(cls) -> str:
        """Generates a valid RUC."""
        import random
        # 5 to 8 digits base
        base = "".join([str(random.randint(0, 9)) for _ in range(random.randint(5, 8))])
        
        k = 2
        total = 0
        for digit in reversed(base):
            total += int(digit) * k
            k += 1
            
        remainder = total % 11
        dv = 0 if remainder <= 1 else 11 - remainder
        
        return cls.format(base + str(dv))
