"""Team leave requests by STATUS — GET /api/v1/ai/team/leaves?type=...

Covers the three layers the status filter passes through:

  1. services/team_leave_filter.py   wording  -> one of four filters
  2. services/erp_client.py          filter   -> the `type` query parameter
  3. hr_graph.team_leave_query_node  filter   -> the card, copy and counts

The endpoint accepts type=all|pending|approved|cancelled. Before this, the
node hardcoded pending, so "show my team's approved leaves" fetched the
pending queue and rendered it under a "pending" heading — the wrong rows
under the wrong label. Every class below is one way that can regress.

The FR-07.1 acceptance suite (test_team_pending_leave_acceptance.py) still
owns the pending case end to end; TestPendingRemainsUnchanged here only
guards the specific strings and shapes this change could have moved.
"""

import pytest
from unittest.mock import MagicMock

import services.hr_graph as hr_graph
import services.erp_client as erp_client
import services.nlp_service as nlp_service
import services.team_leave_filter as tlf
from services.team_leave_filter import (
    ALL, APPROVED, CANCELLED, PENDING, resolve_team_leave_status,
)


# ═════════════════════════════════════════════════════════════════════════════
# Harness
# ═════════════════════════════════════════════════════════════════════════════

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]


def base_state(query: str) -> dict:
    return {
        "query": query, "intent": "HRMS_TEAM_LEAVE_QUERY", "usage_events": [],
        "bearer_token": "caller-token", "company_id": 26, "conversation_id": "conv-1",
        "has_date_expression": False,
    }


def manager_context():
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": True}}}
    return _f


def not_manager_context():
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": False}}}
    return _f


def leave_row(name, leave_type, from_date, to_date, days, status_name="pending",
              employee_number="geo3", designation="IT"):
    """One row in the shape the endpoint documents."""
    return {
        "id": abs(hash((name, from_date, status_name))) % 10000,
        "employee_id": abs(hash(name)) % 5000,
        "employee_number": employee_number,
        "employee_name": name,
        "employee_designation": designation,
        "leave_type": leave_type,
        "leave_type_slug": leave_type.lower().replace(" ", "_"),
        "session_type": "Full Day",
        "session_type_slug": "full_day",
        "from_date": from_date, "to_date": to_date,
        "leave_count": str(days),
        "status": "1", "status_name": status_name,
        "reason": f"reason for {name}",
        "applied_date": "2026-08-24",
    }


def team_leaves(leaves, *, filter_type="pending", access_scope="direct_reports",
                total_pending=None, capture=None):
    """A stand-in for erp_client.get_team_leaves that records how it was called
    and echoes the documented envelope back."""
    async def _f(token, **kwargs):
        if capture is not None:
            capture.update(kwargs)
        data = {
            "access_scope": access_scope,
            "type": kwargs.get("leave_status", filter_type),
            "total_leaves": len(leaves),
            "total_pending_leaves": (
                total_pending if total_pending is not None
                else sum(1 for lv in leaves if lv.get("status_name") == "pending")
            ),
            "leaves": list(leaves),
        }
        return {"http_status": 200, "body": {"success": True, "data": data,
                                             "message": "success"}}
    return _f


APPROVED_ROWS = [
    leave_row("B Geo", "Casual Leave", "2026-08-26", "2026-08-26", 1, "approved"),
    leave_row("Ananya Rao", "Sick Leave", "2026-08-12", "2026-08-13", 2, "approved"),
]
CANCELLED_ROWS = [
    leave_row("Rohan Mehta", "Earned Leave", "2026-07-02", "2026-07-04", 3, "cancelled"),
]
PENDING_ROWS = [
    leave_row("Priya Nair", "Earned Leave", "2026-09-12", "2026-09-14", 3, "pending"),
    leave_row("Vikram Shah", "Casual Leave", "2026-09-18", "2026-09-18", 1, "pending"),
]
MIXED_ROWS = APPROVED_ROWS + CANCELLED_ROWS + PENDING_ROWS


# ═════════════════════════════════════════════════════════════════════════════
# 1 — Wording resolves to a filter
# ═════════════════════════════════════════════════════════════════════════════

class TestResolveStatusFromWording:

    @pytest.mark.parametrize("query", [
        "Show pending leave requests for my team.",
        "my team's pending leave",
        "what leave requests are pending for my reports",
        "outstanding leave requests for my team",
        "team leaves awaiting a decision",
    ])
    def test_pending_wording(self, query):
        assert resolve_team_leave_status(query) == PENDING

    @pytest.mark.parametrize("query", [
        "show approved leaves for my team",
        "my team's approved leave requests",
        "which leaves have been granted to my reports",
        "accepted leave requests for my team",
        "sanctioned leaves for my reportees",
    ])
    def test_approved_wording(self, query):
        assert resolve_team_leave_status(query) == APPROVED

    @pytest.mark.parametrize("query", [
        "show cancelled leaves for my team",
        "my team's canceled leave requests",
        "which team leaves were withdrawn",
        "revoked leave requests for my reports",
        "leave cancellations in my team",
    ])
    def test_cancelled_wording(self, query):
        assert resolve_team_leave_status(query) == CANCELLED

    @pytest.mark.parametrize("query", [
        "show all leave requests for my team",
        "every leave request for my reports",
        "my team's complete leave list",
        "team leave history",
        "show me leaves for my team regardless of status",
    ])
    def test_all_wording(self, query):
        assert resolve_team_leave_status(query) == ALL

    @pytest.mark.parametrize("query", [
        "leave requests for my team",
        "my team's leave",
        "show me team leave",
        "team leave approvals",
    ])
    def test_unqualified_query_defaults_to_pending(self, query):
        """FR-07.1's original reading: an unqualified team-leave question is
        the queue the manager has to act on, not their whole leave archive."""
        assert resolve_team_leave_status(query) == PENDING

    @pytest.mark.parametrize("query", [
        "leave requests pending approval for my team",
        "team leaves awaiting my approval",
        "which team leaves need my approval",
        "leaves yet to be approved in my team",
        "team leave requests not yet approved",
        "unapproved leaves for my team",
        "team leaves waiting for approval",
        "leave requests for my team to approve",
        "team leaves that need my sign-off",
        "approval pending leaves for my team",
    ])
    def test_approval_words_meaning_pending_are_not_read_as_approved(self, query):
        """The one real ambiguity in the vocabulary: every phrase here
        contains an approval word but asks for the PENDING queue. A plain
        substring scan reads them all as `approved` and answers a question
        about outstanding work with a list of settled requests."""
        assert resolve_team_leave_status(query) == PENDING

    def test_all_alongside_a_status_is_a_quantifier_not_a_filter(self):
        assert resolve_team_leave_status("show all pending leaves for my team") == PENDING
        assert resolve_team_leave_status("all approved leaves for my team") == APPROVED
        assert resolve_team_leave_status("every cancelled leave in my team") == CANCELLED

    def test_two_statuses_named_widen_to_all(self):
        """The endpoint has no multi-status filter, and `all` is the only
        response that contains everything the manager named."""
        assert resolve_team_leave_status(
            "show approved and cancelled leaves for my team") == ALL

    @pytest.mark.parametrize("query", ["", "   ", None])
    def test_empty_input_is_the_default_not_a_crash(self, query):
        assert resolve_team_leave_status(query) == PENDING

    def test_case_and_curly_apostrophes_normalize(self):
        assert resolve_team_leave_status("SHOW APPROVED LEAVES FOR MY TEAM") == APPROVED
        assert resolve_team_leave_status("my team’s cancelled leave") == CANCELLED

    @pytest.mark.parametrize("query", [
        "approved", "cancelled", "pending", "all", "random words entirely",
        "approved cancelled pending all", "", "leave",
    ])
    def test_return_value_is_always_a_valid_filter(self, query):
        """The resolver's output goes straight into the querystring, so it may
        never produce a value erp_client would reject."""
        assert resolve_team_leave_status(query) in tlf.VALID_STATUSES
        assert resolve_team_leave_status(query) in erp_client.TEAM_LEAVE_STATUS_FILTERS


# ═════════════════════════════════════════════════════════════════════════════
# 2 — The filter reaches erp-api as a query parameter
# ═════════════════════════════════════════════════════════════════════════════

class TestErpClientSendsTheFilter:

    @pytest.fixture
    def captured(self, monkeypatch):
        seen = {}

        async def _fake_request(method, path, bearer_token, **kwargs):
            seen.update({"method": method, "path": path, **kwargs})
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}

        monkeypatch.setattr(erp_client, "_request", _fake_request)
        return seen

    @pytest.mark.parametrize("status", ["all", "pending", "approved", "cancelled"])
    async def test_each_status_becomes_the_type_parameter(self, captured, status):
        await erp_client.get_team_leaves("tok", leave_status=status)
        assert captured["params"]["type"] == status

    async def test_path_stays_fixed_so_erp_logs_group_by_endpoint(self, captured):
        """The filter is a real querystring parameter, not baked into the path
        — otherwise erp_api_call_logs fragments one endpoint into four."""
        await erp_client.get_team_leaves("tok", leave_status="approved")
        assert captured["path"] == "/api/v1/ai/team/leaves"
        assert "?" not in captured["path"]
        assert captured["method"] == "GET"

    async def test_default_is_pending(self, captured):
        await erp_client.get_team_leaves("tok")
        assert captured["params"]["type"] == "pending"

    async def test_pending_wrapper_delegates_with_pending(self, captured):
        await erp_client.get_team_pending_leaves("tok")
        assert captured["params"]["type"] == "pending"
        assert captured["path"] == "/api/v1/ai/team/leaves"

    async def test_employee_id_narrowing_still_rides_alongside_the_filter(self, captured):
        await erp_client.get_team_leaves("tok", leave_status="approved", employee_id=3735)
        assert captured["params"] == {"type": "approved", "employee_id": 3735}

    async def test_employee_name_narrowing_still_rides_alongside_the_filter(self, captured):
        await erp_client.get_team_leaves("tok", leave_status="all", employee_name="B Geo")
        assert captured["params"] == {"type": "all", "employee_name": "B Geo"}

    async def test_employee_id_wins_over_name_as_before(self, captured):
        await erp_client.get_team_leaves("tok", employee_id=7, employee_name="B Geo")
        assert "employee_name" not in captured["params"]
        assert captured["params"]["employee_id"] == 7

    @pytest.mark.parametrize("bad", ["rejected", "PENDING", "", "any", None])
    async def test_unknown_filter_raises_rather_than_querying_something_else(self, captured, bad):
        with pytest.raises(ValueError):
            await erp_client.get_team_leaves("tok", leave_status=bad)
        assert captured == {}, "no request may be made for an invalid filter"

    def test_client_and_resolver_agree_on_the_vocabulary(self):
        assert set(tlf.VALID_STATUSES) == set(erp_client.TEAM_LEAVE_STATUS_FILTERS)


# ═════════════════════════════════════════════════════════════════════════════
# 3 — The node fetches, labels and renders the right status
# ═════════════════════════════════════════════════════════════════════════════

class TestNodeFetchesTheRequestedStatus:

    @pytest.mark.parametrize("query,expected", [
        ("Show pending leave requests for my team.", "pending"),
        ("show approved leaves for my team", "approved"),
        ("show cancelled leaves for my team", "cancelled"),
        ("show all leave requests for my team", "all"),
    ])
    async def test_resolved_status_is_passed_to_erp(self, monkeypatch, query, expected):
        capture = {}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves",
                            team_leaves(MIXED_ROWS, capture=capture))

        await hr_graph.team_leave_query_node(base_state(query), FakeWriter())
        assert capture["leave_status"] == expected

    async def test_card_states_which_filter_produced_it(self, monkeypatch):
        """The renderer must never label approved rows as pending — the card
        carries the resolved filter rather than leaving it to be inferred."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(APPROVED_ROWS))

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            base_state("show approved leaves for my team"), writer)

        card = writer.of_type("team_pending_leave")[0]["data"]
        assert card["leave_status_filter"] == "approved"

    async def test_card_passes_through_the_endpoint_totals(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves",
                            team_leaves(MIXED_ROWS, total_pending=2))

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            base_state("show all leave requests for my team"), writer)

        card = writer.of_type("team_pending_leave")[0]["data"]
        assert card["total_leaves"] == len(MIXED_ROWS)
        assert card["total_pending_leaves"] == 2
        assert card["access_scope"] == "direct_reports"

    @pytest.mark.parametrize("query,word", [
        ("show approved leaves for my team", "approved"),
        ("show cancelled leaves for my team", "cancelled"),
        ("Show pending leave requests for my team.", "pending"),
    ])
    async def test_summary_names_the_status_it_fetched(self, monkeypatch, query, word):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(APPROVED_ROWS))

        result = await hr_graph.team_leave_query_node(base_state(query), FakeWriter())
        assert f"top {word} leave requests" in result["response_text"]

    async def test_all_filter_summary_carries_no_status_adjective(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(MIXED_ROWS))

        result = await hr_graph.team_leave_query_node(
            base_state("show all leave requests for my team"), FakeWriter())

        assert "Here are the top leave requests for your team:" in result["response_text"]
        for word in ("top pending", "top approved", "top cancelled"):
            assert word not in result["response_text"]

    async def test_rows_are_rendered_from_the_response_not_invented(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(APPROVED_ROWS))

        result = await hr_graph.team_leave_query_node(
            base_state("show approved leaves for my team"), FakeWriter())

        assert "B Geo" in result["response_text"]
        assert "Casual Leave" in result["response_text"]
        assert "2026-08-26" in result["response_text"]

    async def test_top_three_cap_and_more_note_apply_to_every_filter(self, monkeypatch):
        many = [leave_row(f"Emp {i}", "Casual Leave", f"2026-09-{i:02d}",
                          f"2026-09-{i:02d}", 1, "approved") for i in range(1, 6)]
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(many))

        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(
            base_state("show approved leaves for my team"), writer)

        card = writer.of_type("team_pending_leave")[0]["data"]
        assert card["has_more"] is True
        assert len(card["leaves"]) == 5, "the card keeps the full list for View More"
        assert result["response_text"].count("Casual Leave") == 3
        assert "(more approved requests are available)" in result["response_text"]

    async def test_ordering_is_by_start_date_for_every_filter(self, monkeypatch):
        out_of_order = [
            leave_row("Third", "Casual Leave", "2026-08-30", "2026-08-30", 1, "approved"),
            leave_row("First", "Casual Leave", "2026-08-01", "2026-08-01", 1, "approved"),
            leave_row("Second", "Casual Leave", "2026-08-15", "2026-08-15", 1, "approved"),
        ]
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(out_of_order))

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            base_state("show approved leaves for my team"), writer)

        names = [lv["employee_name"] for lv in writer.of_type("team_pending_leave")[0]["data"]["leaves"]]
        assert names == ["First", "Second", "Third"]

    async def test_fetching_event_names_the_status(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(CANCELLED_ROWS))

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            base_state("show cancelled leaves for my team"), writer)

        assert writer.of_type("fetching_team_leaves")[0]["message"] == \
            "Checking your team's cancelled leave requests..."


# ═════════════════════════════════════════════════════════════════════════════
# 4 — Empty states, one per filter
# ═════════════════════════════════════════════════════════════════════════════

class TestEmptyStates:

    async def _run_empty(self, monkeypatch, query):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves([]))
        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(base_state(query), writer)
        return writer, result

    async def test_pending_empty_state_is_verbatim_ac6_copy(self, monkeypatch):
        """AC#6's required wording. Parameterising the copy must not have
        moved this one character."""
        _, result = await self._run_empty(monkeypatch, "Show pending leave requests for my team.")
        assert result["response_text"] == (
            "Great news! There are currently no pending leave requests for your team.")

    @pytest.mark.parametrize("query,expected", [
        ("show approved leaves for my team",
         "There are no approved leave requests for your team."),
        ("show cancelled leaves for my team",
         "There are no cancelled leave requests for your team."),
        ("show all leave requests for my team",
         "There are no leave requests on record for your team."),
    ])
    async def test_other_filters_get_their_own_empty_state(self, monkeypatch, query, expected):
        _, result = await self._run_empty(monkeypatch, query)
        assert result["response_text"] == expected

    async def test_no_card_event_is_emitted_when_empty(self, monkeypatch):
        writer, _ = await self._run_empty(monkeypatch, "show approved leaves for my team")
        assert writer.of_type("team_pending_leave") == []

    async def test_empty_state_never_claims_the_wrong_status(self, monkeypatch):
        _, result = await self._run_empty(monkeypatch, "show cancelled leaves for my team")
        assert "pending" not in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# 5 — Permission and failure paths hold for every filter
# ═════════════════════════════════════════════════════════════════════════════

class TestAccessAndFailures:

    @pytest.mark.parametrize("query,word", [
        ("show approved leaves for my team", "approved"),
        ("show cancelled leaves for my team", "cancelled"),
        ("Show pending leave requests for my team.", "pending"),
    ])
    async def test_non_manager_is_refused_before_any_fetch(self, monkeypatch, query, word):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        never = MagicMock(side_effect=AssertionError(
            "team leaves must never be fetched for a non-manager"))
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", never)

        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(base_state(query), writer)

        never.assert_not_called()
        assert writer.of_type("done")[0]["intent"] == "team_attendance_restricted"
        assert "available to managers with direct or indirect reports" in result["response_text"]
        assert word in result["response_text"], "the refusal names what was asked for"

    async def test_refusal_leaks_no_employee_data(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(MIXED_ROWS))

        result = await hr_graph.team_leave_query_node(
            base_state("show all leave requests for my team"), FakeWriter())

        for row in MIXED_ROWS:
            assert row["employee_name"] not in result["response_text"]

    async def test_erp_side_403_refuses_rather_than_erroring(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _forbidden(token, **kwargs):
            return {"http_status": 403, "body": {"success": False, "message": "Forbidden"}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", _forbidden)

        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(
            base_state("show approved leaves for my team"), writer)

        assert writer.of_type("done")[0]["intent"] == "team_attendance_restricted"
        assert writer.of_type("error") == []
        assert "available to managers with direct or indirect reports" in result["response_text"]

    @pytest.mark.parametrize("exc,fragment", [
        ("ErpApiTimeout", "couldn't reach the HR system in time"),
        ("ErpApiUnavailable", "unable to reach the HR system right now"),
    ])
    async def test_transport_failures_degrade_politely(self, monkeypatch, exc, fragment):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _boom(token, **kwargs):
            raise getattr(erp_client, exc)("down")
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", _boom)

        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(
            base_state("show approved leaves for my team"), writer)

        assert fragment in result["response_text"]
        assert writer.of_type("error") == []

    async def test_no_scope_widening_parameters_are_sent(self, monkeypatch):
        """The request is exactly "my team", as scoped by the caller's token —
        adding a status filter must not have added a way to reach further."""
        capture = {}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves",
                            team_leaves(MIXED_ROWS, capture=capture))

        await hr_graph.team_leave_query_node(
            base_state("show all leave requests for my team"), FakeWriter())

        assert capture.get("employee_id") is None
        assert capture.get("employee_name") is None
        assert set(capture) <= {"company_id", "conversation_id", "leave_status"}


class TestJwtRoleIsTrustedOverAFreshErpCall:
    """Live bug: an "hr"-role JWT resolves state["is_manager"]=True via
    hr_graph.manager_gate_node's fast path (dependencies.is_manager_role),
    but this node used to ignore that and make its OWN fresh get_leave_context
    call regardless — and for one real account, erp-api's own is_manager flag
    disagreed (False), so "show my team leave request" was refused as
    'team_leave_restricted' even though the caller's role said otherwise.
    The gate now trusts the already-resolved state["is_manager"] first, the
    same convention individual_report.py/leave_approval.py already use, and
    only falls back to erp-api when state["is_manager"] was never resolved."""

    async def test_confirmed_manager_state_skips_the_erp_recheck(self, monkeypatch):
        never = MagicMock(side_effect=AssertionError(
            "is_manager already resolved on state - must not re-ask erp-api"))
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", never)
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(MIXED_ROWS))

        state = base_state("show all leave requests for my team")
        state["is_manager"] = True
        result = await hr_graph.team_leave_query_node(state, FakeWriter())

        never.assert_not_called()
        assert "available to managers with direct or indirect reports" not in result["response_text"]

    async def test_state_true_overrides_an_erp_false(self, monkeypatch):
        """The exact live disagreement: state says manager, a fresh erp-api
        call would have said otherwise. state wins, and erp-api is never
        even asked."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(MIXED_ROWS))

        state = base_state("show my team leave request")
        state["is_manager"] = True
        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(state, writer)

        assert writer.of_type("done")[0]["intent"] != "team_attendance_restricted"
        assert "available to managers with direct or indirect reports" not in result["response_text"]

    async def test_manager_status_unknown_asks_to_retry_not_denied(self, monkeypatch):
        import services.individual_report as individual_report
        never = MagicMock(side_effect=AssertionError("must not re-ask erp-api"))
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", never)

        state = base_state("show my team leave request")
        state["is_manager"] = individual_report.MANAGER_UNKNOWN
        result = await hr_graph.team_leave_query_node(state, FakeWriter())

        never.assert_not_called()
        assert "try again" in result["response_text"]
        assert "available to managers with direct or indirect reports" not in result["response_text"]

    async def test_unresolved_state_still_falls_back_to_erp_api(self, monkeypatch):
        """state["is_manager"] absent and no JWT fast path - the node stays
        callable on its own (tests, or any future caller reaching it without
        the gate node), so erp-api is still consulted rather than silently
        granting access."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        state = base_state("show my team leave request")
        result = await hr_graph.team_leave_query_node(state, FakeWriter())

        assert result["response_text"] != ""
        assert "available to managers with direct or indirect reports" in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# 6 — The pending path is byte-for-byte what it was
# ═════════════════════════════════════════════════════════════════════════════

class TestPendingRemainsUnchanged:

    async def test_pending_summary_wording_is_unchanged(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(PENDING_ROWS))

        result = await hr_graph.team_leave_query_node(
            base_state("Show pending leave requests for my team."), FakeWriter())

        assert result["response_text"].startswith(
            "Here are the top pending leave requests for your team:")

    async def test_pending_more_note_is_unchanged(self, monkeypatch):
        many = [leave_row(f"Emp {i}", "Casual Leave", f"2026-09-{i:02d}",
                          f"2026-09-{i:02d}", 1) for i in range(1, 6)]
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(many))

        result = await hr_graph.team_leave_query_node(
            base_state("Show pending leave requests for my team."), FakeWriter())

        assert "(more pending requests are available)" in result["response_text"]

    async def test_pending_restricted_copy_matches_the_figma(self, monkeypatch):
        """HA-193 — the refusal is the Figma's two-sentence copy, byte for
        byte. It is the one string in this module that a designer signed
        off on, so it is pinned exactly rather than by fragment."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(
            base_state("Show pending leave requests for my team."), writer)

        assert result["response_text"] == (
            "Team leave summaries are available to managers with direct or "
            "indirect reports. You can still check your own pending leave "
            "requests.")
        # No apology, and no dead end: the old copy had both.
        assert "sorry" not in result["response_text"].lower()
        assert "pull up for your role" not in result["response_text"]

        # The card the copy renders inside.
        notice = writer.of_type("access_notice")[0]["data"]
        assert notice["title"] == "Not available"
        assert notice["message"] == result["response_text"]
        assert notice["capability"] == "team_leave"
        assert notice["reason"] == "not_a_manager"
        # Persisted too - only done.data survives into history replay.
        assert writer.of_type("done")[0]["data"]["access_notice"] == notice

    async def test_card_event_type_is_unchanged(self, monkeypatch):
        """The renderer subscribes to `team_pending_leave`; renaming it for
        the wider feature would silently drop every card (main._ai_stream
        relays only known event types)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(APPROVED_ROWS))

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            base_state("show approved leaves for my team"), writer)

        assert len(writer.of_type("team_pending_leave")) == 1

    async def test_done_intent_is_unchanged_for_every_filter(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", team_leaves(MIXED_ROWS))

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            base_state("show all leave requests for my team"), writer)

        assert writer.of_type("done")[0]["intent"] == "HRMS_TEAM_LEAVE_QUERY"


# ═════════════════════════════════════════════════════════════════════════════
# 7 — Routing: the non-pending phrasings reach this node at all
# ═════════════════════════════════════════════════════════════════════════════

class TestRouting:

    @pytest.mark.parametrize("query", [
        "Show pending leave requests for my team.",
        "approved leaves for my team",
        "cancelled leaves for my team",
        "all leave requests for my team",
        "my team's leave history",
    ])
    def test_fast_classify_labels_them_team_leave(self, query):
        intent, is_hr, confidence = nlp_service.fast_classify(query)
        assert intent == "HRMS_TEAM_LEAVE_QUERY"
        assert is_hr is True
        assert confidence >= 0.5

    def test_label_routes_to_the_team_leave_node(self):
        assert hr_graph._route_after_classify(
            {"intent": "HRMS_TEAM_LEAVE_QUERY", "is_hr": True}) == "team_leave_query_node"

    def test_status_wording_does_not_steal_the_caller_s_own_leave_query(self):
        """"my approved leaves" is the CALLER's own record — leave_status, not
        the team label. The new keywords must not have widened that far."""
        intent, _, _ = nlp_service.fast_classify("show my approved leaves")
        assert intent != "HRMS_TEAM_LEAVE_QUERY"

    def test_intent_prompt_tells_the_model_any_status_qualifies(self):
        """The LLM classifier is what catches paraphrase; its description has
        to say the label is not pending-only or it will send "approved leaves
        for my team" somewhere else."""
        import services.classify_node as classify_node
        built = classify_node._build_intent_prompt("approved leaves for my team", [], False)
        # The builder returns role-tagged messages; flatten to the text the
        # model actually sees.
        text = built if isinstance(built, str) else "\n".join(
            m.get("content", "") if isinstance(m, dict) else str(m) for m in built)

        block = text[text.index("HRMS_TEAM_LEAVE_QUERY"):]
        block = block[:block.index("manager_leave_request_lookup")]
        # The description is hard-wrapped, so assert on fragments that sit
        # inside one line rather than on phrases that straddle a wrap.
        assert "not only pending" in block, "the description must not read as pending-only"
        for status in ("approved leaves", "cancelled leave requests"):
            assert status in block
