"""HA-193 - the "Not available" permission card.

The Figma for the team-leave screen pairs two states:

  * a manager/HR caller whose team has nothing outstanding gets the plain
    empty-state line ("Great news! ..."), already covered verbatim by
    TestCase3 in test_team_pending_leave_acceptance.py;
  * a caller without reports gets an amber card titled "Not available",
    whose body says what the capability needs and what they can still do
    themselves - replacing the old apologetic "this isn't something I can
    pull up for your role" refusal.

Only the second is new, so that is what this module pins: the copy, the
structured payload the card renders from, and the fact that all three
manager-only team capabilities (leave, attendance, roster) emit it rather
than just the one the Figma happened to be drawn for.

The nodes are driven directly with a fake StreamWriter and a mocked
erp_client, the same pattern as test_team_attendance_summary.py.
"""

import pytest

import services.hr_graph as hr_graph
import services.access_notice as access_notice
import services.team_leave_filter as team_leave_filter


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, intent: str) -> dict:
    return {
        "query": query, "intent": intent, "usage_events": [],
        "bearer_token": "caller-token", "company_id": 1, "conversation_id": "conv-1",
        "has_date_expression": False, "is_manager": False,
    }


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


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


async def forbidden_response(token, **kwargs):
    return {"http_status": 403, "body": {"success": False, "message": "Forbidden"}}


def never_fetch(token, **kwargs):
    raise AssertionError("no team data may be fetched for a non-manager")


FIGMA_LEAVE_REFUSAL = (
    "Team leave summaries are available to managers with direct or "
    "indirect reports. You can still check your own pending leave requests."
)

FIGMA_EMPTY_STATE = (
    "Great news! There are currently no pending leave requests for your team."
)


# =============================================================================
# The copy itself
# =============================================================================

class TestFigmaCopy:

    def test_pending_refusal_is_the_figma_string_byte_for_byte(self):
        assert team_leave_filter.restricted_message(
            team_leave_filter.PENDING) == FIGMA_LEAVE_REFUSAL

    def test_the_card_title_is_the_figma_heading(self):
        assert access_notice.TITLE == "Not available"

    @pytest.mark.parametrize("status,word", [
        (team_leave_filter.PENDING, "pending"),
        (team_leave_filter.APPROVED, "approved"),
        (team_leave_filter.CANCELLED, "cancelled"),
    ])
    def test_the_offer_names_the_status_that_was_asked_about(self, status, word):
        """A caller who asked about approved leave is offered their own
        approved leave, not silently redirected to the pending queue."""
        msg = team_leave_filter.restricted_message(status)
        assert "your own {} leave requests".format(word) in msg

    def test_an_unqualified_ask_is_offered_leave_requests_with_no_adjective(self):
        msg = team_leave_filter.restricted_message(team_leave_filter.ALL)
        assert "your own leave requests" in msg
        assert "your own all leave requests" not in msg

    @pytest.mark.parametrize("status", team_leave_filter.VALID_STATUSES)
    def test_no_refusal_apologises_or_dead_ends(self, status):
        msg = team_leave_filter.restricted_message(status)
        assert "sorry" not in msg.lower()
        assert "pull up for your role" not in msg
        # Every refusal ends with something the caller can actually do.
        assert "You can still " in msg

    def test_leave_and_attendance_state_one_consistent_access_rule(self):
        """Both render in the same card; a caller who asks for both must not
        be told two different rules about who may see team data."""
        rule = "are available to managers with direct or indirect reports."
        assert rule in team_leave_filter.restricted_message(team_leave_filter.PENDING)
        assert rule in access_notice.message(
            "Team attendance summaries", "check your own attendance status")


# =============================================================================
# The payload
# =============================================================================

class TestNoticePayload:

    def test_build_carries_everything_the_card_needs(self):
        assert access_notice.build("team_leave", "some copy") == {
            "title": "Not available",
            "message": "some copy",
            "capability": "team_leave",
            "reason": "not_a_manager",
            "requires": "manager_with_reports",
        }

    def test_capability_lets_the_frontend_branch_without_parsing_prose(self):
        notice = team_leave_filter.restricted_notice(team_leave_filter.PENDING)
        assert notice["capability"] == "team_leave"
        assert notice["message"] == FIGMA_LEAVE_REFUSAL


# =============================================================================
# Every manager-only team capability emits it
# =============================================================================

# (node, `done` intent, capability name, state intent, query)
CAPABILITIES = [
    ("team_leave_query_node", "team_attendance_restricted", "team_leave",
     "HRMS_TEAM_LEAVE_QUERY", "Show pending leave requests for my team."),
    ("team_attendance_summary_node", "team_attendance_restricted", "team_attendance",
     "HRMS_TEAM_ATTENDANCE_QUERY", "Who was absent in my team today?"),
]

CAPABILITY_IDS = [row[2] for row in CAPABILITIES]


class TestEveryTeamCapabilityShowsTheCard:

    @pytest.mark.parametrize("node_name,intent,capability,state_intent,query",
                             CAPABILITIES, ids=CAPABILITY_IDS)
    async def test_non_manager_gets_the_notice_event_and_intent(
        self, monkeypatch, node_name, intent, capability, state_intent, query
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        writer = FakeWriter()

        result = await getattr(hr_graph, node_name)(
            base_state(query, state_intent), writer)

        events = writer.of_type("access_notice")
        assert len(events) == 1, "exactly one card per refusal"
        data = events[0]["data"]
        assert data["title"] == "Not available"
        assert data["capability"] == capability
        assert data["reason"] == "not_a_manager"
        # The card text and the chat text are the same sentence, never two
        # differently-worded explanations of the same refusal.
        assert data["message"] == result["response_text"]
        assert writer.of_type("done")[0]["intent"] == intent

    @pytest.mark.parametrize("node_name,intent,capability,state_intent,query",
                             CAPABILITIES, ids=CAPABILITY_IDS)
    async def test_the_notice_survives_into_the_done_payload(
        self, monkeypatch, node_name, intent, capability, state_intent, query
    ):
        """main._persist_and_build_done saves only `done`'s `data`, so a
        non-streaming client and a replayed conversation see the card only
        if it is in there too."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        writer = FakeWriter()

        await getattr(hr_graph, node_name)(base_state(query, state_intent), writer)

        done = writer.of_type("done")[0]["data"]
        assert done["access_notice"] == writer.of_type("access_notice")[0]["data"]
        assert done["answer"] == done["access_notice"]["message"]

    @pytest.mark.parametrize("node_name,intent,capability,state_intent,query",
                             CAPABILITIES, ids=CAPABILITY_IDS)
    async def test_refusing_still_fetches_no_team_data(
        self, monkeypatch, node_name, intent, capability, state_intent, query
    ):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", never_fetch)
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", never_fetch)

        writer = FakeWriter()
        await getattr(hr_graph, node_name)(base_state(query, state_intent), writer)

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

    async def test_team_roster_refusal_also_shows_the_card(self, monkeypatch):
        """team_members_node has no client-side role gate - erp-api's 403 is
        its authoritative one - so its refusal is reached by a different
        path and is asserted separately."""
        monkeypatch.setattr(hr_graph.erp_client, "get_team_members", forbidden_response)

        writer = FakeWriter()
        result = await hr_graph.team_members_node(
            base_state("show my team members", "HRMS_TEAM_MEMBERS_QUERY"), writer)

        data = writer.of_type("access_notice")[0]["data"]
        assert data["capability"] == "team_members"
        assert data["title"] == "Not available"
        assert writer.of_type("done")[0]["intent"] == "team_attendance_restricted"
        assert "You can still " in result["response_text"]

    async def test_an_erp_side_403_shows_the_card_too(self, monkeypatch):
        """A manager flag that disagrees with erp-api's own gate lands on the
        same card, not a raw error and not a bare sentence."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context)
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", forbidden_response)

        state = base_state("Show pending leave requests for my team.",
                           "HRMS_TEAM_LEAVE_QUERY")
        state["is_manager"] = True
        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(state, writer)

        assert len(writer.of_type("access_notice")) == 1
        assert writer.of_type("error") == []
        assert result["response_text"] == FIGMA_LEAVE_REFUSAL


# =============================================================================
# The card has to actually REACH the caller
# =============================================================================

class TestTheGuardDoesNotPreemptTheCard:
    """The card was implemented, tested and still not reaching QA: the
    pre-classify ownership guard hard-blocked "show my team pending leaves"
    as a "group" query and ended the turn with

        intent "blocked", "Sorry, I can only share attendance details ..."

    so team_leave_query_node never ran. A per-node refusal is only as good as
    the routing that reaches it, which is what this pins.
    """

    async def test_the_guard_lets_an_own_team_question_through(self, monkeypatch):
        import services.ownership_guard as ownership_guard

        async def _would_say_group(prompt, labels, fallback_label="unknown"):
            return "group", {"total_tokens": 10}, False

        monkeypatch.setattr(ownership_guard, "classify_intent_structured", _would_say_group)
        monkeypatch.setattr(ownership_guard.attendance_mod, "_decode_jwt_claims",
                            lambda bearer: {})

        writer = FakeWriter()
        result = await ownership_guard.ownership_guard_node(
            {"query": "show my team pending leaves", "bearer_token": "t",
             "is_manager": False}, writer)

        assert result["blocked"] is False
        assert writer.of_type("guardrail") == []
        assert ownership_guard._route_after_ownership(result) == "classify_node"

    async def test_end_to_end_a_non_manager_gets_the_card_not_a_block(self, monkeypatch):
        """Guard -> node, in order, for the exact reported query."""
        import services.ownership_guard as ownership_guard

        async def _would_say_group(prompt, labels, fallback_label="unknown"):
            return "group", {"total_tokens": 10}, False

        monkeypatch.setattr(ownership_guard, "classify_intent_structured", _would_say_group)
        monkeypatch.setattr(ownership_guard.attendance_mod, "_decode_jwt_claims",
                            lambda bearer: {})
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        query = "show my team pending leaves"
        guard_writer = FakeWriter()
        guarded = await ownership_guard.ownership_guard_node(
            {"query": query, "bearer_token": "t", "is_manager": False}, guard_writer)
        assert guarded["blocked"] is False

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

        notice = writer.of_type("access_notice")[0]["data"]
        assert notice["title"] == "Not available"
        assert notice["capability"] == "team_leave"
        assert result["response_text"] == FIGMA_LEAVE_REFUSAL
        assert writer.of_type("done")[0]["intent"] == "team_attendance_restricted"
        # Not the attendance-worded block the caller was actually getting.
        assert "attendance details for your own account" not in result["response_text"]


# =============================================================================
# A manager is never shown the card
# =============================================================================

class TestManagersNeverSeeTheCard:

    async def test_the_empty_state_is_not_a_permission_refusal(self, monkeypatch):
        """The Figma's two states are distinct: a manager with nothing
        pending gets the plain "Great news!" line and NO card. Collapsing
        them would tell a manager they lack access to their own team."""
        async def _empty(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "access_scope": "direct_reports",
                "total_pending_leaves": 0,
                "leaves": [],
            }}}

        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context)
        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", _empty)

        state = base_state("Show pending leave requests for my team.",
                           "HRMS_TEAM_LEAVE_QUERY")
        state["is_manager"] = True
        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(state, writer)

        assert result["response_text"] == FIGMA_EMPTY_STATE
        assert writer.of_type("access_notice") == []
        assert writer.of_type("done")[0]["intent"] == "HRMS_TEAM_LEAVE_QUERY"
