from __future__ import annotations

from typing import Optional


class QuotaError(Exception):
    pass


async def reserve_voice_session(
    redis,
    org_id: Optional[str],
    sid: str,
    limit: int,
    ttl_seconds: int,
) -> None:
    org_key = org_id or "unknown"
    session_key = f"voice:session:{sid}"
    count_key = f"voice:concurrency:{org_key}"

    created = await redis.set(session_key, org_key, ex=ttl_seconds, nx=True)
    if not created:
        return

    count = await redis.incr(count_key)
    if count == 1:
        await redis.expire(count_key, ttl_seconds)
    if count > limit:
        await redis.decr(count_key)
        await redis.delete(session_key)
        raise QuotaError("Concurrent voice session limit reached")


async def release_voice_session(redis, org_id: Optional[str], sid: str) -> None:
    org_key = org_id or "unknown"
    session_key = f"voice:session:{sid}"
    count_key = f"voice:concurrency:{org_key}"

    deleted = await redis.delete(session_key)
    if deleted:
        await redis.decr(count_key)
