"""main._finalize_ai_stream with no `done` event to finalize.

It runs from the `finally` of _ai_stream, so it is reached on EVERY exit
path, including the ones that never produced a `done` event and therefore
never assigned full_result:

  * an exception caught by the handler above it;
  * the client disconnecting mid-stream - CancelledError is not an
    Exception, so it unwinds straight past that handler.

Three reads in there dereferenced full_result unguarded. Because the raise
happened inside a `finally`, it REPLACED whatever was already unwinding:
the real stream error was logged and then buried under

    AttributeError: 'NoneType' object has no attribute 'get'

surfacing at the ASGI layer. These tests pin the guard, and - the part that
actually matters - that a failed turn is still logged rather than lost.
"""

import pytest
from unittest.mock import MagicMock

import main


@pytest.fixture
def captured(monkeypatch):
    """Neutralise the finalizer's three side effects, capturing the HR log."""
    calls = {"hr_log": [], "cache": [], "usage": []}

    async def _run_in_threadpool(fn, *args, **kwargs):
        if fn is main.store_hr_log:
            calls["hr_log"].append(kwargs)
        elif fn is main.set_cached_query:
            calls["cache"].append(args)
        elif fn is main._record_usage_events:
            calls["usage"].append(args)
        return None

    monkeypatch.setattr(main, "run_in_threadpool", _run_in_threadpool)
    return calls


def finalize(full_result, status="failure", detected_intent="leave_status",
             is_fresh_query=True, extra_usage_events=None):
    return main._finalize_ai_stream(
        full_result, detected_intent, status, is_fresh_query,
        "show my leave status", {"company_id": 1, "user_id": 7}, MagicMock(),
        start_time=0.0, ai_time=0.1,
        conversation_id="conv-1", company_id=1, true_company_id=1, role_id=2,
        extra_usage_events=extra_usage_events,
    )


class TestStreamEndedWithoutDone:

    async def test_none_full_result_does_not_raise(self, captured):
        """The regression itself: this used to raise AttributeError from
        inside a `finally` and mask the real stream failure."""
        await finalize(None)

    async def test_the_failed_turn_is_still_logged(self, captured):
        await finalize(None, status="failure")

        assert len(captured["hr_log"]) == 1
        logged = captured["hr_log"][0]
        assert logged["status"] == "failure"
        # Falls back to the intent classification already resolved upstream,
        # so a crashed turn is still attributed to the right intent.
        assert logged["intent"] == "leave_status"
        assert logged["response"]["success"] is False
        assert logged["response"]["data"] is None

    async def test_nothing_is_cached_from_a_turn_that_never_answered(self, captured):
        await finalize(None)
        assert captured["cache"] == [], "an empty answer must never be cached"

    async def test_usage_recorded_before_the_failure_is_not_lost(self, captured):
        """Tokens were spent even though the stream died - the title call
        here - so they still have to be billed."""
        await finalize(None, extra_usage_events=[
            {"source": "title", "usage": {"prompt_tokens": 10, "completion_tokens": 2}}])

        assert len(captured["usage"]) == 1


class TestNormalDonePathIsUnchanged:

    DONE = {
        "intent": "team_leave_restricted",
        "is_hr": True,
        "data": {"answer": "Team leave summaries are available to managers."},
        "usage_events": [{"source": "classify", "usage": {"prompt_tokens": 5}}],
    }

    async def test_the_events_intent_wins_over_the_upstream_guess(self, captured):
        await finalize(self.DONE, status="success", detected_intent="general")

        logged = captured["hr_log"][0]
        assert logged["intent"] == "team_leave_restricted"
        assert logged["response"]["intent"] == "team_leave_restricted"
        assert logged["response"]["success"] is True
        assert logged["response"]["data"] == self.DONE["data"]

    async def test_an_event_without_an_intent_falls_back(self, captured):
        await finalize({**self.DONE, "intent": None}, status="success",
                       detected_intent="leave_status")

        assert captured["hr_log"][0]["intent"] == "leave_status"

    async def test_a_successful_answer_is_cached(self, captured):
        # Not the class's own DONE: "team_leave_restricted" is a refusal
        # CARD and is deliberately uncacheable now - see the test below.
        cacheable = {**self.DONE, "intent": "general",
                     "data": {"answer": "Casual leave accrues monthly."}}
        await finalize(cacheable, status="success", detected_intent="general")

        assert len(captured["cache"]) == 1
        assert captured["cache"][0][2]["result"] == cacheable["data"]["answer"]

    async def test_a_manager_only_refusal_is_never_cached(self, captured):
        """HA-193 - the refusal renders as the Figma's "Not available" card,
        and the query cache holds only the answer text. Caching it meant the
        next conversation replayed the two sentences as a plain bubble with
        the card payload gone, which is how the card came and went."""
        await finalize(self.DONE, status="success", detected_intent="general")

        assert captured["cache"] == []

    async def test_usage_events_from_the_turn_are_recorded(self, captured):
        await finalize(self.DONE, status="success")
        assert len(captured["usage"]) == 1


class TestRefusalsAreUncacheableOnBothSides:
    """The write side is pinned above; this is the read side.

    Entries written before HA-193 are still in Redis until REDIS_EXPIRATION
    elapses, and the same set is what _ai_stream's cache-hit gate consults -
    so listing the refusal intents there is also what discards a stale one
    instead of replaying it as a bubble.
    """

    @pytest.mark.parametrize("intent", [
        "team_leave_restricted",
        "team_attendance_restricted",
        "team_members_restricted",
    ])
    def test_a_cached_refusal_is_not_served(self, intent):
        assert intent in main._STATEFUL_QUERY_INTENTS
