import threading
from collections import defaultdict


class OrgLimiter:
    """Simple semaphore-based limiter for per-org and global concurrency."""

    def __init__(self, per_org: int, global_cap: int):
        self._per_org = max(1, per_org)
        self._global = max(1, global_cap)
        self._per_org_sems = defaultdict(lambda: threading.Semaphore(self._per_org))
        self._global_sem = threading.Semaphore(self._global)

    def acquire(self, org_id: str):
        self._global_sem.acquire()
        self._per_org_sems[str(org_id)].acquire()

    def release(self, org_id: str):
        self._per_org_sems[str(org_id)].release()
        self._global_sem.release()
