"""When the current message overrides the flow it arrives in.

Three reported cases, all one question: does THIS message decide the turn, or
does the flow that is already open?

1. SAYING THE OPPOSITE ACTION STANDS THE CARD DOWN.
   "reject" at an approve card is not a confirmation and not a re-aim - it
   says the manager does not want the approval being offered. It used to fall
   through to be re-read as a fresh instruction, which rebuilt the SAME
   approve card and left it armed. Verified before the fix:

       approve 310  ->  "reject"  ->  "yes"   ==>  request 310 APPROVED

   The manager said reject and the request was approved.

2. NAMING ANOTHER REQUEST RE-AIMS THE CARD.
   A different request ID or team member at the card is a new target, and the
   confirm flow should continue with that one.

3. AN EXPLICIT INSTRUCTION ESCAPES AN OPEN FLOW.
   Mid-cancellation, "approve leave" means approve - the cancel flow must not
   claim it. fast_classify has no approve/reject vocabulary (it scores
   "approve leave" 0.0), so this never registered as an interruption and the
   message was read against a cancel-biased prompt.

The counterweight, asserted throughout: a message that IS an answer to the
open flow ("yes", "the second one") must keep belonging to it, and a question
must never decide anything.
"""

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


ROW_310 = {
    "id": 310, "employee_id": 692, "employee_number": "em6",
    "employee_name": "A Khan Test", "employee_designation": "IT",
    "leave_type": "Short Leave", "leave_type_slug": "short_leave",
    "session_type": "Full Day", "from_date": "2026-09-16",
    "to_date": "2026-09-16", "leave_count": "1", "status_name": "pending",
    "reason": "work", "applied_date": "2026-09-17",
}
ROW_400 = {**ROW_310, "id": 400, "employee_id": 489, "employee_number": "test07",
           "employee_name": "ABC Testing", "leave_type": "Sick Leave",
           "leave_type_slug": "sick_leave", "from_date": "2026-09-22",
           "to_date": "2026-09-22"}

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",
             "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))
    return store


@pytest.fixture(autouse=True)
def _report_store(monkeypatch):
    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)


@pytest.fixture(autouse=True)
def _audit(monkeypatch):
    import services.audit_log_service as audit_log_service
    monkeypatch.setattr(audit_log_service, "_write", lambda **fields: None)


@pytest.fixture
def rows(monkeypatch):
    """What erp-api returns for a pending lookup. Mutable so a test can point
    it at a different request before re-aiming the card."""
    current = [ROW_310]

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

    monkeypatch.setattr(leave_approval.erp_client, "get_team_pending_leaves", _pending)
    return current


@pytest.fixture
def erp(monkeypatch, rows):
    """Every approval actually executed against erp-api."""
    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": {}}}

    monkeypatch.setattr(leave_approval.erp_client, "approve_leave_request", _approve)
    return approved


def extraction(monkeypatch, action=None, rid=None, name=None):
    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields",
                        AsyncMock(return_value=(
                            {"action": action, "leave_request_id": rid,
                             "employee_id": None, "employee_name": name,
                             "uses_pronoun": False, "targets_multiple": False}, None)))


def state(query):
    return {"query": query, "intent": "leave_approval", "usage_events": [],
            "bearer_token": "t", "company_id": 1, "conversation_id": "conv-1",
            "is_manager": True}


def arm(action_store):
    action_store[("1", "conv-1")] = dict(APPROVE_CARD)


# =============================================================================
# 1 - The opposite action stands the approval down
# =============================================================================

class TestTheOppositeActionStandsTheCardDown:

    @pytest.mark.parametrize("reply", ["reject", "reject it", "deny", "decline it",
                                       "reject this request"])
    async def test_the_pending_approval_is_cleared(self, monkeypatch, erp, action_store, reply):
        arm(action_store)
        extraction(monkeypatch, action="reject")

        await leave_approval_node(state(reply), FakeWriter())

        assert action_store.get(("1", "conv-1")) is None, \
            f"{reply!r} must not leave an approve card armed"

    @pytest.mark.parametrize("reply", ["reject", "deny", "reject it"])
    async def test_it_does_not_re_show_the_approve_card(self, monkeypatch, erp, action_store, reply):
        arm(action_store)
        extraction(monkeypatch, action="reject")

        result = await leave_approval_node(state(reply), FakeWriter())

        assert "Please confirm this action" not in result["response_text"]

    async def test_the_reported_hazard_reject_then_yes(self, monkeypatch, erp, action_store):
        """The exact sequence that approved a request the manager rejected."""
        arm(action_store)
        extraction(monkeypatch, action="reject")
        await leave_approval_node(state("reject"), FakeWriter())

        extraction(monkeypatch, action=None)
        await leave_approval_node(state("yes"), FakeWriter())

        assert erp == [], "a rejected request must never end up approved"

    async def test_a_plain_no_still_works(self, monkeypatch, erp, action_store):
        arm(action_store)
        extraction(monkeypatch)

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

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

    async def test_cancel_still_works(self, monkeypatch, erp, action_store):
        arm(action_store)
        extraction(monkeypatch)

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

        assert erp == []
        assert "Nothing has been changed" in result["response_text"]

    async def test_yes_still_approves(self, monkeypatch, erp, action_store):
        """The counterweight - standing down on the opposite verb must not
        make the card harder to confirm."""
        arm(action_store)
        extraction(monkeypatch)

        await leave_approval_node(state("yes"), FakeWriter())

        assert erp == [310]

    @pytest.mark.parametrize("question", [
        "what happens if I reject?", "can I reject this instead?",
        "did you reject it?",
    ])
    def test_a_question_about_rejecting_is_not_a_decision(self, question):
        assert leave_approval._asks_the_opposite_action(question, APPROVE_CARD) is False

    @pytest.mark.parametrize("reply", ["reject", "deny", "decline", "reject it"])
    def test_the_opposite_verb_is_detected(self, reply):
        assert leave_approval._asks_the_opposite_action(reply, APPROVE_CARD) is True

    @pytest.mark.parametrize("reply", ["approve", "yes", "approve it", "confirm"])
    def test_the_cards_own_action_is_not_the_opposite(self, reply):
        assert leave_approval._asks_the_opposite_action(reply, APPROVE_CARD) is False

    def test_polarity_flips_for_a_reject_card(self):
        reject_card = {**APPROVE_CARD, "action": "reject"}
        assert leave_approval._asks_the_opposite_action("approve", reject_card) is True
        assert leave_approval._asks_the_opposite_action("reject", reject_card) is False


# =============================================================================
# 2 - Naming another request re-aims the card
# =============================================================================

class TestNamingAnotherRequestReAims:

    async def test_a_different_id_moves_the_card(self, monkeypatch, erp, rows, action_store):
        arm(action_store)
        rows[:] = [ROW_400]
        extraction(monkeypatch)

        writer = FakeWriter()
        await leave_approval_node(state("400"), writer)

        assert len(writer.of_type("leave_approval_confirmation")) == 1
        assert action_store[("1", "conv-1")]["leave_request_id"] == 400

    async def test_a_different_person_moves_the_card(self, monkeypatch, erp, rows, action_store):
        arm(action_store)
        rows[:] = [ROW_400]
        extraction(monkeypatch)

        result = await leave_approval_node(state("abc testing"), FakeWriter())

        assert "ABC Testing" in result["response_text"]

    async def test_re_aiming_executes_nothing(self, monkeypatch, erp, rows, action_store):
        arm(action_store)
        rows[:] = [ROW_400]
        extraction(monkeypatch)

        await leave_approval_node(state("400"), FakeWriter())

        assert erp == []


# =============================================================================
# 3 - An explicit instruction escapes an open flow
# =============================================================================

def _classify_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}


class TestAnApprovalInstructionEscapesTheCancelFlow:

    @staticmethod
    def _patched(llm_says="cancel_leave"):
        none_pending = MagicMock(return_value=None)
        cancel_state = MagicMock(get_state=MagicMock(
            return_value={"step": "awaiting_selection", "candidates": []}))
        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=cancel_state,
            # A regularisation mid-flow left behind by another test
            # module otherwise claims these turns - slot_store is a
            # SEPARATE store from leave_slot_service.
            slot_store=MagicMock(get_slots=MagicMock(return_value=None)),
        ), patch.object(classify_node.leave_approval,
                        "resolve_pending_approval_intent", none_pending), \
            patch.object(classify_node.regularisation_approval,
                         "resolve_pending_regularisation_intent", none_pending), \
            patch.object(classify_node.individual_report,
                         "resolve_pending_selection_intent", none_pending)

    @pytest.mark.parametrize("query", [
        "approve leave", "approve a khan leave", "approve 310",
        "approve abc testing sick leave",
    ])
    async def test_it_is_answered_as_an_approval(self, query):
        outer, a, b, c = self._patched()
        with outer, a, b, c:
            result = await hr_graph.classify_node(_classify_state(query), FakeWriter())

        assert result["intent"] == "manager_leave_approval"

    @pytest.mark.parametrize("query", ["yes", "the second one", "cancel it", "no"])
    async def test_answers_to_the_cancellation_still_belong_to_it(self, query):
        """The counterweight: the open flow keeps its own replies."""
        outer, a, b, c = self._patched()
        with outer, a, b, c:
            result = await hr_graph.classify_node(_classify_state(query), FakeWriter())

        assert result["intent"] != "manager_leave_approval"

    async def test_a_non_manager_cannot_escape_this_way(self):
        outer, a, b, c = self._patched()
        with outer, a, b, c:
            result = await hr_graph.classify_node(
                _classify_state("approve leave", is_manager=False), FakeWriter())

        assert result["intent"] != "manager_leave_approval"

    async def test_the_escape_costs_no_llm_call(self):
        """Deterministic, so a rate-limited classifier cannot strand the
        manager inside the cancellation."""
        none_pending = MagicMock(return_value=None)
        clf = AsyncMock(return_value=("cancel_leave", None, False))
        cancel_state = MagicMock(get_state=MagicMock(
            return_value={"step": "awaiting_selection", "candidates": []}))
        with patch.multiple(
            classify_node, classify_intent_structured=clf,
            _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=cancel_state,
            # A regularisation mid-flow left behind by another test
            # module otherwise claims these turns - slot_store is a
            # SEPARATE store from leave_slot_service.
            slot_store=MagicMock(get_slots=MagicMock(return_value=None)),
        ), patch.object(classify_node.leave_approval,
                        "resolve_pending_approval_intent", none_pending), \
            patch.object(classify_node.regularisation_approval,
                         "resolve_pending_regularisation_intent", none_pending), \
            patch.object(classify_node.individual_report,
                         "resolve_pending_selection_intent", none_pending):
            await hr_graph.classify_node(_classify_state("approve leave"), FakeWriter())

        assert not clf.called
