"""ARQ job queue integration."""

from __future__ import annotations

from typing import Any

from arq import create_pool
from arq.connections import RedisSettings

from app.config import get_settings


async def get_job_pool():
    """Get an ARQ job pool for enqueueing background tasks."""
    settings = get_settings()
    redis_settings = RedisSettings.from_dsn(settings.redis_url)
    return await create_pool(redis_settings)


async def enqueue_job(job_name: str, *args: Any, **kwargs: Any) -> str | None:
    """Enqueue a background job. Returns job_id or None."""
    pool = await get_job_pool()
    job = await pool.enqueue_job(job_name, *args, **kwargs)
    if job:
        return job.job_id
    return None


async def get_job_status(job_id: str) -> dict[str, Any] | None:
    """Get the status of a background job."""
    pool = await get_job_pool()
    job_info = await pool.job_info(job_id)
    if job_info is None:
        return None
    return {
        "job_id": job_id,
        "status": str(job_info.status),
        "result": job_info.result,
        "enqueue_time": job_info.enqueue_time.isoformat() if job_info.enqueue_time else None,
        "start_time": job_info.start_time.isoformat() if job_info.start_time else None,
        "finish_time": job_info.finish_time.isoformat() if job_info.finish_time else None,
    }
