"""Every way of asking for the team's leave means the same thing.

Reported, side by side in one conversation:

    "show team pending leaves"     -> "Sorry, I can only share attendance
                                       details for your own account ..."
    "show my team pending leaves"  -> the "Not available" card

One word apart, two entirely different answers - and the first is about
ATTENDANCE, for a question about leave.

Both _TEAM_QUERY_PATTERNS required "my team" or "team's", so every phrasing
without "my" missed. Missing was not the worst of it: "show team pending
leaves" then matched _LEAVE_STATUS_PATTERNS and came back as the CALLER'S
OWN leave status, which is how a team question reached the attendance
ownership guard at all and got refused there.

The new pattern is adjacency-only - "team" has to sit directly against the
leave wording - so "leave for the team building day" stays an ordinary leave
application. That is what the second class below pins.
"""

import pytest
from unittest.mock import AsyncMock, patch

import services.hr_graph as hr_graph
import services.classify_node as classify_node
import services.ownership_guard as ownership_guard
from services.nlp_service import fast_classify


TEAM_LEAVE = "HRMS_TEAM_LEAVE_QUERY"

#: The reported variants, with and without "my", "pending" and the verb.
PHRASINGS = [
    "show team leaves",
    "view team leaves",
    "show team pending leaves",
    "view team pending leaves",
    "show my team leaves",
    "view my team leaves",
    "show my team pending leaves",
    "view my team pending leaves",
    "team leaves",
    "team pending leaves",
    "show the team leaves",
    "team leave requests",
    "view team leave request",
    "show team's leave requests",
]


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

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

    def types(self):
        return [e.get("type") for e in self.events]

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


class TestEveryPhrasingIsTheSameQuestion:

    @pytest.mark.parametrize("query", PHRASINGS)
    def test_they_all_classify_as_a_team_leave_query(self, query):
        assert fast_classify(query)[0] == TEAM_LEAVE

    @pytest.mark.parametrize("query", PHRASINGS)
    def test_they_all_take_the_deterministic_team_route(self, query):
        assert classify_node._is_team_leave_query(query) is True

    @pytest.mark.parametrize("query", PHRASINGS)
    def test_none_is_read_as_the_callers_own_leave_status(self, query):
        """"show team pending leaves" scored leave_status at full confidence,
        which is what sent it to the attendance guard."""
        assert fast_classify(query)[0] != "leave_status"


class TestTheAttendanceGuardLetsThemThrough:

    @pytest.mark.parametrize("query", PHRASINGS)
    def test_they_are_exempt_from_the_ownership_guard(self, query):
        assert ownership_guard._is_own_team_capability_query(query) is True

    @pytest.mark.parametrize("query", ["show team pending leaves", "team leaves"])
    async def test_the_guard_does_not_block_them(self, query, monkeypatch):
        """Even with the guard's own classifier calling it a "group"
        question, which is what it answered live."""
        monkeypatch.setattr(ownership_guard, "classify_intent_structured",
                            AsyncMock(return_value=("group", None, False)))
        monkeypatch.setattr(ownership_guard.attendance_mod, "_decode_jwt_claims",
                            lambda bearer: {})

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

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


class TestANonManagerGetsTheSameCardForAllOfThem:

    @pytest.fixture(autouse=True)
    def not_a_manager(self, monkeypatch):
        async def _context(token, **kwargs):
            return {"http_status": 200, "body": {"success": True,
                                                 "data": {"is_manager": False}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _context)

    @pytest.mark.parametrize("query", PHRASINGS)
    async def test_the_not_available_card_is_emitted(self, query):
        writer = FakeWriter()
        result = await hr_graph.team_leave_query_node(
            {"query": query, "intent": TEAM_LEAVE, "usage_events": [],
             "bearer_token": "t", "company_id": 1, "conversation_id": "conv-1",
             "has_date_expression": False, "is_manager": False}, writer)

        notice = writer.of_type("access_notice")
        assert len(notice) == 1
        assert notice[0]["data"]["title"] == "Not available"
        assert writer.of_type("done")[0]["intent"] == "team_attendance_restricted"
        # Never the attendance-worded refusal, for a leave question.
        assert "attendance details for your own account" not in result["response_text"]

    async def test_the_answer_is_identical_with_and_without_my(self):
        """The reported pair, one word apart."""
        answers = []
        for query in ("show team pending leaves", "show my team pending leaves"):
            writer = FakeWriter()
            result = await hr_graph.team_leave_query_node(
                {"query": query, "intent": TEAM_LEAVE, "usage_events": [],
                 "bearer_token": "t", "company_id": 1, "conversation_id": "conv-1",
                 "has_date_expression": False, "is_manager": False}, writer)
            answers.append(result["response_text"])

        assert answers[0] == answers[1]


class TestWhatMustNotBeSweptIn:

    @pytest.mark.parametrize("query", [
        "leave for the team building day",
        "apply leave for team outing",
        "i need leave for a team event",
    ])
    def test_a_leave_application_mentioning_a_team_is_not_a_team_query(self, query):
        """The reason the pattern is adjacency-only: "team" near "leave" is
        not the same as "team leave"."""
        assert fast_classify(query)[0] != TEAM_LEAVE
        assert classify_node._is_team_leave_query(query) is False

    @pytest.mark.parametrize("query", [
        "my leave balance", "show my pending leaves", "show my leave requests",
    ])
    def test_the_callers_own_questions_are_untouched(self, query):
        assert fast_classify(query)[0] != TEAM_LEAVE

    @pytest.mark.parametrize("query,expected", [
        ("team attendance", "HRMS_TEAM_ATTENDANCE_QUERY"),
        ("show my team members", "HRMS_TEAM_MEMBERS_QUERY"),
    ])
    def test_the_sibling_team_capabilities_keep_their_own_route(self, query, expected):
        assert fast_classify(query)[0] == expected
