from __future__ import annotations

from ..config import mcp_config

_in_flight = 0


class WaitSlot:
    """RAII-style slot for limiting concurrent upload_and_wait calls."""

    def __init__(self) -> None:
        self._released = False

    def release(self) -> None:
        global _in_flight
        if not self._released:
            self._released = True
            _in_flight -= 1


def acquire_wait_slot() -> tuple[bool, WaitSlot | None, str]:
    """Returns (ok, slot, error_message)."""
    global _in_flight
    if _in_flight >= mcp_config.wait.max_concurrent:
        return (
            False,
            None,
            f"Server is processing {_in_flight} concurrent uploads. "
            f"Max is {mcp_config.wait.max_concurrent}. "
            "Use upload_from_url or upload_file instead (they return immediately) or retry shortly.",
        )
    _in_flight += 1
    return True, WaitSlot(), ""


def active_waits() -> int:
    return _in_flight
