"""Job queue helpers (ARQ / Redis)."""

from __future__ import annotations

from typing import Any, Optional

from arq import create_pool
from arq.connections import ArqRedis, RedisSettings

from packages.config import get_settings

_pool: Optional[ArqRedis] = None


def redis_settings() -> RedisSettings:
    return RedisSettings.from_dsn(get_settings().redis_url)


async def get_redis_pool() -> ArqRedis:
    global _pool
    if _pool is None:
        _pool = await create_pool(redis_settings())
    return _pool


async def enqueue_process_run(run_id: str, resume: bool = False) -> Any:
    pool = await get_redis_pool()
    return await pool.enqueue_job("process_run", run_id, resume)


async def close_redis_pool() -> None:
    global _pool
    if _pool is not None:
        await _pool.close()
        _pool = None
