from django.apps import AppConfig


def _start_cbc_seed_worker():
    import os
    import threading
    import time
    from django.conf import settings
    from django.core.cache import cache
    from django.core.management import call_command
    from django.utils import timezone

    if getattr(settings, "CBC_AUTO_SEED_ENABLED", True) is False:
        return
    # Avoid duplicate threads in autoreload
    if settings.DEBUG and os.environ.get("RUN_MAIN") != "true":
        return

    def worker():
        while True:
            today = timezone.localdate().isoformat()
            key = f"cbc_comment_seeded_{today}"
            if cache.add(key, True, timeout=26 * 3600):
                try:
                    call_command("seed_cbc_comment_banks", silent=True)
                except Exception:
                    pass
            time.sleep(3600)

    threading.Thread(target=worker, daemon=True).start()


class SchoolsConfig(AppConfig):
    name = 'schools'

    def ready(self):
        _start_cbc_seed_worker()
