from ..core.base import BaseValidator
from .ci import CI

class RUC(BaseValidator):
    """
    Validator for Ecuadorian RUC.
    """

    @classmethod
    def validate(cls, doc: str) -> bool:
        doc = cls.clean(doc)
        
        if len(doc) != 13:
            return False
            
        # Validate province code (first 2 digits)
        province = int(doc[:2])
        if not (1 <= province <= 24):
            return False
            
        third_digit = int(doc[2])
        
        if third_digit < 6:
            # Natural Person: First 10 digits are a valid CI
            return CI.validate(doc[:10]) and doc[10:] == '001'
            
        elif third_digit == 9:
            # Private Society
            # Modulo 11, coefficients 4,3,2,7,6,5,4,3,2
            base = doc[:9]
            dv = int(doc[9])
            coeffs = [4, 3, 2, 7, 6, 5, 4, 3, 2]
            total = sum(int(base[i]) * coeffs[i] for i in range(9))
            remainder = total % 11
            calculated_dv = 0 if remainder == 0 else 11 - remainder
            return dv == calculated_dv and doc[10:] == '001'
            
        elif third_digit == 6:
            # Public Society
            # Modulo 11, coefficients 3,2,7,6,5,4,3,2
            base = doc[:8]
            dv = int(doc[8])
            coeffs = [3, 2, 7, 6, 5, 4, 3, 2]
            total = sum(int(base[i]) * coeffs[i] for i in range(8))
            remainder = total % 11
            calculated_dv = 0 if remainder == 0 else 11 - remainder
            return dv == calculated_dv and doc[9:] == '0001'
            
        return False

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