"""Background task runner for AI calls.

TEMP: Celery + Redis are the target architecture but neither is installable
in this offline environment. This module provides a minimal in-process
thread-pool queue with a Celery-compatible surface — tasks are decorated
with @background_task and dispatched with `.delay(...)`, exactly like
Celery's shared_task. To move to real Celery later:

    1. pip install celery redis, add CELERY_BROKER_URL to settings
    2. replace @background_task with @shared_task in tasks that use it
    3. delete this module

Django DB connections are closed after each task so worker threads never
hold stale connections.
"""

import logging
import threading
import time
from concurrent.futures import ThreadPoolExecutor

from django.db import connection

logger = logging.getLogger(__name__)

_executor = ThreadPoolExecutor(max_workers=8, thread_name_prefix="ai-call-worker")


def _run(fn, args, kwargs):
    try:
        fn(*args, **kwargs)
    except Exception:
        logger.exception("Background task %s failed", getattr(fn, "__name__", fn))
    finally:
        connection.close()


def background_task(fn):
    """Celery-compatible decorator: call fn.delay(...) to run in the background."""

    def delay(*args, **kwargs):
        return _executor.submit(_run, fn, args, kwargs)

    fn.delay = delay
    return fn


def sleep(seconds):
    """Interruptible-ish sleep used by the mock call simulator."""
    time.sleep(seconds)


def spawn_later(seconds, fn, *args, **kwargs):
    """Run fn(*args) after a delay without blocking a pool worker."""
    timer = threading.Timer(seconds, lambda: _run(fn, args, kwargs))
    timer.daemon = True
    timer.start()
    return timer
