"""Abuse and concurrency controls for voice, plus the per-user in-flight lock.

This is the first rate limiting in this codebase — there was no prior art to
copy, so the conventions here follow the nearest neighbours deliberately:
sync redis wrapped in run_in_threadpool (redis_chat_service), and FAIL OPEN on
a Redis outage (cache_service). A dead Redis must degrade the guard, never the
feature.
"""

import asyncio
import logging
import os
import time
from contextlib import asynccontextmanager

import redis
from fastapi.concurrency import run_in_threadpool

logger = logging.getLogger(__name__)

REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
REDIS_DB = int(os.getenv("REDIS_DB", 0))
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD") or None
REDIS_USERNAME = os.getenv("REDIS_USERNAME") or None

VOICE_MAX_CONCURRENCY = int(os.getenv("VOICE_MAX_CONCURRENCY", 4))
VOICE_RATE_LIMIT_PER_MIN = int(os.getenv("VOICE_RATE_LIMIT_PER_MIN", 10))
VOICE_RATE_LIMIT_SECONDS_PER_DAY = int(os.getenv("VOICE_RATE_LIMIT_SECONDS_PER_DAY", 1800))

# Guards the GPU, the actual scarce resource — and keeps working when Redis is
# down, which the Redis-backed limits above do not.
#
# PER WORKER under gunicorn: the real ceiling is (workers x this value). One
# GPU behind 4 workers at 4 each is 16 concurrent jobs against a box that can
# probably serve 2. Size this as capacity / worker_count.
_semaphore = asyncio.Semaphore(VOICE_MAX_CONCURRENCY)
_SEMAPHORE_WAIT_SEC = 5.0


class VoiceThrottled(Exception):
    def __init__(self, status_code: int, error_code: str, detail: str, retry_after: int = 5):
        self.status_code = status_code
        self.error_code = error_code
        self.detail = detail
        self.retry_after = retry_after
        super().__init__(detail)


def _make_client():
    client = redis.Redis(
        host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,
        username=REDIS_USERNAME, password=REDIS_PASSWORD,
        decode_responses=True, socket_connect_timeout=3,
        socket_timeout=3, retry_on_timeout=True,
    )
    client.ping()
    return client


try:
    _r = _make_client()
except Exception as e:  # pragma: no cover - environment dependent
    logger.warning("Voice rate limiter: Redis unavailable (%s) — limits fail open", e)
    _r = None


def _get_redis():
    global _r
    if _r is not None:
        return _r
    try:
        _r = _make_client()
        logger.info("Voice rate limiter: Redis reconnected")
    except Exception:
        pass
    return _r


# ── Per-user in-flight lock ───────────────────────────────────────────────────
# "Only one request is processed at a time." The frontend already blocks a
# second send, but that is a client-side promise; this is the server-side one.

_INFLIGHT_TTL = 120  # generous upper bound; the finally-release is the real path


def _lock_key(user_id) -> str:
    return f"voice:inflight:{user_id}"


def _acquire_sync(key: str) -> bool:
    client = _get_redis()
    if not client:
        return True  # fail open
    try:
        return bool(client.set(key, str(int(time.time())), nx=True, ex=_INFLIGHT_TTL))
    except Exception as e:
        logger.warning("In-flight lock acquire failed (allowing): %s", e)
        return True


def _release_sync(key: str) -> None:
    client = _get_redis()
    if not client:
        return
    try:
        client.delete(key)
    except Exception as e:
        logger.warning("In-flight lock release failed: %s", e)


@asynccontextmanager
async def single_flight(user_id, *, error_code: str = "voice_busy",
                        detail: str = "Another request is still being processed."):
    """Reject a second concurrent request from the same user with 409.

    The release is in `finally` so it runs on the exception path too — a lock
    that only releases on success would wedge the user until the TTL expires,
    which is the classic way this pattern fails in production.
    """
    key = _lock_key(user_id)
    acquired = await run_in_threadpool(_acquire_sync, key)
    if not acquired:
        raise VoiceThrottled(409, error_code, detail, retry_after=2)
    try:
        yield
    finally:
        await run_in_threadpool(_release_sync, key)


# ── Rate limits ───────────────────────────────────────────────────────────────

def _check_sync(user_id, audio_seconds: float) -> None:
    client = _get_redis()
    if not client:
        return  # fail open, consistent with cache_service
    now = time.gmtime()
    minute_key = f"voice:rl:{user_id}:{time.strftime('%Y%m%d%H%M', now)}"
    day_key = f"voice:sec:{user_id}:{time.strftime('%Y%m%d', now)}"
    try:
        count = client.incr(minute_key)
        if count == 1:
            client.expire(minute_key, 120)
        if count > VOICE_RATE_LIMIT_PER_MIN:
            raise VoiceThrottled(429, "voice_rate_limited",
                                 "Too many voice requests. Try again in a minute.",
                                 retry_after=60)
        if audio_seconds and VOICE_RATE_LIMIT_SECONDS_PER_DAY > 0:
            total = client.incrbyfloat(day_key, audio_seconds)
            if total == audio_seconds:
                client.expire(day_key, 172800)
            if total > VOICE_RATE_LIMIT_SECONDS_PER_DAY:
                raise VoiceThrottled(429, "voice_rate_limited",
                                     "You've reached today's voice limit.",
                                     retry_after=3600)
    except VoiceThrottled:
        raise
    except Exception as e:
        logger.warning("Voice rate limit check failed (allowing): %s", e)


async def check_rate_limit(user_id, audio_seconds: float = 0.0) -> None:
    await run_in_threadpool(_check_sync, user_id, audio_seconds)


@asynccontextmanager
async def gpu_slot():
    """Bound concurrent ASR work. 503 + Retry-After when the queue is full."""
    try:
        await asyncio.wait_for(_semaphore.acquire(), timeout=_SEMAPHORE_WAIT_SEC)
    except asyncio.TimeoutError:
        raise VoiceThrottled(503, "voice_busy",
                             "The voice service is busy. Please try again.",
                             retry_after=5)
    try:
        yield
    finally:
        _semaphore.release()
