"""A non-Manager/HR caller asking to SEE team (or another employee's)
regularization requests is refused in erp-api's own words:

    GET /api/v1/ai/regularizations?type=all
    {"success": false, "message": "Only Manager/HR users can view team regularization requests."}

Before, the same question got a different sentence depending on which layer
answered it: the ownership guard said "I can only share attendance details",
the approval node's gate said "Reviewing and approving ... managers only",
and a caller the guard labelled "self" could fall through into the APPLY
flow. Approving stays on its own, approve-worded refusal.
"""
import pytest

import services.classify_node as classify_node
import services.ownership_guard as ownership_guard
import services.regularisation_approval as regularisation_approval
from services.regularisation_guards import TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE

ERP_REFUSAL = "Only Manager/HR users can view team regularization requests."


class Writer:
    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 done(self):
        return self.of_type("done")[-1]


def test_the_message_is_erp_apis_own_wording():
    assert TEAM_REGULARISATION_VIEW_NOT_ALLOWED_MESSAGE == ERP_REFUSAL


# -- regularisation_approval_node --------------------------------------------

class FakeErp:
    def __init__(self, list_result=None):
        self.list_result = list_result
        self.list_calls = []

    async def get_pending_regularizations(self, token, employee_id=None,
                                          company_id=None, conversation_id=None):
        self.list_calls.append(employee_id)
        return self.list_result


@pytest.fixture
def erp(monkeypatch):
    fake = FakeErp()
    monkeypatch.setattr(regularisation_approval.erp_client, "get_pending_regularizations",
                        fake.get_pending_regularizations)
    monkeypatch.setattr(regularisation_approval.leave_slot_service, "get_manager_action",
                        lambda c, k: None)
    monkeypatch.setattr(regularisation_approval.leave_slot_service, "clear_manager_action",
                        lambda c, k: None)
    return fake


def _state(query, intent, is_manager):
    return {"query": query, "intent": intent, "usage_events": [],
            "bearer_token": "caller-token", "company_id": 26,
            "conversation_id": "conv-view-refusal", "is_manager_jwt": True,
            "is_manager": is_manager, "is_hr_role": False}


class TestApprovalNodeGate:
    async def test_non_manager_view_is_refused_in_erp_words_without_a_fetch(self, erp):
        writer = Writer()
        await regularisation_approval.regularisation_approval_node(
            _state("show my team regularization requests",
                   regularisation_approval.VIEW_INTENT, is_manager=False), writer)

        assert writer.done()["data"]["answer"] == ERP_REFUSAL
        assert writer.done()["intent"] == "team_attendance_restricted"
        assert erp.list_calls == []

    async def test_non_manager_approval_keeps_the_approve_wording(self, erp):
        writer = Writer()
        await regularisation_approval.regularisation_approval_node(
            _state("approve A Emp's regularization request",
                   regularisation_approval.APPROVAL_INTENT, is_manager=False), writer)

        assert writer.done()["data"]["answer"] == regularisation_approval.NOT_A_MANAGER_MESSAGE

    async def test_erp_403_is_shown_verbatim(self, erp):
        erp.list_result = {"http_status": 403,
                           "body": {"success": False, "message": ERP_REFUSAL}}
        writer = Writer()
        await regularisation_approval.regularisation_approval_node(
            _state("show pending regularization requests",
                   regularisation_approval.VIEW_INTENT, is_manager=True), writer)

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

    async def test_the_live_403_through_the_real_client(self, monkeypatch):
        """The exact Postman response: HTTP 403 Forbidden (the status is on
        the response, not in the body) with erp-api's sentence as the body.
        Through the REAL erp_client._request, so this pins that the 403 comes
        back as data (allow_403_body) and reaches the node's restricted
        branch, rather than raising ErpApiUnavailable and being reported as
        "unable to reach the HR system"."""
        import httpx

        request = httpx.Request("GET", "http://erp/api/v1/ai/regularizations")
        response = httpx.Response(403, json={"success": False, "message": ERP_REFUSAL},
                                  request=request)
        seen = {}

        async def fake_http(method, url, **kwargs):
            seen["params"] = kwargs.get("params")
            return response

        monkeypatch.setattr(regularisation_approval.erp_client._http, "request", fake_http)
        monkeypatch.setattr(regularisation_approval.erp_client, "_log_call_background",
                            lambda **kwargs: None)
        monkeypatch.setattr(regularisation_approval.leave_slot_service, "get_manager_action",
                            lambda c, k: None)
        monkeypatch.setattr(regularisation_approval.leave_slot_service, "clear_manager_action",
                            lambda c, k: None)

        writer = Writer()
        await regularisation_approval.regularisation_approval_node(
            _state("show pending regularization requests",
                   regularisation_approval.VIEW_INTENT, is_manager=True), writer)

        assert seen["params"] == {"type": "all", "status": "pending"}
        done = writer.done()
        assert done["intent"] == "team_attendance_restricted"
        assert done["data"]["answer"] == ERP_REFUSAL
        assert writer.of_type("access_notice")[0]["data"]["message"] == ERP_REFUSAL

    @pytest.mark.parametrize("http_status", [200, 400, 401, 422])
    async def test_a_success_false_refusal_gets_the_restricted_intent_and_card(self, erp, http_status):
        """erp-api's refusal is not guaranteed to arrive as a 403 — the body
        alone ({"success": false, "message": ...}) must produce the
        restricted intent and the card."""
        erp.list_result = {"http_status": http_status,
                           "body": {"success": False, "message": ERP_REFUSAL}}
        writer = Writer()
        await regularisation_approval.regularisation_approval_node(
            _state("show pending regularization requests",
                   regularisation_approval.VIEW_INTENT, is_manager=True), writer)

        done = writer.done()
        assert done["intent"] == "team_attendance_restricted"
        assert done["data"]["answer"] == ERP_REFUSAL
        notice = writer.of_type("access_notice")[0]["data"]
        assert notice["message"] == ERP_REFUSAL
        assert notice["capability"] == "regularisation_approval"

    async def test_a_success_false_without_a_message_uses_the_same_sentence(self, erp):
        erp.list_result = {"http_status": 200, "body": {"success": False}}
        writer = Writer()
        await regularisation_approval.regularisation_approval_node(
            _state("show pending regularization requests",
                   regularisation_approval.VIEW_INTENT, is_manager=True), writer)

        assert writer.done()["data"]["answer"] == ERP_REFUSAL
        assert writer.done()["intent"] == "team_attendance_restricted"


# -- ownership_guard ---------------------------------------------------------

async def _guard(monkeypatch, query, label):
    async def classify(prompt, labels, fallback_label="unknown"):
        return label, {"total_tokens": 1}, False

    monkeypatch.setattr(ownership_guard, "classify_intent_structured", classify)
    monkeypatch.setattr(ownership_guard.attendance_mod, "_decode_jwt_claims", lambda bearer: {})
    writer = Writer()
    result = await ownership_guard.ownership_guard_node(
        {"query": query, "bearer_token": "t", "is_manager": False, "is_hr_role": False}, writer)
    return result, writer


class TestOwnershipGuard:
    @pytest.mark.parametrize("query,label", [
        ("show Ayush Jio's regularization requests", "other"),
        ("show regularization requests of the sales team", "group"),
    ])
    async def test_a_refused_regularization_view_uses_erp_words(self, monkeypatch, query, label):
        result, writer = await _guard(monkeypatch, query, label)

        assert result["blocked"] is True
        event = writer.of_type("guardrail")[0]
        assert event["message"] == ERP_REFUSAL
        assert event["access_notice"]["capability"] == "other_employee_regularization"

    async def test_attendance_refusal_is_unchanged(self, monkeypatch):
        result, writer = await _guard(monkeypatch, "show Ayush Jio's attendance", "other")

        event = writer.of_type("guardrail")[0]
        assert "attendance details" in event["message"]
        assert event["access_notice"]["capability"] == "other_employee_attendance"

    async def test_applying_for_someone_else_keeps_the_attendance_wording(self, monkeypatch):
        result, writer = await _guard(monkeypatch, "apply regularization for Ayush Jio", "other")

        assert writer.of_type("guardrail")[0]["message"] != ERP_REFUSAL


# -- classify_node routing (the guard labelled it "self") ---------------------

class TestClassifyRoutesNonManagerTeamView:
    @pytest.fixture(autouse=True)
    def _no_llm(self, monkeypatch):
        async def _no_shift_verdict(query):
            return None, 0.0, None

        async def _no_classification(prompt, labels, fallback_label="unknown"):
            return fallback_label, None, True

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift_verdict)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _no_classification)
        monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda ns, c, v: None)

    def _state(self, query):
        return {"query": query, "company_id": 1, "conversation_id": "conv-team-view",
                "bearer_token": "t", "usage_events": [], "is_manager": False,
                "is_hr_role": False}

    @pytest.mark.parametrize("query", [
        "show my team regularization requests",
        "show team's pending regularisations",
        "list regularization requests of other employees",
        "show regularization requests of my reportees",
    ])
    async def test_team_scope_goes_to_the_view_node_which_refuses(self, query):
        out = await classify_node.classify_node(self._state(query), Writer())
        assert out["intent"] == "manager_regularisation_view", query

    @pytest.mark.parametrize("query,expected", [
        # A bare "show regularization requests" from an employee means their
        # own — refusing it would be wrong.
        ("show my regularization requests", "my_regularisation_view"),
    ])
    async def test_own_requests_are_untouched(self, query, expected):
        out = await classify_node.classify_node(self._state(query), Writer())
        assert out["intent"] == expected

    async def test_a_manager_asking_for_my_team_gets_the_team_queue_not_their_own(self):
        """"show MY TEAM regularization requests" used to match the own-
        requests pattern ("show ... my ... regulari") before the manager
        router, so a manager got their own list back."""
        state = {**self._state("show my team regularization requests"), "is_manager": True}
        out = await classify_node.classify_node(state, Writer())
        assert out["intent"] == "manager_regularisation_view"

    @pytest.mark.parametrize("query", [
        "show regularization requests",
        "apply regularization for my team",
        "approve team regularization",
    ])
    def test_the_matcher_needs_a_team_scope_and_no_apply_or_approve(self, query):
        assert classify_node._non_manager_team_regularisation_view(query.lower()) is False
