"""Escalation queue via Redis LPUSH/BRPOP."""

from __future__ import annotations

import json

from redis.asyncio import Redis

from loom.bus import channels


async def push_escalation(
    redis: Redis, project_id: str, task_id: str, message: str
) -> None:
    """Push an escalation onto the queue."""
    data = json.dumps({"task_id": task_id, "message": message})
    await redis.lpush(channels.escalation_queue(project_id), data)


async def pop_escalation(
    redis: Redis, project_id: str, timeout: int = 0
) -> dict | None:
    """Pop the next escalation from the queue. Blocks up to timeout seconds."""
    result = await redis.brpop(
        channels.escalation_queue(project_id), timeout=timeout
    )
    if result is None:
        return None
    _, data = result
    return json.loads(data)
