"""FR-08 / FR-09 at the request level: what the analytics row says, and when
the general-chat allowance is spent.

Review findings these pin down: a blocked input and a crashed HR turn are
carried with is_hr=False, and the category was derived from that, so every one
of them was counted as GENERAL chat; a general-chat turn that produced no
answer was logged as status "success"; failure_stage was never written.
"""
from unittest.mock import patch

import pytest

import main
from tests.conftest import TEST_CONV_ID
from tests.test_api import _blocked_astream, collect_stream, stream_mocks  # noqa: F401


@pytest.fixture(autouse=True)
def flag(monkeypatch):
    """The lane on, nothing used yet - each test overrides what it needs."""
    monkeypatch.setattr(main.feature_flag_service, "is_enabled", lambda *a, **k: True)
    monkeypatch.setattr(main, "count_recent_turns", lambda *a, **k: 0)


def _logged(stream_mocks):
    return stream_mocks["store_hr_log"].call_args.kwargs


async def test_a_blocked_input_is_not_counted_as_general(client, stream_mocks):
    with patch.object(main.hr_graph, "astream", side_effect=_blocked_astream):
        await collect_stream(client, {"query": "x", "conversation_id": TEST_CONV_ID})
    row = _logged(stream_mocks)
    assert row["status"] == "blocked"
    assert row["category"] is None
    assert row["failure_stage"] == "input_guardrail"


async def test_a_crashed_hr_turn_keeps_its_hr_category(client, stream_mocks):
    async def _crash(state, stream_mode=None):
        yield {"type": "intent", "intent": "leave_balance", "is_hr": True}
        yield {"type": "error", "message": "boom"}

    with patch.object(main.hr_graph, "astream", side_effect=_crash):
        await collect_stream(client, {"query": "my leave balance", "conversation_id": TEST_CONV_ID})
    row = _logged(stream_mocks)
    assert row["status"] == "fallback"
    assert row["category"] == "hrms_action"
    assert row["failure_stage"] == "graph"


@pytest.mark.parametrize("stage, status", [
    ("general_chat_llm", "failure"),
    ("general_chat_rate_limited", "rate_limited"),
])
async def test_a_general_non_answer_is_not_a_success(client, stream_mocks, stage, status):
    async def _general(state, stream_mode=None):
        yield {"type": "intent", "intent": "non_hr", "is_hr": False}
        yield {"type": "done", "intent": "general_chat", "is_hr": False,
               "data": {"answer": "sorry"}, "message": "sorry", "failure_stage": stage}

    with patch.object(main.hr_graph, "astream", side_effect=_general):
        events = await collect_stream(client, {"query": "explain x", "conversation_id": TEST_CONV_ID})
    row = _logged(stream_mocks)
    assert row["status"] == status
    assert row["category"] == "general"
    assert row["failure_stage"] == stage
    # Internal only - never on the wire.
    done = next(e for e in events if e["type"] == "done")
    assert "failure_stage" not in done


async def test_a_general_answer_is_a_success(client, stream_mocks):
    async def _general(state, stream_mode=None):
        yield {"type": "intent", "intent": "non_hr", "is_hr": False}
        yield {"type": "done", "intent": "general_chat", "is_hr": False,
               "data": {"answer": "Revenue is..."}, "message": "Revenue is..."}

    with patch.object(main.hr_graph, "astream", side_effect=_general):
        await collect_stream(client, {"query": "explain x", "conversation_id": TEST_CONV_ID})
    row = _logged(stream_mocks)
    assert (row["status"], row["category"], row["failure_stage"]) == ("success", "general", None)


@pytest.mark.parametrize("value, limit", [("30", 30), ("5", 5), ("0", 0), ("-1", -1), ("lots", 30)])
def test_the_hourly_limit_setting(monkeypatch, value, limit):
    monkeypatch.setenv("GENERAL_CHAT_HOURLY_LIMIT", value)
    assert main._general_chat_hourly_limit() == limit


# Product decision (fcc303a, 12 Oct): the general-chat lane is off whatever the
# feature flag says - non-HR questions go to non_hr_node. So the allowance is
# never counted and never spent, even with the flag on and the hour used up.
# This test expected the pre-decision behaviour (30 of 30 used -> over limit).
@pytest.mark.parametrize("used, limit", [(29, "30"), (30, "30"), (500, "0")])
async def test_the_hourly_allowance_is_off_with_the_lane(client, stream_mocks, monkeypatch, used, limit):
    def _never(*a, **k):
        raise AssertionError("counted while the general lane is off")

    monkeypatch.setattr(main, "count_recent_turns", _never)
    monkeypatch.setenv("GENERAL_CHAT_HOURLY_LIMIT", limit)
    seen = {}

    async def _capture(state, stream_mode=None):
        seen.update(state)
        yield {"type": "done", "intent": "leave_policy", "is_hr": True,
               "data": {"answer": "ok"}, "message": "ok"}

    with patch.object(main.hr_graph, "astream", side_effect=_capture):
        await collect_stream(client, {"query": "q", "conversation_id": TEST_CONV_ID})
    assert seen["general_chat_over_limit"] is False
    assert seen["general_chat_enabled"] is False


async def test_the_allowance_is_not_counted_with_the_lane_off(client, stream_mocks, monkeypatch):
    monkeypatch.setattr(main.feature_flag_service, "is_enabled", lambda *a, **k: False)

    def _never(*a, **k):
        raise AssertionError("counted with the lane off")

    monkeypatch.setattr(main, "count_recent_turns", _never)

    async def _hr(state, stream_mode=None):
        yield {"type": "done", "intent": "leave_policy", "is_hr": True,
               "data": {"answer": "ok"}, "message": "ok"}

    with patch.object(main.hr_graph, "astream", side_effect=_hr):
        await collect_stream(client, {"query": "q", "conversation_id": TEST_CONV_ID})
