"""The per-THREAD in-flight lock on /hr-assist-stream (AC8).

This is the only change the voice feature makes to the existing chat path, so
the tests here are about NOT breaking chat as much as about enforcing the rule.
"""

import pytest

import services.chat_inflight as chat_inflight
from tests.conftest import FAKE_JWT_PAYLOAD

# The user the `client` fixture authenticates as. The stop route releases the
# slot for the CALLER, so a test that seeds the lock under a different id is
# testing nothing.
AUTHED_USER = FAKE_JWT_PAYLOAD["user_id"]


async def test_second_request_is_rejected_with_409(client, monkeypatch):
    monkeypatch.setattr(chat_inflight, "_acquire_sync", lambda uid, conv: False)

    resp = await client.post("/hr-assist-stream", json={"query": "what is my leave balance"})

    assert resp.status_code == 409
    assert resp.json()["detail"]["error_code"] == "request_in_progress"


async def test_lock_is_released_when_the_route_raises_before_streaming(client, monkeypatch):
    """The whole reason the body is wrapped in try/finally.

    Without it, any failure between acquiring the lock and returning the
    StreamingResponse would wedge that user for the full TTL.
    """
    released = []
    monkeypatch.setattr(chat_inflight, "_acquire_sync", lambda uid, conv: True)
    monkeypatch.setattr(chat_inflight, "_release_sync",
                        lambda uid, conv: released.append(uid))

    def boom(*args, **kwargs):
        raise RuntimeError("history lookup exploded")

    # _load_chat_history runs after the lock is taken and before the response.
    import main
    monkeypatch.setattr(main, "_resolve_conversation", boom)

    # No longer a 500: a pre-stream failure answers with the Helix fallback
    # reply (a 500 shows as "something went wrong" in the client).
    resp = await client.post("/hr-assist-stream", json={"query": "hello"})

    assert resp.status_code == 200
    assert "Helix AI" in resp.text
    assert '"blocked": false' in resp.text
    assert '"type": "error"' not in resp.text
    assert released, "lock must be released on the exception path"


async def test_empty_query_is_rejected_without_taking_the_lock(client, monkeypatch):
    """A 400 must not consume the slot — otherwise a malformed request would
    lock the user out of their next real one."""
    acquired = []
    monkeypatch.setattr(chat_inflight, "_acquire_sync",
                        lambda uid, conv: (acquired.append(uid), True)[1])

    resp = await client.post("/hr-assist-stream", json={})

    assert resp.status_code == 400
    assert not acquired, "validation must run before the lock is taken"


def test_guard_fails_open_when_redis_is_down(monkeypatch, lock_on):
    """A Redis outage must degrade the guard, never chat itself — the frontend
    guard still holds. Same philosophy as cache_service."""
    monkeypatch.setattr(chat_inflight, "_r", None)
    assert chat_inflight._acquire_sync(123, "c1") is True
    chat_inflight._release_sync(123, "c1")  # must not raise


def test_guard_fails_open_when_redis_errors(monkeypatch, lock_on):
    class Exploding:
        def set(self, *a, **k):
            raise RuntimeError("connection reset")

        def delete(self, *a, **k):
            raise RuntimeError("connection reset")

    monkeypatch.setattr(chat_inflight, "_r", Exploding())
    assert chat_inflight._acquire_sync(123, "c1") is True
    chat_inflight._release_sync(123, "c1")  # must not raise


async def test_release_after_releases_on_generator_exception():
    """Covers a stream that dies mid-answer."""
    released = []

    async def failing_stream():
        yield "data: one\n\n"
        raise RuntimeError("upstream died")

    agen = chat_inflight.release_after(7, "conv-a", failing_stream())

    import services.chat_inflight as ci
    original = ci.release

    async def fake_release(uid, conv=None):
        released.append((uid, conv))

    ci.release = fake_release
    try:
        with pytest.raises(RuntimeError):
            async for _ in agen:
                pass
    finally:
        ci.release = original

    assert released == [(7, "conv-a")]


async def test_release_after_releases_on_client_disconnect():
    """A user closing the tab mid-answer is the common case, not an edge case:
    it surfaces as GeneratorExit and must still free the slot."""
    released = []

    async def endless_stream():
        while True:
            yield "data: chunk\n\n"

    agen = chat_inflight.release_after(9, "conv-b", endless_stream())

    import services.chat_inflight as ci
    original = ci.release

    async def fake_release(uid, conv=None):
        released.append((uid, conv))

    ci.release = fake_release
    try:
        async for _ in agen:
            break          # simulate the client going away
        await agen.aclose()
    finally:
        ci.release = original

    assert released == [(9, "conv-b")]


# ── Thread scoping ────────────────────────────────────────────────────────────
# Reported: "check leave balance" in one chat, then a NEW chat, and the new chat
# answered "Please wait for the current response to finish." The lock was keyed
# on user_id alone, so one person could only ever have one answer in flight
# anywhere. The rule is one answer per THREAD.

@pytest.fixture
def lock_on(monkeypatch):
    """The guard SHIPS OFF (see the note in chat_inflight). Everything below is
    about how it behaves when switched on, so these turn it on explicitly."""
    monkeypatch.setattr(chat_inflight, "CHAT_INFLIGHT_ENABLED", True)


def test_the_guard_is_off_by_default():
    """Pins the shipped default. It was on, and a stale key then refused every
    send for the whole TTL with "please wait for the current response to
    finish" — about a response that had already finished."""
    assert chat_inflight.CHAT_INFLIGHT_ENABLED is False


def test_when_disabled_every_request_is_allowed(monkeypatch):
    """Chat must behave exactly as it does on main: no slot, no refusals."""
    monkeypatch.setattr(chat_inflight, "CHAT_INFLIGHT_ENABLED", False)
    monkeypatch.setattr(chat_inflight, "_r", _FakeRedis())

    for _ in range(5):
        assert chat_inflight._acquire_sync(1, "conv-a") is True


class _FakeRedis:
    """Enough of redis-py for SET NX EX / DELETE, so the key scheme itself is
    under test rather than mocked away."""

    def __init__(self):
        self.store = {}

    def set(self, key, value, nx=False, ex=None):
        if nx and key in self.store:
            return None
        self.store[key] = value
        return True

    def delete(self, key):
        return self.store.pop(key, None) is not None


def test_two_different_chats_can_answer_at_the_same_time(monkeypatch, lock_on):
    monkeypatch.setattr(chat_inflight, "_r", _FakeRedis())

    assert chat_inflight._acquire_sync(1, "conv-a") is True
    assert chat_inflight._acquire_sync(1, "conv-b") is True,         "a second thread must not be blocked by the first"


def test_a_new_chat_is_not_blocked_by_an_ongoing_one(monkeypatch, lock_on):
    """The exact reported case: an answer is still streaming in an existing
    thread, and the user starts a fresh chat (no conversation_id yet)."""
    monkeypatch.setattr(chat_inflight, "_r", _FakeRedis())

    assert chat_inflight._acquire_sync(1, "conv-a") is True
    assert chat_inflight._acquire_sync(1, None) is True


def test_the_same_thread_still_allows_only_one_answer(monkeypatch, lock_on):
    """The rule being preserved. Widening the scope must not have widened it
    into nothing."""
    monkeypatch.setattr(chat_inflight, "_r", _FakeRedis())

    assert chat_inflight._acquire_sync(1, "conv-a") is True
    assert chat_inflight._acquire_sync(1, "conv-a") is False


def test_two_new_chats_at_once_are_still_serialised(monkeypatch, lock_on):
    """A double-click on an empty composer would otherwise create two
    conversations. Threads without an id share the "new" slot on purpose."""
    monkeypatch.setattr(chat_inflight, "_r", _FakeRedis())

    assert chat_inflight._acquire_sync(1, None) is True
    assert chat_inflight._acquire_sync(1, None) is False


def test_one_persons_chat_never_blocks_another_persons(monkeypatch, lock_on):
    monkeypatch.setattr(chat_inflight, "_r", _FakeRedis())

    assert chat_inflight._acquire_sync(1, "shared-conv") is True
    assert chat_inflight._acquire_sync(2, "shared-conv") is True


def test_releasing_one_thread_leaves_the_other_running(monkeypatch, lock_on):
    fake = _FakeRedis()
    monkeypatch.setattr(chat_inflight, "_r", fake)

    chat_inflight._acquire_sync(1, "conv-a")
    chat_inflight._acquire_sync(1, "conv-b")
    chat_inflight._release_sync(1, "conv-a")

    assert chat_inflight._acquire_sync(1, "conv-a") is True, "released thread is free"
    assert chat_inflight._acquire_sync(1, "conv-b") is False, "the other is still held"


# ── Stop ──────────────────────────────────────────────────────────────────────

async def test_stop_frees_the_slot_so_a_resend_is_accepted(client, monkeypatch, lock_on):
    """Pressing Stop and immediately resending used to race the disconnect and
    come back 409 — which reads as "the thing I just stopped is still running"."""
    fake = _FakeRedis()
    monkeypatch.setattr(chat_inflight, "_r", fake)

    assert chat_inflight._acquire_sync(AUTHED_USER, "conv-a") is True

    resp = await client.post("/hr-assist-stop", json={"conversation_id": "conv-a"})
    assert resp.status_code == 200
    assert resp.json()["success"] is True

    assert chat_inflight._acquire_sync(AUTHED_USER, "conv-a") is True,         "resend must be accepted"


async def test_stop_on_a_thread_holding_nothing_is_harmless(client, monkeypatch):
    """Stop is fire-and-forget from the client, and the generator's own finally
    may well have released first. Calling it twice must not error."""
    monkeypatch.setattr(chat_inflight, "_r", _FakeRedis())

    for _ in range(2):
        resp = await client.post("/hr-assist-stop", json={"conversation_id": "conv-a"})
        assert resp.status_code == 200


async def test_stop_only_frees_the_thread_it_was_given(client, monkeypatch, lock_on):
    """A Stop in one chat must not cancel the guard on another."""
    fake = _FakeRedis()
    monkeypatch.setattr(chat_inflight, "_r", fake)
    chat_inflight._acquire_sync(AUTHED_USER, "conv-a")
    chat_inflight._acquire_sync(AUTHED_USER, "conv-b")

    await client.post("/hr-assist-stop", json={"conversation_id": "conv-a"})

    assert chat_inflight._acquire_sync(AUTHED_USER, "conv-b") is False


async def test_stop_requires_a_token(unauth_client):
    resp = await unauth_client.post("/hr-assist-stop", json={"conversation_id": "c"})
    assert resp.status_code in (401, 422)
