"""ARQ client helper to enqueue jobs."""

from __future__ import annotations

from typing import Any

from arq.connections import RedisSettings, create_pool

from app.config import get_settings

_pool = None


async def _get_pool():
    global _pool
    if _pool is not None:
        return _pool

    settings = get_settings()
    if not settings.redis_url:
        raise RuntimeError("redis_url is not configured (set REDIS_URL)")

    _pool = await create_pool(RedisSettings.from_dsn(settings.redis_url))
    return _pool


async def enqueue_job(name: str, *args: Any, **kwargs: Any) -> str:
    """
    Enqueue a job by name. Returns the job id.
    """
    pool = await _get_pool()
    job = await pool.enqueue_job(name, *args, **kwargs)
    # job may be None if enqueue failed
    if job is None:
        raise RuntimeError(f"Failed to enqueue job: {name}")
    return job.job_id


