"""Per-THREAD in-flight lock for /hr-assist-stream (AC8 — one request at a time).

Scoped to a conversation, not to a person. It was keyed on user_id alone at
first, which quietly meant "one request at a time per HUMAN": asking something
in one chat blocked every other chat that person had open, and starting a fresh
chat while an answer was still streaming was refused outright. The rule people
actually expect — and the one AC8 asks for — is one answer per THREAD, with
separate threads free to run alongside each other.

Split out from voice_rate_limit so the chat path carries no voice imports, and
so this can be reviewed and reverted on its own — it is the only change this
feature makes to the existing chat flow.

Reuses the conventions of its neighbours: sync redis wrapped in
run_in_threadpool (redis_chat_service) and FAIL OPEN on any Redis problem
(cache_service). A Redis outage must degrade the guard, never chat itself.
"""

import logging
import os
import time

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

# OFF by default. This guard was added for AC8 and has since caused two
# user-visible faults and prevented nothing: a stale key — left by a restart or
# a disconnect the server did not notice — refuses every send for the whole
# TTL, and the refusal reads "please wait for the current response to finish"
# for a response that already finished. Chat on main has never had it and does
# not miss it; the client already blocks a second send while isStreaming, which
# is the case this was meant to cover.
#
# Kept rather than deleted because the rule itself is sound and the plumbing is
# now correct (per-thread, explicit release, self-healing client). Turn it on
# with CHAT_INFLIGHT_LOCK_ENABLED=true once it has been exercised somewhere
# that is not someone's working day.
CHAT_INFLIGHT_ENABLED = os.getenv("CHAT_INFLIGHT_LOCK_ENABLED", "false").lower() == "true"

# Only a backstop for a process that dies mid-stream. The normal release is the
# generator's finally, so this never needs to be tight — but it must comfortably
# exceed the longest legitimate turn, or a slow answer would unlock itself and
# let a second request through.
_TTL_SECONDS = int(os.getenv("CHAT_INFLIGHT_TTL_SECONDS", 300))

try:
    _r = 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,
    )
    _r.ping()
except Exception as e:  # pragma: no cover - environment dependent
    logger.warning("Chat in-flight lock: Redis unavailable (%s) — guard fails open", e)
    _r = None


def _key(user_id, conversation_id=None) -> str:
    """One slot per (person, thread).

    A brand-new chat has no id yet, so those share the "new" slot. That is
    deliberate rather than unlocked: the first message of a thread cannot
    violate a per-thread rule, but a double-click on an empty composer would
    otherwise create two conversations. It is still the narrowest possible
    scope — an ongoing thread never blocks a new chat, which is the whole
    point of the change.
    """
    return f"chat:inflight:{user_id}:{conversation_id or 'new'}"


def _acquire_sync(user_id, conversation_id) -> bool:
    if not _r or not CHAT_INFLIGHT_ENABLED:
        return True
    try:
        return bool(_r.set(_key(user_id, conversation_id), str(int(time.time())),
                           nx=True, ex=_TTL_SECONDS))
    except Exception as e:
        logger.warning("Chat in-flight acquire failed (allowing): %s", e)
        return True


def _release_sync(user_id, conversation_id) -> None:
    if not _r or not CHAT_INFLIGHT_ENABLED:
        return
    try:
        _r.delete(_key(user_id, conversation_id))
    except Exception as e:
        logger.warning("Chat in-flight release failed: %s", e)


async def acquire(user_id, conversation_id=None) -> bool:
    """True if this caller now owns the thread's slot; False means reject 409."""
    return await run_in_threadpool(_acquire_sync, user_id, conversation_id)


async def release(user_id, conversation_id=None) -> None:
    await run_in_threadpool(_release_sync, user_id, conversation_id)


async def release_after(user_id, conversation_id, inner):
    """Pass through an SSE generator, releasing the lock when it finishes.

    The `finally` covers all three endings: normal completion, an exception
    raised mid-stream, and GeneratorExit when the client disconnects early.
    A lock that released only on success would wedge the user for the whole TTL
    every time they closed the tab mid-answer — which is the common case, not
    an edge case.
    """
    try:
        async for chunk in inner:
            yield chunk
    finally:
        await release(user_id, conversation_id)
