# apps/core/signals.py
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.core.exceptions import ValidationError
from django.apps import apps
from django.db.models import UUIDField
import uuid


def validate_uuid_length(sender, instance, **kwargs):
    """
    Signal handler to validate UUID length before saving
    """
    # Get the primary key field
    pk_field = sender._meta.pk
    
    # Only check if it's a UUID field
    if not isinstance(pk_field, UUIDField):
        return
    
    # Get the UUID value
    uuid_value = getattr(instance, pk_field.name)
    
    if uuid_value:
        uuid_str = str(uuid_value)
        
        # Check length
        if len(uuid_str) < 36:
            raise ValidationError(
                f"UUID must be at least 36 characters. Got: {len(uuid_str)} chars"
            )
        
        # Validate format
        try:
            uuid.UUID(uuid_str)
        except ValueError:
            raise ValidationError(
                f"Invalid UUID format: {uuid_str}"
            )


def connect_uuid_validators():
    """
    Connect the validator to all models with UUID primary keys
    """
    for model in apps.get_models():
        pk_field = model._meta.pk
        if isinstance(pk_field, UUIDField):
            pre_save.connect(
                validate_uuid_length,
                sender=model,
                dispatch_uid=f'validate_uuid_{model._meta.label}'
            )