import os
import threading
import time

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

class ApiConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'api'

    def ready(self):
        # Register integration lifecycle hooks before starting optional runtime
        # background work. Importing here avoids model-loading side effects.
        from api.services.integration import signals  # noqa: F401
        from api import checks  # noqa: F401

        if not settings.REDIS_KEEPALIVE_ENABLED:
            return

        def keep_alive():
            while True:
                try:
                    from backend.redis_client import redis_client
                    redis_client.ping()
                except Exception as e:
                    from api.utils import log_critical_error, get_exception_detail
                    e_details = get_exception_detail(e)
                    log_critical_error(user_id=None, descr=e_details['descr'], url=e_details['url'],trace=e_details['trace'])
                time.sleep(60)  # every 60 seconds

        # Run in a background thread (non-blocking)
        # deamon=True means process can exit anytime, thread dies with it
        thread = threading.Thread(target=keep_alive, daemon=True)
        thread.start()
