from django.apps import AppConfig
from django.conf import settings

class OperationLogConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'django_ops_logger'
    verbose_name = 'Operation Logger'

    def ready(self):
        # Prevent double loading
        if getattr(self, '_ready_called', False):
            return
        self._ready_called = True

        # Check configuration
        config = getattr(settings, 'DJANGO_OPS_LOGGER', {})
        if not config.get('ENABLED', True):
            return

        # Start async worker
        from .queue import start_worker, enqueue_log
        start_worker()

        # Install DB logger
        if config.get('SQL_LOG_ENABLE', True):
            from .db_log import install_db_logger
            install_db_logger()

        # Install Cache logger
        if config.get('CACHE_LOG_ENABLE', False):
            from .cache_log import install_cache_logger
            install_cache_logger()

        # Connect signals
        from . import signals

        # Log startup
        from .models import OperationLog
        from django.utils import timezone
        
        enqueue_log(
            operation_type=OperationLog.OpType.STARTUP,
            level='INFO',
            start_time=timezone.now(),
            details={'message': 'Application started'}
        )
