try:
    from django.db import models
    from django.core.exceptions import ValidationError
except ImportError:
    # Mock for when Django is not installed, to allow import but fail on usage if needed
    # Or just raise ImportError immediately
    raise ImportError("Django is required to use doclatam.integrations.django. Install it with 'pip install django'")

from ...br.cpf import CPF
from ...br.cnpj import CNPJ

class DocLatamField(models.CharField):
    description = "A field for validating Latin American documents"
    validator_class = None

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('max_length', 20)
        super().__init__(*args, **kwargs)

    def validate(self, value, model_instance):
        super().validate(value, model_instance)
        if value and self.validator_class and not self.validator_class.validate(value):
            raise ValidationError(f"Invalid {self.validator_class.__name__}")

    def pre_save(self, model_instance, add):
        value = super().pre_save(model_instance, add)
        if value and self.validator_class:
             try:
                return self.validator_class.format(value)
             except:
                return value
        return value

class CPFField(DocLatamField):
    validator_class = CPF
    description = "CPF Field"

class CNPJField(DocLatamField):
    validator_class = CNPJ
    description = "CNPJ Field"
