"""services/permission_service.py - one rule for "may this caller see a
record that is not their own", and the capabilities that ask it.

The rule: a MANAGER, an HR user or an ADMIN may see their team; everyone
else sees only themselves. It used to be spelled "is the caller a manager"
in five separate nodes, which is how the HR and admin halves came to be
missing from all of them at once - a manager could pull up a report's leave,
attendance, shift and regularisations, an HR user could pull up none of them.

Each capability is exercised through its own node, not through the helper,
because the helper being right is worth nothing if a node forgets to ask it.
"""

import pytest

import services.attendance as attendance_mod
import services.hr_graph as hr_graph
import services.individual_report as individual_report
import services.permission_service as permission_service
import services.shift_query as shift_query
from services.permission_service import ACCESS_UNKNOWN, may_view_team, routes_as_manager


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]


EMPLOYEE = {"is_manager": False, "is_hr_role": False}
MANAGER = {"is_manager": True, "is_hr_role": False}
HR = {"is_manager": False, "is_hr_role": True}
UNRESOLVED = {"is_manager": ACCESS_UNKNOWN, "is_hr_role": ACCESS_UNKNOWN}

#: The three privileged roles, as each is actually recognised: the first two
#: from erp-api's /leave/context flags, admin from the JWT role claim only.
PRIVILEGED_CALLERS = [
    ("manager (erp is_manager)", MANAGER, {}),
    ("hr (erp is_hr)", HR, {}),
    ("admin (jwt role_name)", EMPLOYEE, {"role_name": "admin"}),
    ("manager (jwt role_name)", EMPLOYEE, {"role_name": "manager"}),
    ("hr (jwt role_name)", EMPLOYEE, {"role_name": "hr"}),
]


def _state(flags, query="show my team", intent="HRMS_TEAM_LEAVE_QUERY", claims=None):
    state = {"query": query, "intent": intent, "usage_events": [],
             "bearer_token": "caller-token", "company_id": 1,
             "conversation_id": "conv-1", "has_date_expression": False}
    state.update(flags)
    return state


# =============================================================================
# The rule itself
# =============================================================================

class TestTheRule:

    @pytest.mark.parametrize("label,flags,claims", PRIVILEGED_CALLERS)
    def test_every_privileged_role_may_view_a_team(self, label, flags, claims):
        assert may_view_team(_state(flags), claims=claims) is True, label

    def test_an_ordinary_employee_may_not(self):
        assert may_view_team(_state(EMPLOYEE), claims={}) is False

    def test_an_ordinary_jwt_role_is_not_a_privilege(self):
        """The JWT half is an ALLOW list, not "any role claim will do"."""
        assert may_view_team(_state(EMPLOYEE), claims={"role_name": "employee"}) is False

    def test_a_fresh_context_payload_is_read_for_both_flags(self):
        """A node that ran without the gate fetches /leave/context itself.
        Its is_hr half used to be dropped on the floor - only is_manager was
        kept - so an HR caller was refused by a node that had just been told
        they were HR."""
        assert may_view_team(_state(EMPLOYEE), claims={},
                             context_data={"is_manager": False, "is_hr": True}) is True
        assert may_view_team(_state(EMPLOYEE), claims={},
                             context_data={"is_manager": True, "is_hr": False}) is True
        assert may_view_team(_state(EMPLOYEE), claims={},
                             context_data={"is_manager": False, "is_hr": False}) is False

    def test_an_unreachable_erp_is_unknown_not_a_denial(self):
        """Refusing on the strength of an outage would assert something about
        this caller's scope that nobody actually knows."""
        assert may_view_team(_state(UNRESOLVED), claims={}) == ACCESS_UNKNOWN

    def test_an_unknown_role_is_still_allowed_by_a_privileged_jwt(self):
        """The JWT needs no round trip, so an outage cannot take it away."""
        assert may_view_team(_state(UNRESOLVED), claims={"role_name": "admin"}) is True

    def test_unknown_never_reads_as_true(self):
        assert may_view_team(_state(UNRESOLVED), claims={}) is not True

    def test_routing_collapses_unknown_to_false(self):
        """A routing shortcut must not send a turn to a manager node that
        would only refuse it."""
        assert routes_as_manager(_state(UNRESOLVED)) is False
        assert routes_as_manager(_state(MANAGER)) is True
        assert routes_as_manager(_state(HR)) is True
        assert routes_as_manager(_state(EMPLOYEE)) is False

    def test_the_unknown_sentinel_matches_the_graphs(self):
        """manager_gate_node writes individual_report.MANAGER_UNKNOWN onto
        the state for both flags; this module compares against its own copy
        rather than importing that one (the node imports this one)."""
        assert ACCESS_UNKNOWN == individual_report.MANAGER_UNKNOWN

    def test_a_missing_state_is_not_an_allow(self):
        assert may_view_team(None, claims={}) is False
        assert may_view_team({}, claims={}) is False


# =============================================================================
# Every capability that shows someone else's record asks it
# =============================================================================

class TestTeamLeaveIsVisibleToHrAndAdmin:

    @pytest.mark.parametrize("label,flags,claims", PRIVILEGED_CALLERS)
    async def test_pending_team_leave_is_fetched(self, monkeypatch, label, flags, claims):
        fetched = []

        async def _team_leaves(token, **kwargs):
            fetched.append(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}

        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", _team_leaves)
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: claims)

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            _state(flags, "show pending leave requests for my team"), writer)

        assert fetched, f"{label} was refused the team's leave"
        assert writer.of_type("access_notice") == []

    async def test_an_employee_still_gets_the_not_available_card(self, monkeypatch):
        def _never(token, **kwargs):
            raise AssertionError("no team data may be fetched for an employee")

        monkeypatch.setattr(hr_graph.erp_client, "get_team_leaves", _never)
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})

        writer = FakeWriter()
        await hr_graph.team_leave_query_node(
            _state(EMPLOYEE, "show pending leave requests for my team"), writer)

        assert writer.of_type("access_notice")


class TestTeamAttendanceIsVisibleToHrAndAdmin:

    @pytest.mark.parametrize("label,flags,claims", PRIVILEGED_CALLERS)
    async def test_team_attendance_is_fetched(self, monkeypatch, label, flags, claims):
        fetched = []

        async def _summary(token, **kwargs):
            fetched.append(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": {
                "summary": {"total": 0}, "employees": []}}}

        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: claims)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            _state(flags, "show my team attendance", "HRMS_TEAM_ATTENDANCE_QUERY"), writer)

        assert fetched, f"{label} was refused the team's attendance"
        assert writer.of_type("access_notice") == []

    async def test_an_employee_still_gets_the_not_available_card(self, monkeypatch):
        def _never(token, **kwargs):
            raise AssertionError("no team data may be fetched for an employee")

        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _never)
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            _state(EMPLOYEE, "show my team attendance", "HRMS_TEAM_ATTENDANCE_QUERY"), writer)

        assert writer.of_type("access_notice")


class TestIndividualReportIsVisibleToHrAndAdmin:
    """manager_leave_request_lookup / manager_attendance_explanation - a
    named employee's leave requests and their attendance day, the two
    capabilities behind "why was Ayush marked absent on the 20th"."""

    @pytest.fixture(autouse=True)
    def _no_extraction_call(self, monkeypatch):
        """The node's field extraction is an LLM call; it is past the gate
        this class is about, and stubbing it keeps the test off the network."""
        async def _fake(query, today=None):
            return {"employee_id": None, "employee_name": None,
                    "attendance_date": None, "asserted_status": None}, None
        monkeypatch.setattr(individual_report.ai_service,
                            "extract_individual_report_fields", _fake)

        async def _no_leaves(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {"leaves": []}}}
        monkeypatch.setattr(individual_report.erp_client, "get_team_leaves", _no_leaves)

    @pytest.mark.parametrize("label,flags,claims", PRIVILEGED_CALLERS)
    async def test_the_role_gate_lets_them_past(self, monkeypatch, label, flags, claims):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: claims)

        writer = FakeWriter()
        result = await individual_report.individual_report_node(
            _state(flags, "show leave requests", "manager_leave_request_lookup"), writer)

        assert result["response_text"] != individual_report.NOT_A_MANAGER_MESSAGE, label
        assert writer.of_type("done")[0]["intent"] != "team_attendance_restricted"

    async def test_an_employee_is_still_told_it_is_manager_only(self, monkeypatch):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})

        writer = FakeWriter()
        result = await individual_report.individual_report_node(
            _state(EMPLOYEE, "show leave requests", "manager_leave_request_lookup"), writer)

        assert result["response_text"] == individual_report.NOT_A_MANAGER_MESSAGE


class TestShiftIsVisibleToHrAndAdmin:
    """The shift route keeps its own named gate, which delegates here."""

    @pytest.mark.parametrize("label,flags,claims", PRIVILEGED_CALLERS)
    def test_the_shift_gate_delegates_to_the_shared_rule(self, label, flags, claims):
        assert shift_query._may_view_team_shifts(_state(flags), claims) is True, label

    def test_an_employee_is_refused_by_the_same_gate(self):
        assert shift_query._may_view_team_shifts(_state(EMPLOYEE), {}) is False

    def test_an_unresolved_role_fails_closed(self):
        """The one place that must collapse ACCESS_UNKNOWN to a refusal
        rather than to "I couldn't verify" - a shift lookup has a fixed
        denial string and no outage branch."""
        assert shift_query._may_view_team_shifts(_state(UNRESOLVED), {}) is False


class TestTheOwnershipGuardDoesNotPreemptAnyOfIt:
    """A per-node rule is only as good as the routing that reaches it: this
    guard runs first and used to hard-block "someone else's data" for anyone
    whose is_manager wasn't already True - which is every HR and admin
    caller, before their node ever ran."""

    @pytest.mark.parametrize("label,flags,claims", PRIVILEGED_CALLERS)
    async def test_a_privileged_caller_is_let_through(self, monkeypatch, label, flags, claims):
        import services.ownership_guard as ownership_guard

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

        monkeypatch.setattr(ownership_guard, "classify_intent_structured", _would_say_other)
        monkeypatch.setattr(ownership_guard.attendance_mod, "_decode_jwt_claims",
                            lambda bearer: claims)

        writer = FakeWriter()
        state = _state(flags, "what is Ayush's attendance this month")
        result = await ownership_guard.ownership_guard_node(state, writer)

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

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

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

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

        writer = FakeWriter()
        result = await ownership_guard.ownership_guard_node(
            _state(EMPLOYEE, "what is Ayush's attendance this month"), writer)

        assert result["blocked"] is True


class TestRoutingReachesTheWidenedNodes:
    """classify_node's manager-only LOOKUP shortcuts fire for HR and admin
    too - otherwise the widened gates are unreachable for them."""

    @pytest.mark.parametrize("label,flags,claims", PRIVILEGED_CALLERS)
    def test_lookup_shortcuts_fire(self, monkeypatch, label, flags, claims):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: claims)
        assert permission_service.routes_as_manager(_state(flags)) is True, label

    def test_they_do_not_fire_for_an_employee(self, monkeypatch):
        monkeypatch.setattr(attendance_mod, "_decode_jwt_claims", lambda token: {})
        assert permission_service.routes_as_manager(_state(EMPLOYEE)) is False


class TestApprovalRightsAreNotWidened:
    """Viewing is not approving. The approval shortcuts stay on is_manager,
    so nothing here hands an HR or admin caller the power to approve - only
    to see. Pinned so a later "make it consistent" change is a decision
    rather than an accident."""

    def test_the_approval_routing_still_reads_is_manager(self):
        import inspect
        import services.classify_node as classify_node

        source = inspect.getsource(classify_node.classify_node)
        for action in ("_is_bulk_approval_query(ql)", "_is_leave_approval_query(ql)"):
            line = next(l for l in source.splitlines() if action in l)
            assert 'state.get("is_manager") is True' in line, line
