"""QA's scripted manager-approval walkthrough, run as tests.

The script QA/Product signed off on, step for step:

  TC1  "Show me my team's pending leave requests."   -> the pending list
  TC2  "Approve John Doe's leave request."           -> details + confirmation
  TC3  "Yes, approve it."                            -> approved

  Alt  "Do I have any leave requests waiting for my approval?"
       "Approve the leave request for Ahmed Khan."
       "Yes."

  Neg  "Approve Rahul's leave request."              -> nothing to approve

Each flow is driven as a REAL multi-turn conversation - one store carries
state from one turn to the next, and nothing is re-armed by hand in between.
A test that armed the confirmation card itself would still pass if the turn
that is supposed to arm it stopped working, which is precisely the
regression this file exists to catch.

Assertions are on BEHAVIOUR, not on copy: which employee, which request id,
whether erp-api's approve endpoint was called at all, and whether it was
called before the manager confirmed. Wording differs from the script's
illustrative examples in places the feature owners chose deliberately - see
TestNegativeCase for the one that matters.
"""

import pytest

import services.erp_client as erp_client
import services.hr_graph as hr_graph
import services.leave_approval as leave_approval
import services.audit_log_service as audit_log_service
from services.leave_approval import leave_approval_node

from tests.test_leave_approval import FakeWriter, base_state


# -- The team QA's script describes -----------------------------------------

JOHN = {
    "id": 101, "employee_id": 5001, "employee_number": "EMP-101",
    "employee_name": "John Doe", "leave_type": "Annual Leave",
    "session_type": "Full Day", "from_date": "2026-09-10", "to_date": "2026-09-12",
    "leave_count": "3", "status": 0, "status_name": "pending",
    "reason": "Family trip", "applied_date": "2026-09-01",
}
AHMED = {
    "id": 102, "employee_id": 5002, "employee_number": "EMP-102",
    "employee_name": "Ahmed Khan", "leave_type": "Sick Leave",
    "session_type": "Full Day", "from_date": "2026-09-11", "to_date": "2026-09-11",
    "leave_count": "1", "status": 0, "status_name": "pending",
    "reason": "Fever", "applied_date": "2026-09-10",
}
SARAH = {
    "id": 103, "employee_id": 5003, "employee_number": "EMP-103",
    "employee_name": "Sarah Ali", "leave_type": "Casual Leave",
    "session_type": "Full Day", "from_date": "2026-09-15", "to_date": "2026-09-16",
    "leave_count": "2", "status": 0, "status_name": "pending",
    "reason": "Personal", "applied_date": "2026-09-05",
}
TEAM = [JOHN, AHMED, SARAH]

ROSTER = [
    {"employee_id": lv["employee_id"], "employee_name": lv["employee_name"],
     "employee_number": lv["employee_number"], "employee_designation": "Engineering"}
    for lv in TEAM
]


def approved_body(leave):
    return {
        "success": True,
        "message": "Leave request approved successfully.",
        "data": {**leave, "leave_request_id": leave["id"], "status": 1,
                 "status_name": "approved",
                 "approved_by": {"id": 704, "employee_number": "mgr1", "name": "The Manager"}},
    }


# -- Fixtures ---------------------------------------------------------------

@pytest.fixture(autouse=True)
def _stores(monkeypatch):
    """In-memory stand-ins for the Redis-backed conversation state, shared
    across the turns of a flow - this is what makes these multi-turn rather
    than three unrelated node calls."""
    actions, reports = {}, {}
    svc = leave_approval.leave_slot_service

    monkeypatch.setattr(svc, "get_manager_action",
                        lambda c, k: actions.get((str(c), k)))
    monkeypatch.setattr(svc, "set_manager_action",
                        lambda c, k, v: (actions.__setitem__((str(c), k), v), True)[1])
    monkeypatch.setattr(svc, "clear_manager_action",
                        lambda c, k: (actions.pop((str(c), k), None), True)[1])
    monkeypatch.setattr(svc, "get_report_state",
                        lambda c, k: reports.get((str(c), k)))
    monkeypatch.setattr(svc, "set_report_state",
                        lambda c, k, v: (reports.__setitem__((str(c), k), v), True)[1])
    return actions


@pytest.fixture(autouse=True)
def _no_audit_db(monkeypatch):
    rows = []
    monkeypatch.setattr(audit_log_service, "_write", lambda **f: rows.append(f))
    return rows


@pytest.fixture
def approve_calls(monkeypatch):
    """erp-api stubbed at the client boundary, recording every approve call.

    Pending lookups answer by the same rules erp-api uses: a name search that
    matches nobody comes back search_matched=false with the WHOLE roster
    attached - the shape that made "geo3" look out-of-team until
    _resolve_from_roster was added.
    """
    calls = []

    async def _pending(token, company_id=None, conversation_id=None,
                       employee_id=None, employee_name=None, leave_status=None):
        if employee_id is not None:
            rows = [lv for lv in TEAM if lv["employee_id"] == employee_id]
            return {"http_status": 200,
                    "body": {"success": True, "data": {"leaves": rows}}}
        if employee_name:
            hits = [e for e in ROSTER
                    if employee_name.strip().lower() in e["employee_name"].lower()]
            return {"http_status": 200, "body": {"success": True, "data": {
                "action_required": "select_employee",
                "search_matched": bool(hits),
                "employees": hits or ROSTER,
            }}}
        return {"http_status": 200,
                "body": {"success": True, "data": {"leaves": list(TEAM),
                                                   "access_scope": "direct_reports"}}}

    async def _approve(token, leave_request_id, company_id=None, conversation_id=None):
        calls.append(leave_request_id)
        leave = next(lv for lv in TEAM if lv["id"] == leave_request_id)
        return {"http_status": 200, "body": approved_body(leave)}

    async def _context(token, company_id=None, conversation_id=None, **kw):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": True}}}

    for mod in (leave_approval.erp_client, hr_graph.erp_client, erp_client):
        monkeypatch.setattr(mod, "get_team_pending_leaves", _pending)
        # team_leave_query_node reaches erp-api through the status-filtered
        # call; _pending ignores the extra leave_status kwarg and answers the
        # same way, so both entry points stay stubbed at the client boundary.
        monkeypatch.setattr(mod, "get_team_leaves", _pending)
        monkeypatch.setattr(mod, "approve_leave_request", _approve)
        monkeypatch.setattr(mod, "get_leave_context", _context)
    return calls


def extraction(monkeypatch, **fields):
    """Stands in for the LLM field extractor. QA's flows exercise it only for
    "which employee did they name", so it is stubbed to keep these tests on
    the approval mechanics rather than the model's phrasing sensitivity."""
    base = {"action": "approve", "leave_request_id": None, "employee_id": None,
            "employee_name": None, "uses_pronoun": False, "targets_multiple": False}

    async def _extract(query, today):
        return {**base, **fields}, None

    monkeypatch.setattr(leave_approval.ai_service, "extract_leave_approval_fields", _extract)


async def turn(query, conversation_id="qa-1"):
    writer = FakeWriter()
    state = {**base_state(query), "conversation_id": conversation_id}
    await leave_approval_node(state, writer)
    return writer


# -- The scripted flow ------------------------------------------------------

class TestScriptedApprovalFlow:
    @pytest.mark.asyncio
    async def test_tc1_the_team_list_is_shown(self, approve_calls):
        """TC1 - the manager asks to see the team's pending requests."""
        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            {"company_id": 7, "conversation_id": "qa-1", "bearer_token": "tok",
             "usage_events": []}, writer)

        answer = writer.answer()
        for name in ("John Doe", "Ahmed Khan", "Sarah Ali"):
            assert name in answer
        assert approve_calls == [], "listing requests must never approve one"

    @pytest.mark.asyncio
    async def test_tc2_then_tc3_approves_johns_request(self, approve_calls, monkeypatch):
        """TC2 names John, TC3 confirms - one continuous conversation."""
        extraction(monkeypatch, employee_name="John Doe")
        writer = await turn("Approve John Doe's leave request.")

        # TC2 - details shown, NOTHING executed yet (FR-08.3).
        card = writer.of_type("leave_approval_confirmation")[0]["data"]
        assert card["leave_request_id"] == 101
        assert card["employee_name"] == "John Doe"
        assert card["date_range"] == "2026-09-10 to 2026-09-12"
        assert approve_calls == [], "TC2 approved before the manager confirmed"

        # TC3 - "Yes, approve it."
        writer = await turn("Yes, approve it.")
        assert approve_calls == [101]
        assert "John Doe" in writer.answer()
        assert writer.of_type("leave_approval_success")

    @pytest.mark.asyncio
    async def test_the_alternative_flow_approves_ahmeds_request_on_a_bare_yes(
            self, approve_calls, monkeypatch):
        """Alt flow - the confirming turn is nothing but "Yes."."""
        extraction(monkeypatch, employee_name="Ahmed Khan")
        writer = await turn("Approve the leave request for Ahmed Khan.", "qa-2")
        assert writer.of_type("leave_approval_confirmation")[0]["data"]["leave_request_id"] == 102
        assert approve_calls == []

        writer = await turn("Yes.", "qa-2")
        assert approve_calls == [102]
        assert "Ahmed Khan" in writer.answer()

    @pytest.mark.asyncio
    async def test_declining_leaves_the_request_pending(self, approve_calls, monkeypatch):
        """Not in the script, but the other half of TC3: "no" must change
        nothing, and say so."""
        extraction(monkeypatch, employee_name="John Doe")
        await turn("Approve John Doe's leave request.", "qa-3")

        writer = await turn("No.", "qa-3")
        assert approve_calls == []
        assert "pending" in writer.answer().lower()


class TestNegativeCase:
    @pytest.mark.asyncio
    async def test_an_unknown_name_approves_nothing_and_leaks_nothing(
            self, approve_calls, monkeypatch):
        """Neg - "Approve Rahul's leave request."

        The script's expected copy names Rahul back ("no pending leave
        request for Rahul"). This service does not name him back, and that
        difference is deliberate: erp-api returns an identical response for a
        typo, for gibberish, and for a real employee on another manager's
        team, so naming the person back would turn this reply into a way to
        probe who reports to whom.

        The caller IS now shown their own team to pick from, which the same
        reasoning permits - that roster is identical in all three cases, so
        it distinguishes none of them, and it is the caller's own reports.
        What QA is actually checking here - nothing approved, nothing
        disclosed about Rahul - is asserted below and unchanged.
        """
        extraction(monkeypatch, employee_name="Rahul")
        writer = await turn("Approve Rahul's leave request.", "qa-4")

        answer = writer.answer()
        assert approve_calls == [], "nothing may be approved for an unknown name"
        assert "Rahul" not in answer, "the named person must not be confirmed or denied"
        assert "No employee matched that name" in answer

    @pytest.mark.asyncio
    async def test_a_team_member_with_nothing_pending_is_named(
            self, approve_calls, monkeypatch):
        """The other reading of the negative case: the person IS on the team
        and simply has nothing outstanding. Here the script's wording is what
        the service already says, because naming them back discloses nothing
        the manager cannot already see."""
        extraction(monkeypatch, employee_id=5001)

        async def _empty(token, company_id=None, conversation_id=None,
                         employee_id=None, employee_name=None):
            return {"http_status": 200, "body": {"success": True, "data": {
                "leaves": [], "employee": {"name": "John Doe", "emp_no": "EMP-101"}}}}

        monkeypatch.setattr(leave_approval.erp_client, "get_team_pending_leaves", _empty)

        writer = await turn("Approve John Doe's leave request.", "qa-5")
        assert approve_calls == []
        assert "no pending leave requests to approve" in writer.answer()
