"""
Track deliver_id values for in-flight execute_async work.

The job_push poll loop calls queue_manager.get_job_status for every subscribed
job_id and may emit notify_job_state_changed on a terminal row that does not
match the real async command result. The notifier deduplicates terminal events
per job_id, so a spurious poll notification can block the legitimate completion
from _run_async_command_and_notify. While execute_async runs for a deliver_id,
the poll loop must not call notify_job_state_changed for that id.

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

from __future__ import annotations

from threading import RLock
from typing import Set

_active_deliver_ids: Set[str] = set()
_lock = RLock()


def register_execute_async_deliver_id(deliver_id: str) -> None:
    """Mark deliver_id as owned by an in-flight execute_async command."""
    key = (deliver_id or "").strip()
    if not key:
        return
    with _lock:
        _active_deliver_ids.add(key)


def unregister_execute_async_deliver_id(deliver_id: str) -> None:
    """Remove deliver_id after execute_async completion or failure notification."""
    key = (deliver_id or "").strip()
    if not key:
        return
    with _lock:
        _active_deliver_ids.discard(key)


def is_execute_async_deliver_id_in_flight(deliver_id: str) -> bool:
    """Return True if this id is currently an active execute_async deliver_id."""
    key = (deliver_id or "").strip()
    if not key:
        return False
    with _lock:
        return key in _active_deliver_ids


def clear_execute_async_deliver_ids() -> None:
    """Clear all tracked ids (e.g. together with clear_notifier_listeners in tests)."""
    with _lock:
        _active_deliver_ids.clear()
