"""Leave codes on their own ("el", "cl", "sl", "shl", "compoff", "lwp").

Reported live, as a manager:
  * "el" / "cl" / "sl" rendered as EMPTY bubbles — the reply carried no chunk
    event — and were tagged intent "policy" though they ask a question back.
  * "shl" went to the employee search ("No matching employee"): fast_classify
    scores casual/sick/earned as a bare leave-type mention but not short
    leave, comp off or LWP, so they fell to the manager's bare-name lookup.
  * with that picker up, "compoff", "no i mean comp off" and "no i mean comp
    off for leave" each re-showed it. A bare leave type after a manager's
    lookup is read as narrowing THAT person — even when the lookup found
    nobody — so it went back to the lookup, which re-showed the picker.

Now every leave code gets the same "balance / applied / eligibility / apply?"
clarification, streamed with its text; a correction opener is dropped; and a
waiting picker is dismissed instead of capturing the reply. A leave type after
a lookup that DID find a person still narrows that person, as before.
"""
import pytest

import services.classify_node as classify_node
from services import leave_slot_service

COMPANY_ID = 1


@pytest.fixture(autouse=True)
def _no_llm(monkeypatch):
    async def _no_shift(q):
        return None, 0.0, None

    async def _unsure(prompt, labels, fallback_label="unknown"):
        return fallback_label, None, True

    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _unsure)


def _state(query, conversation_id, last_intent=None):
    return {"query": query, "company_id": COMPANY_ID, "conversation_id": conversation_id,
            "bearer_token": "t", "usage_events": [], "is_manager": True, "is_manager_jwt": True,
            "last_intent": last_intent}


async def _classify(query, conversation_id, last_intent=None):
    events = []
    out = await classify_node.classify_node(_state(query, conversation_id, last_intent), events.append)
    return out, events


class TestEveryLeaveCodeIsAClarification:
    @pytest.mark.parametrize("query,slug", [
        ("el", "earned_leave"), ("cl", "casual_leave"), ("sl", "sick_leave"),
        ("shl", "short_leave"),               # reported: employee search
        ("short leave", "short_leave"),
    ])
    async def test_a_code_alone_asks_what_they_want(self, query, slug):
        out, events = await _classify(query, f"codes-{query}")

        assert out["intent"] == "leave_type_clarify"
        assert [e["type"] for e in events] == ["intent", "chunk", "done"]
        chunk, done = events[1], events[2]
        # The text is streamed, so the bubble is never empty.
        assert chunk["content"] == done["message"]
        assert "leave balance" in done["message"]
        assert "leave policy" in done["message"]
        assert done["intent"] == "clarify_needed"
        assert done["data"]["leave_type"] == slug
        # balance, applied, eligibility, apply — and the leave policy.
        assert len(done["data"]["options"]) == 5
        assert done["data"]["options"][-1].lower().endswith("leave policy")

    def test_a_code_is_never_read_as_a_name(self):
        for query in ("shl", "compoff", "lwp", "el"):
            assert classify_node._is_bare_person_fragment(query, False) is False, query


class TestNoPickerLoop:
    def _leave_picker_up(self, conversation_id):
        """A manager lookup that matched nobody: picker waiting, no subject."""
        leave_slot_service.set_report_state(COMPANY_ID, conversation_id, {
            "step": "awaiting_employee_selection", "intent": "manager_leave_request_lookup",
            "candidates": [{"employee_id": 6112, "employee_name": "Aa employee"},
                           {"employee_id": 7534, "employee_name": "AA GEO"}],
        })

    @pytest.mark.parametrize("reply,intent", [
        ("compoff", "policy"), ("no i mean comp off", "policy"),
        ("no i mean comp off for leave", "policy"), ("actually sick leave", "leave_type_clarify"),
    ])
    async def test_a_leave_type_with_a_picker_up_escapes_it(self, reply, intent):
        cid = f"picker-{reply}"
        self._leave_picker_up(cid)
        out, events = await _classify(reply, cid, last_intent="manager_leave_request_lookup")

        assert out["intent"] == intent, "sent back to the employee picker"
        # The picker no longer captures the next reply.
        assert (leave_slot_service.get_report_state(COMPANY_ID, cid) or {}).get("step") \
            != "awaiting_employee_selection"
        leave_slot_service.clear_report_state(COMPANY_ID, cid)

    async def test_a_leave_type_after_a_found_person_still_narrows_that_person(self):
        """The rule the loop broke: after "show A Khan Test leave requests",
        "casual leave" means HIS casual leave, not the caller's menu."""
        cid = "subject-established"
        leave_slot_service.set_report_state(COMPANY_ID, cid, {
            "last_employee": {"employee_id": 692, "employee_name": "A Khan Test"}})
        out, _ = await _classify("casual leave", cid, last_intent="manager_leave_request_lookup")

        assert out["intent"] != "leave_type_clarify"
        leave_slot_service.clear_report_state(COMPANY_ID, cid)


class TestCorrectionPrefix:
    @pytest.mark.parametrize("query,expected", [
        ("no i mean comp off", "comp off"),
        ("no i mean comp off for leave", "comp off for leave"),
        ("actually sick leave", "sick leave"),
        ("sorry, I meant EL", "EL"),
        ("comp off", "comp off"),
        ("no", "no"),
    ])
    def test_the_opener_is_dropped(self, query, expected):
        assert classify_node._without_correction_prefix(query) == expected


class TestPolicyOnlyTypes:
    """Comp off and leave without pay relate only to the leave policy — no
    balance, applied list, eligibility or application of their own here — so
    a bare mention goes straight to their policy, not to a menu."""

    @pytest.mark.parametrize("query,expected_query", [
        ("comp-off", "what is the comp off (compensatory off) policy"),   # reported
        ("compoff", "what is the comp off (compensatory off) policy"),
        ("comp off", "what is the comp off (compensatory off) policy"),
        ("lwp", "what is the leave without pay (LWP) policy"),
        ("leave without pay", "what is the leave without pay (LWP) policy"),
    ])
    async def test_goes_straight_to_the_policy(self, query, expected_query):
        out, events = await _classify(query, f"policy-only-{query}")

        assert out["intent"] == "policy"
        assert out["query"] == expected_query
        assert [e["type"] for e in events] == ["intent"]
        assert events[0]["intent"] == "policy"


class TestReplyingToTheMenu:
    @pytest.mark.parametrize("reply", ["policy", "leave policy", "show the rules", "el policy"])
    async def test_policy_answers_that_types_policy(self, reply):
        cid = f"menu-{reply}"
        await _classify("el", cid)                       # asks the question
        out, _ = await _classify(reply, cid)

        assert out["intent"] == "policy"
        assert out["query"] == "what is the earned leave policy"

    @pytest.mark.parametrize("reply,intent", [
        ("balance", "leave_balance"), ("apply", "apply_leave"),
        ("eligibility", "leave_eligibility"), ("applied", "leave_status"),
    ])
    async def test_the_other_choices_are_unchanged(self, reply, intent):
        cid = f"menu-other-{reply}"
        await _classify("el", cid)
        out, _ = await _classify(reply, cid)
        assert out["intent"] == intent


class TestUnknownLeaveCode:
    """"pl" / "tl" — a leave code this app doesn't have. Live, a manager's "pl"
    became an employee search and an employee's went unanswered. It now lists
    the leave types there are, with their codes, and what can be done."""

    @pytest.mark.parametrize("query,code", [
        ("pl", "PL"), ("tl", "TL"), ("ml", "ML"), ("p.l.", "PL"), ("pl leave", "PL"), ("TL", "TL"),
    ])
    @pytest.mark.parametrize("is_manager", [False, True])
    async def test_lists_the_supported_types(self, query, code, is_manager):
        events = []
        out = await classify_node.classify_node(
            {**_state(query, f"unknown-{is_manager}-{query}"), "is_manager": is_manager},
            events.append)

        assert out["intent"] == "unknown_leave_type"
        assert [e["type"] for e in events] == ["intent", "chunk", "done"]
        done = events[-1]
        assert done["intent"] == "clarify_needed"
        assert done["data"]["unknown_leave_code"] == code
        assert done["data"]["options"] == ["Casual Leave", "Sick Leave", "Earned Leave", "Short Leave"]
        for name_and_code in ("Casual Leave** (CL)", "Sick Leave** (SL)",
                              "Earned Leave** (EL)", "Short Leave** (SHL)"):
            assert name_and_code in done["message"]
        for capability in ("balance", "applied leaves", "eligibility", "apply for leave",
                           "leave policy", "regularization"):
            assert capability in done["message"]

    @pytest.mark.parametrize("query", ["cl", "sl", "el", "shl", "all", "tell", "call", "ok", "hello"])
    def test_a_known_code_or_a_word_is_not_unknown(self, query):
        assert classify_node._unknown_leave_code(query) is None

    def test_the_graph_ends_the_turn_there(self):
        import services.hr_graph as hr_graph
        from langgraph.graph import END
        assert hr_graph._route_after_classify({"intent": "unknown_leave_type"}) == END
