"""Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

Push ad-hoc queue_job WebSocket payloads (lifecycle events) without terminal dedup.
"""

from __future__ import annotations

import time
from typing import Any

from mcp_proxy_adapter.core.job_push.hooks import run_job_push_handlers
from mcp_proxy_adapter.core.job_push.subscriptions import (
    SubscriberRegistry,
    SubscriptionCategory,
)
from mcp_proxy_adapter.core.job_push.transfer_push import get_transfer_push_app
from mcp_proxy_adapter.core.logging import get_global_logger

_job_processing_step_last_mono: dict[str, float] = {}
_JOB_PROCESSING_STEP_MIN_INTERVAL_SEC: float = 1.0


def job_processing_step_should_emit(job_id: str) -> bool:
    """Throttle processing-step WS events per job_id (monotonic clock)."""
    jid = str(job_id).strip()
    if jid == "":
        return False
    now = time.monotonic()
    last = _job_processing_step_last_mono.get(jid)
    if last is None or (now - last) >= _JOB_PROCESSING_STEP_MIN_INTERVAL_SEC:
        _job_processing_step_last_mono[jid] = now
        return True
    return False


async def push_queue_job_ws_payload(payload: dict[str, Any]) -> None:
    """
    Deliver one message to all queue_job subscribers for payload['job_id'].

    Runs job_push_handlers hook chain (same as terminal notifications).
    """
    jid_raw = payload.get("job_id")
    jid = str(jid_raw).strip() if jid_raw is not None else ""
    if jid == "":
        return
    app = get_transfer_push_app()
    if app is None:
        return
    registry = getattr(app.state, "job_push_registry", None)
    if not isinstance(registry, SubscriberRegistry):
        return
    final = await run_job_push_handlers(jid, dict(payload))
    if final is None:
        return
    logger = get_global_logger()
    subs = await registry.get_subscribers(jid, SubscriptionCategory.QUEUE_JOB)
    for sub in subs:
        try:
            await sub.send(final)
        except Exception as e:
            logger.warning("queue_job custom push failed job_id=%s: %s", jid, e)
