from django.conf import settings
from django.apps import apps
from .models import BaseModel
from django.contrib.auth import get_user_model
import threading

User = get_user_model()

class SyncRegistry:
    def __init__(self):
        self._registry = {}

    def load_sync_apps(self):
        sync_apps = getattr(settings, 'SYNC_APPS', {})
        for app_label, config in sync_apps.items():
            app_models = apps.get_app_config(app_label).get_models()
            for model in app_models:
                if hasattr(model, '_meta') and not model._meta.abstract:
                    if issubclass(model, BaseModel) or model == User:
                        model_name = model.__name__
                        if self.should_sync_model(model_name, config):
                            self.register(model)

    def should_sync_model(self, model_name, config):
        if 'exclude' in config and model_name in config['exclude']:
            return False
        if 'models' in config and config['models']:
            return model_name in config['models']
        return True

    def register(self, model):
        self._registry[model.__name__] = model

    def get_model(self, model_name):
        if not self._registry:
            self.load_sync_apps()
        return self._registry.get(model_name)

# Global instance
sync_registry = SyncRegistry()

class DeviceRegistry:
    """Thread-safe registry to track device IDs associated with model instances."""

    def __init__(self):
        self._registry = {}
        self._lock = threading.RLock()

    def count(self):
        """Return the number of items in the registry."""
        with self._lock:
            return len(self._registry)

    def register(self, instance_id, device_id):
        """Register a device_id for a model instance ID."""
        with self._lock:
            self._registry[str(instance_id)] = device_id

    def get_device_id(self, instance_id):
        """Get the device_id for a model instance ID."""
        with self._lock:
            return self._registry.get(str(instance_id))

    def unregister(self, instance_id):
        """Remove an instance from the registry."""
        with self._lock:
            if instance_id in self._registry:
                del self._registry[instance_id]

# Global instance
device_registry = DeviceRegistry()
