"""'cancel a khan test' calls off an APPROVAL - it is not the caller's own leave.

Reported: a manager stood an approval down with "no" (answered correctly),
then typed "cancel a khan test" and was shown their OWN five leave requests -

    Your Leave Requests (5 requests)
    Could you let me know which one you'd like to cancel - by its leave type,
    leave date, applied date, number, or reference?
    ... Showing only your own requests ...

The message names a TEAM MEMBER. Answering it with the caller's own leave
list is the wrong person's data, and it left the manager one reply away from
cancelling a real leave of their own - an actual, unintended change.

The LLM labelled it cancel_leave, which is a reasonable reading of the verb
alone. The discriminator is the OBJECT: "cancel my leave" is the caller's own
flow and stays there; "cancel <someone>" is calling off an approval.

Calling an approval off never changes the request. The reply says so, and
names the person, so a manager who expected something to happen to that
request is not left guessing.
"""

import pytest
from unittest.mock import patch, AsyncMock, MagicMock

import services.hr_graph as hr_graph
import services.classify_node as classify_node
import services.leave_approval as leave_approval
from services.leave_approval import leave_approval_node


APPROVE_CARD = {
    "kind": leave_approval.CARD_KIND, "step": "awaiting_confirmation",
    "action": "approve", "leave_request_id": 310,
    "card": {"employee_name": "A Khan Test", "employee_number": "em6",
             "employee_id": 692, "leave_request_id": 310, "action": "approve"},
}


class FakeWriter:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def of_type(self, etype):
        return [e for e in self.events if e.get("type") == etype]


@pytest.fixture(autouse=True)
def action_store(monkeypatch):
    store = {}
    monkeypatch.setattr(leave_approval.leave_slot_service, "get_manager_action",
                        lambda c, k: store.get((str(c), k)))
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_manager_action",
                        lambda c, k, v: bool(store.__setitem__((str(c), k), v)) or True)
    monkeypatch.setattr(leave_approval.leave_slot_service, "clear_manager_action",
                        lambda c, k: store.pop((str(c), k), None))
    monkeypatch.setattr(leave_approval.leave_slot_service, "get_report_state",
                        lambda c, k: None)
    monkeypatch.setattr(leave_approval.leave_slot_service, "set_report_state",
                        lambda c, k, v: True)
    return store


@pytest.fixture(autouse=True)
def erp(monkeypatch):
    """Records anything actually executed. Nothing here may execute."""
    approved = []

    async def _approve(token, leave_request_id, company_id=None, conversation_id=None):
        approved.append(leave_request_id)
        return {"http_status": 200, "body": {"success": True, "data": {}}}

    async def _pending(token, company_id=None, conversation_id=None,
                       employee_id=None, employee_name=None):
        return {"http_status": 200, "body": {"success": True, "data": {
            "total_pending_leaves": 0, "leaves": []}}}

    monkeypatch.setattr(leave_approval.erp_client, "approve_leave_request", _approve)
    monkeypatch.setattr(leave_approval.erp_client, "get_team_pending_leaves", _pending)
    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields",
                        AsyncMock(return_value=(
                            {"action": None, "leave_request_id": None,
                             "employee_id": None, "employee_name": None,
                             "uses_pronoun": False, "targets_multiple": False}, None)))
    return approved


def state(query, is_manager=True):
    return {"query": query, "context": [], "bearer_token": "t", "company_id": 1,
            "conversation_id": "conv-1", "usage_events": [],
            "is_manager": is_manager, "intent": "general", "last_intent": None,
            "has_date_expression": False}


# =============================================================================
# The discriminator
# =============================================================================

class TestWhatCountsAsCallingAnApprovalOff:

    @pytest.mark.parametrize("query", [
        "cancel a khan test",
        "cancel abc testing",
        "stop a khan test",
        "cancel approval for a khan test",
        "cancel the approval for a khan test",
        "call off the approval for abc testing",
    ])
    def test_naming_somebody_calls_the_approval_off(self, query):
        assert leave_approval.is_cancel_approval_instruction(query) is True

    @pytest.mark.parametrize("query", [
        "cancel my leave",
        "cancel my sick leave",
        "cancel leave",
        "cancel leave request",
        "cancel",
        "no",
        "cancel my leave request for tomorrow",
    ])
    def test_the_callers_own_cancellation_is_left_alone(self, query):
        """The whole feature turns on this: a cancel verb with no other
        person named is the caller's own leave, and must keep its own flow."""
        assert leave_approval.is_cancel_approval_instruction(query) is False

    @pytest.mark.parametrize("query", [
        "cancel and approve request 61",
        "cancel and approve priya",
        "no, approve 400 instead",
        "cancel this and reject 310",
    ])
    def test_a_decline_that_re_aims_is_not_a_stand_down(self, query):
        """"cancel and approve request 61" calls THIS one off and asks for
        another - it says what to do next, so it belongs to the re-aim path.
        A message carrying its own action verb, or naming its own request, is
        never a stand-down."""
        assert leave_approval.is_cancel_approval_instruction(query) is False

    @pytest.mark.parametrize("query,subject", [
        ("cancel a khan test", "A Khan Test"),
        ("stop a khan test", "A Khan Test"),
        ("cancel approval for a khan test", "A Khan Test"),
        ("cancel the approval for a khan test", "A Khan Test"),
    ])
    def test_the_name_survives_intact(self, query, subject):
        """"A Khan Test" begins with an article. Stripping instruction words
        wherever they appeared turned the name into "Khan Test"."""
        assert leave_approval._stood_down_subject(query) == subject


# =============================================================================
# Routing
# =============================================================================

def _classifier(llm_says="cancel_leave", real_approval_resolver=False):
    """`real_approval_resolver` leaves leave_approval's own pending-card
    lookup in place, so a card armed in action_store is actually found. The
    default stubs it out, for the cases where no card exists."""
    none_pending = MagicMock(return_value=None)
    approval_resolver = (leave_approval.resolve_pending_approval_intent
                         if real_approval_resolver else none_pending)
    return patch.multiple(
        classify_node,
        classify_intent_structured=AsyncMock(return_value=(llm_says, None, False)),
        _check_moderation=AsyncMock(return_value={"flagged": False}),
        _resolve_shift_route=AsyncMock(return_value=(None, 0.0, None)),
        _resolve_individual_report_route=AsyncMock(return_value=(None, 0.0, None)),
        leave_slot_service=MagicMock(get_slots=MagicMock(return_value=None)),
        leave_cancel_state=MagicMock(get_state=MagicMock(return_value=None)),
        # A regularisation mid-flow left behind by another test module
        # otherwise claims these turns - slot_store is a SEPARATE store
        # from leave_slot_service and needs neutralising of its own.
        slot_store=MagicMock(get_slots=MagicMock(return_value=None)),
    ), patch.object(classify_node.leave_approval,
                    "resolve_pending_approval_intent", approval_resolver), \
        patch.object(classify_node.regularisation_approval,
                     "resolve_pending_regularisation_intent", none_pending), \
        patch.object(classify_node.individual_report,
                     "resolve_pending_selection_intent", none_pending)


class TestItRoutesAwayFromTheOwnCancelFlow:

    @pytest.mark.parametrize("query", ["cancel a khan test", "cancel abc testing",
                                       "stop a khan test"])
    async def test_it_goes_to_the_approval_node(self, query):
        """Even with the LLM insisting on cancel_leave, which is what it
        actually answered live."""
        outer, a, b, c = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(state(query), FakeWriter())

        assert result["intent"] == "manager_leave_approval"
        assert hr_graph._route_after_classify(result) == "leave_approval_node"

    @pytest.mark.parametrize("query", ["cancel my leave", "cancel leave"])
    async def test_the_own_cancel_flow_is_untouched(self, query):
        outer, a, b, c = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(state(query), FakeWriter())

        assert result["intent"] == "cancel_leave"
        assert hr_graph._route_after_classify(result) == "leave_action_node"

    async def test_a_non_manager_keeps_the_own_cancel_flow(self):
        """Only a manager has approvals to call off."""
        outer, a, b, c = _classifier()
        with outer, a, b, c:
            result = await hr_graph.classify_node(
                state("cancel a khan test", is_manager=False), FakeWriter())

        assert result["intent"] == "cancel_leave"


# =============================================================================
# The answer
# =============================================================================

class TestABareCancelReachesTheCard:
    """The worst of these bugs, verified live:

        approve card showing  ->  "cancel"
        "What would you like to cancel?  - Leave request"     <- card still armed
                              ->  "yes"   (meaning yes, cancel it)
        "Approved - ABC Testing's Sick Leave request is now approved."

    The manager said CANCEL and the leave was APPROVED.

    classify_node's bare-verb clarify caught the lone "cancel" and asked what
    they meant, leaving the approval card armed behind it - so the "yes" that
    answered the clarify question reached the card instead. That block's own
    comment states the invariant it relied on ("every mid-flow block above
    gets first refusal ... by the time control reaches here, no flow is
    active"); the pending-card check simply sat below it rather than above.

    leave_approval already answers a bare "cancel" correctly. It only had to
    be given the turn.
    """

    @pytest.mark.parametrize("reply", ["cancel", "no", "stop", "nevermind"])
    async def test_a_bare_decline_reaches_the_approval_node(self, reply, action_store):
        action_store[("1", "conv-1")] = dict(APPROVE_CARD)

        outer, a, b, c = _classifier(llm_says="general_hr", real_approval_resolver=True)
        with outer, a, b, c:
            result = await hr_graph.classify_node(state(reply), FakeWriter())

        assert result["intent"] == "manager_leave_approval", \
            f"{reply!r} must reach the card, not the bare-verb clarify"
        assert result["intent"] != "clarify_needed"

    async def test_cancel_stands_the_card_down(self, action_store, erp):
        action_store[("1", "conv-1")] = dict(APPROVE_CARD)

        result = await leave_approval_node(state("cancel"), FakeWriter())

        assert "Nothing has been changed" in result["response_text"]
        assert action_store.get(("1", "conv-1")) is None
        assert erp == []

    async def test_the_reported_sequence_approves_nothing(self, action_store, erp):
        """cancel -> yes, end to end. The yes must find no card waiting."""
        action_store[("1", "conv-1")] = dict(APPROVE_CARD)

        await leave_approval_node(state("cancel"), FakeWriter())
        assert action_store.get(("1", "conv-1")) is None

        outer, a, b, c = _classifier(llm_says="general_hr", real_approval_resolver=True)
        with outer, a, b, c:
            follow_up = await hr_graph.classify_node(state("yes"), FakeWriter())

        assert follow_up["intent"] != "manager_leave_approval", \
            "a yes after cancelling must not be routed back to an approval"
        assert erp == [], "the leave the manager cancelled must never be approved"

    async def test_a_bare_verb_with_no_card_still_asks(self, action_store):
        """The clarify is right when there IS no flow - that is what it is
        for, and it must keep working."""
        outer, a, b, c = _classifier(llm_says="general_hr", real_approval_resolver=True)
        with outer, a, b, c:
            result = await hr_graph.classify_node(state("cancel"), FakeWriter())

        assert result["intent"] == "clarify_needed"


class TestTheAnswer:

    async def test_with_a_card_armed_it_says_the_request_is_untouched(
            self, action_store, erp):
        action_store[("1", "conv-1")] = dict(APPROVE_CARD)

        result = await leave_approval_node(state("cancel a khan test"), FakeWriter())

        assert "A Khan Test" in result["response_text"]
        assert "Nothing has been changed" in result["response_text"]
        assert action_store.get(("1", "conv-1")) is None

    async def test_with_nothing_armed_it_still_answers_about_that_person(
            self, action_store, erp):
        """The reported turn - the approval had already been stood down by
        "no", so there was no card left to find."""
        result = await leave_approval_node(state("cancel a khan test"), FakeWriter())

        assert "A Khan Test" in result["response_text"]
        assert "unchanged" in result["response_text"]
        assert "still pending" in result["response_text"]

    async def test_it_never_lists_the_callers_own_leaves(self, action_store, erp):
        """The bug, stated directly."""
        result = await leave_approval_node(state("cancel a khan test"), FakeWriter())

        text = result["response_text"]
        assert "your own requests" not in text.lower()
        assert "which one you'd like to cancel" not in text.lower()

    async def test_nothing_is_approved_or_cancelled(self, action_store, erp):
        action_store[("1", "conv-1")] = dict(APPROVE_CARD)

        await leave_approval_node(state("cancel a khan test"), FakeWriter())

        assert erp == [], "calling an approval off must change nothing"

    async def test_no_card_event_is_emitted(self, action_store, erp):
        writer = FakeWriter()
        await leave_approval_node(state("cancel a khan test"), writer)

        assert writer.of_type("leave_approval_confirmation") == []
