"""services/ownership_guard.py::ownership_guard_node — the pre-classify
attendance/punch ownership gate (START -> manager_gate_node -> HERE ->
classify_node).

Focus: it is scoped to ATTENDANCE/PUNCH data. A shift-assignment question
must pass straight through so classify_node can route it to
shift_query_node, which owns FR-06.4's shift-worded permission gate. The
guard blocking a shift query would emit an attendance-worded refusal and
intent "blocked" instead.
"""
import base64
import json

import pytest

import services.ownership_guard as og


def _jwt(payload: dict) -> str:
    seg = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
    return f"h.{seg}.s"


# Ayush Jio / geo3 — a plain employee (role that is NOT privileged).
EMP_JWT = _jwt({"name": "Ayush Jio", "emp_no": "geo3", "role_id": "5", "role_name": "user"})


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]


@pytest.fixture
def stub_classifier(monkeypatch):
    """Stub the guard's own OpenAI ownership classifier. Call the returned
    setter with the label it should produce; asserts it is NOT called when a
    test expects the shift short-circuit to fire first."""
    state = {"label": "self", "called": False}

    async def _fake(prompt, labels, fallback_label="unknown"):
        state["called"] = True
        return state["label"], {"total_tokens": 10}, False

    monkeypatch.setattr(og, "classify_intent_structured", _fake)
    return state


async def _run(query, bearer=EMP_JWT, is_manager=None):
    st = {"query": query, "bearer_token": bearer}
    if is_manager is not None:
        st["is_manager"] = is_manager
    writer = FakeWriter()
    result = await og.ownership_guard_node(st, writer)
    return result, writer


# ── shift queries must bypass this attendance guard ────────────────────────

class TestShiftQueriesBypassTheGuard:

    async def test_own_shift_query_passes_without_classifier_call(self, stub_classifier):
        result, writer = await _run("what shift am I assigned?")
        assert result == {"blocked": False}
        assert stub_classifier["called"] is False, "shift query should short-circuit before the LLM call"
        assert not writer.of_type("guardrail")

    async def test_teammate_shift_query_is_NOT_blocked_here(self, stub_classifier):
        """The reported bug: 'What shift is employee geo assigned?' was
        hard-blocked with an attendance-worded message. It must instead flow
        on to classify_node -> shift_query_node -> FR-06.4's own gate."""
        stub_classifier["label"] = "other"  # what the classifier WOULD say if reached
        result, writer = await _run("What shift is employee geo assigned?")
        assert result == {"blocked": False}
        assert stub_classifier["called"] is False
        assert not writer.of_type("guardrail")

    @pytest.mark.parametrize("query", [
        "what shift is Sarah on?",
        "shift details of geo3",
        "my shift timing",
        "which shift do I have",
        "provide me shift detail of employee id is 770",
    ])
    async def test_shift_phrasings_all_pass(self, stub_classifier, query):
        result, _ = await _run(query)
        assert result == {"blocked": False}
        assert stub_classifier["called"] is False

    async def test_out_of_scope_shift_phrasing_still_reaches_the_classifier(self, stub_classifier):
        """'change my shift' / a roster view scores 0.0 (an explicit
        out-of-scope veto in _score_shift_lookup_query, not just "no
        signal"), so the guard still evaluates it normally rather than
        waving it through."""
        stub_classifier["label"] = "self"
        result, _ = await _run("can I change my shift")
        assert result == {"blocked": False}      # 'self' -> allowed, but...
        assert stub_classifier["called"] is True  # ...it went through the classifier, not the shortcut

    @pytest.mark.parametrize("query", [
        "Please tell me A Sharma shift twice",
        "Show me the shift for FakeUser123",
        "tell me the shift for geo6",
    ])
    async def test_shift_phrasings_the_certain_tier_alone_would_have_missed(
            self, stub_classifier, query):
        """Live bug: these are unmistakably shift-assignment questions but
        match none of _is_shift_lookup_query's exact phrases (no "shift
        details", no "'s shift" possessive) — the OLD bypass check missed
        them, so they fell to this guard's own ATTENDANCE-scoped classifier,
        which correctly saw a named other employee and hard-blocked with the
        attendance-worded refusal before shift_query_node's own (correct,
        role-blind) shift-worded gate ever ran. The bypass now checks
        _score_shift_lookup_query > 0.0 (the same weak/domain-word tier
        classify_node's own routing consults), which catches all three."""
        result, writer = await _run(query)
        assert result == {"blocked": False}
        assert stub_classifier["called"] is False, f"{query!r} reached the attendance classifier"
        assert not writer.of_type("guardrail")


# ── the caller's own TEAM capabilities bypass it, same as shift ────────────

class TestOwnTeamCapabilitiesBypassTheGuard:
    """Reported: a non-manager asked "show my team pending leaves" and got

        intent "blocked", "Sorry, I can only share attendance details for
        your own account ..."

    - the ATTENDANCE refusal, for a LEAVE question, from a guard that never
    let the turn reach team_leave_query_node. That node's own gate answers
    with the "Not available" card naming the real rule (managers with direct
    or indirect reports), which is what the design calls for.

    Same shape as the shift exemption above: a different feature with its own
    permission gate must not be pre-empted here.
    """

    @pytest.mark.parametrize("query", [
        "show my team pending leaves",
        "show my team's leave requests",
        "show my team attendance",
        "who was absent in my team today",
        "show my team members",
    ])
    async def test_team_queries_pass_without_a_classifier_call(self, stub_classifier, query):
        stub_classifier["label"] = "group"  # what the classifier WOULD say
        result, writer = await _run(query)

        assert result == {"blocked": False}
        assert stub_classifier["called"] is False,             "an own-team question must short-circuit before the LLM label"
        assert not writer.of_type("guardrail")

    async def test_the_reported_query_is_not_blocked_for_a_plain_employee(self, stub_classifier):
        stub_classifier["label"] = "group"
        result, writer = await _run("show my team pending leaves", is_manager=False)

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

    async def test_a_manager_is_not_blocked_either(self, stub_classifier):
        """This also un-breaks managers: the "group" branch denied anyone
        whose is_manager was not already True on the state, and the label is
        an LLM call - so the same query passed or failed run to run."""
        stub_classifier["label"] = "group"
        result, _ = await _run("show my team pending leaves", is_manager=True)

        assert result["blocked"] is False

    async def test_someone_elses_team_is_still_not_a_bypass(self, stub_classifier):
        """The exemption is for the caller's OWN team. A department/other
        group phrasing is not one of the team capabilities and must still be
        judged by the guard."""
        stub_classifier["label"] = "group"
        result, writer = await _run("attendance for the sales team")

        assert stub_classifier["called"] is True
        assert result["blocked"] is True
        assert writer.of_type("guardrail")[0]["status"] == "failed"

    @pytest.mark.parametrize("query,exempt", [
        ("show my team pending leaves", True),
        ("show my team attendance", True),
        ("show my team members", True),
        ("attendance for the sales team", False),
        ("what is John's attendance this month", False),
        ("give me attendance for last week", False),
    ])
    def test_the_exemption_predicate_is_narrow(self, query, exempt):
        assert og._is_own_team_capability_query(query) is exempt


# ── the guard still does its real job for attendance/punch ─────────────────

class TestAttendanceOwnershipStillEnforced:

    async def test_other_employee_attendance_is_blocked_for_a_non_manager(self, stub_classifier):
        stub_classifier["label"] = "other"
        result, writer = await _run("why was John marked half-day")
        assert result == {"blocked": True}
        assert writer.of_type("guardrail")[0]["message"].startswith("Sorry, I can only share attendance")

    async def test_own_attendance_passes(self, stub_classifier):
        stub_classifier["label"] = "self"
        result, writer = await _run("show my attendance this week")
        assert result == {"blocked": False}
        assert not writer.of_type("guardrail")

    async def test_confirmed_manager_is_allowed_through(self, stub_classifier):
        stub_classifier["label"] = "other"
        result, writer = await _run("why was John marked half-day", is_manager=True)
        assert result == {"blocked": False}
        assert not writer.of_type("guardrail")
