"""
Tests for the shift-assignment-query feature (FR-06.1):
  - services/erp_client.py::get_active_shift
  - services/shift_query.py::shift_query_node

shift_query_node is exercised directly (not through the HTTP layer) with a
fake StreamWriter, same pattern as test_leave_action.py. The node now makes
one structured-extraction LLM call (services.ai_service.extract_shift_
target_fields) to detect an employee_id/employee_name in the query before
fetching — the _default_shift_target autouse fixture below stubs this to
"no target" (own shift) for every test unless a test overrides it via
mock_shift_target, so no real LLM call ever happens here.

Strict scope boundary under test: no specific-date lookup, no location, no
timezone (AC1's "other relevant detail" is generic passthrough of whatever
extra fields erp-api returns, never guessed at), and the "No Active Shift
Assigned" state (AC4) never shows blank fields or raises an error.

Employee targeting: erp-api itself enforces whether the caller's role may
view another employee's shift (live-verified: disallowed lookups come back
as a normal {"success": false, "message": "..."} body, not an exception) —
this module has no permission logic of its own to test.
"""

from unittest.mock import MagicMock, patch

import pytest

import services.erp_client as erp_client
import services.classify_node as classify_node
import services.hr_graph as hr_graph
import services.shift_query as shift_query
from services.erp_client import ErpApiTimeout, ErpApiUnavailable


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 = "what shift am I assigned?") -> dict:
    return {
        "query": query, "intent": "shift_query", "usage_events": [],
        "bearer_token": "caller-token", "company_id": 1, "conversation_id": "conv-1",
    }


@pytest.fixture(autouse=True)
def _default_shift_target(monkeypatch):
    """Default stub: query names no target employee (the common "my shift"
    case). Tests that need targeting behavior override via mock_shift_target."""
    async def _fake(query, today=None):
        return {"employee_id": None, "employee_name": None, "requested_date": None}, None
    monkeypatch.setattr(shift_query.ai_service, "extract_shift_target_fields", _fake)


def mock_shift_target(monkeypatch, employee_id: int | None = None,
                       employee_name: str | None = None, usage: dict | None = None,
                       requested_date: str | None = None):
    async def _fake(query, today=None):
        return {"employee_id": employee_id, "employee_name": employee_name,
                "requested_date": requested_date}, usage
    monkeypatch.setattr(shift_query.ai_service, "extract_shift_target_fields", _fake)


# Mirrors the confirmed live erp-api /api/v1/ai/shift-details response shape.
ACTIVE_SHIFT = {
    "shift_id": 247, "shift_name": "DEV Team", "shift_code": "SHIFT-26-0063",
    "shift_type": "NORMAL", "start_time": "10:00:00", "end_time": "19:00:00",
    "working_minutes": 540, "break_time_minutes": 30, "relief_time_minutes": 30,
    "week_off_day": [], "status": "1", "is_general_shift": False, "is_readonly": False,
    "session_summary": {"total_sessions": 0, "total_working_minutes": 0,
                         "total_break_time_minutes": 0, "total_relief_time_minutes": 0},
    "sessions": [],
}

# Mirrors the confirmed live erp-api "employee" sibling of "shift" in the
# same response, used to name the subject of a targeted lookup.
TARGET_EMPLOYEE = {
    "employee_id": 770, "employee_number": "em10", "employee_name": "A Akash",
    "email": "a@Gmail.com", "phone": "7271871666", "department_id": 70,
    "department_name": "Shopfloor Team", "designation_id": 96, "designation_name": "IT",
}

# Mirrors the confirmed live erp-api response for a manager-role caller
# (direct reports, no target named) — no "shift"/"employee" key at all, just
# a disambiguation prompt. Live-verified: this caller's own employee_id also
# comes back 403 "not found in your team" — this endpoint has no concept of
# a manager's own shift, only their team's.
TEAM_SELECTION_DATA = {
    "action_required": "select_employee",
    "access_scope": "direct_reports",
    "total_employees": 2,
    "employees": [
        {"employee_id": 3759, "employee_number": "geo6", "employee_name": "A Emp",
         "department_id": 70, "designation_id": 96, "has_shift_assignment": True},
        {"employee_id": 616, "employee_number": "User1", "employee_name": "Adarsh Tiwari",
         "department_id": 80, "designation_id": 119, "has_shift_assignment": False},
    ],
}


# ═════════════════════════════════════════════════════════════════════════════
# erp_client — get_active_shift
# ═════════════════════════════════════════════════════════════════════════════

class TestErpClientGetActiveShift:

    async def test_forwards_token_and_url(self):
        captured = {}

        async def _request(method, url, headers=None, **kwargs):
            captured.update(method=method, url=url, headers=headers)
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {"shift": ACTIVE_SHIFT}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            result = await erp_client.get_active_shift("caller-token-abc")

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/shift-details"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        assert result["body"]["data"]["shift"]["shift_name"] == "DEV Team"

    async def test_timeout_raises(self):
        import httpx

        async def _request(*a, **kw):
            raise httpx.TimeoutException("timed out")

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiTimeout):
                await erp_client.get_active_shift("tok")

    async def test_401_raises_unavailable(self):
        async def _request(*a, **kw):
            resp = MagicMock()
            resp.status_code = 401
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            with pytest.raises(ErpApiUnavailable):
                await erp_client.get_active_shift("tok")

    async def test_forwards_employee_id_as_query_param(self):
        captured = {}

        async def _request(method, url, headers=None, params=None, **kwargs):
            captured["params"] = params
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            await erp_client.get_active_shift("tok", employee_id=770)

        assert captured["params"] == {"employee_id": 770}

    async def test_forwards_employee_name_as_query_param(self):
        captured = {}

        async def _request(method, url, headers=None, params=None, **kwargs):
            captured["params"] = params
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            await erp_client.get_active_shift("tok", employee_name="Akash")

        assert captured["params"] == {"employee_name": "Akash"}

    async def test_no_target_sends_no_extra_params(self):
        captured = {}

        async def _request(method, url, headers=None, params=None, **kwargs):
            captured["params"] = params
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {}}
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http:
            mock_http.request = _request
            await erp_client.get_active_shift("tok")

        assert captured["params"] is None

    # ── erp-api ANSWERING vs erp-api being down ──────────────────────────
    # A targeted lookup ("what shift is EMP-4092 on?") can be declined by
    # erp-api on its own team-scope rules, or name someone it doesn't know.
    # Both are answers, and _request's default "any non-2xx is an outage"
    # rule used to turn them into ErpApiUnavailable — so a manager was told
    # "I'm unable to reach the HR system right now" and invited to retry
    # something that could never succeed.
    #
    # These four exercise the REAL _request status handling. The node-level
    # tests further down stub get_active_shift itself, which is why they went
    # on passing while this route was broken end to end.

    async def _call_with_status(self, status, body):
        async def _request(method, url, headers=None, params=None, **kwargs):
            resp = MagicMock()
            resp.status_code = status
            resp.json.return_value = body
            return resp

        with patch.object(erp_client, "ERP_API_URL", "http://erp.test"), \
             patch.object(erp_client, "_http") as mock_http, \
             patch.object(erp_client, "_log_call_background", lambda **k: None):
            mock_http.request = _request
            return await erp_client.get_active_shift("tok", employee_name="EMP-4092")

    async def test_403_team_scope_refusal_comes_back_as_a_body(self):
        """erp-api's live wording for a target the caller may not see. It is
        the honest answer, so it has to reach the caller intact."""
        body = {"success": False,
                "message": "I cannot retrieve information for other employees. "
                           "You can only access your own records."}

        result = await self._call_with_status(403, body)

        assert result["body"] == body
        assert result["http_status"] == 403

    async def test_400_business_error_comes_back_as_a_body(self):
        """erp-api uses 400 for validation and business rules alike - an
        employee code it doesn't recognise lands here."""
        body = {"success": False, "message": "Employee not found."}

        result = await self._call_with_status(400, body)

        assert result["body"] == body

    async def test_404_still_raises(self):
        """A fixed, no-ID route can only 404 when it isn't reachable (not
        deployed, wrong ERP_API_URL, proxy misroute). Surfacing that as a
        business answer would report a deploy gap as an answer about the
        employee, so this route deliberately does NOT opt into 404 bodies."""
        with pytest.raises(ErpApiUnavailable):
            await self._call_with_status(404, {"success": False, "message": "nope"})

    async def test_500_still_raises(self):
        """The opt-ins are scoped to the statuses erp-api uses to answer. A
        5xx is still an outage and must still read as one."""
        with pytest.raises(ErpApiUnavailable):
            await self._call_with_status(500, {"success": False, "message": "boom"})


# ═════════════════════════════════════════════════════════════════════════════
# shift_query_node
# ═════════════════════════════════════════════════════════════════════════════

def mock_active_shift(monkeypatch, shift: dict | None, success: bool = True,
                       message: str | None = None, employee: dict | None = None):
    async def _fake(token, **kwargs):
        data = {}
        if shift is not None:
            data["shift"] = shift
        if employee is not None:
            data["employee"] = employee
        return {"http_status": 200, "body": {
            "success": success, "message": message,
            "data": data,
        }}
    monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)


class TestShiftQueryNodeHappyPath:

    async def test_returns_shift_summary_card_with_name_and_timing(self, monkeypatch):
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        text = result["response_text"]
        assert "DEV Team" in text
        assert "10:00" in text and "19:00" in text

        done = writer.of_type("done")[0]
        assert done["data"]["shift"]["shift_name"] == "DEV Team"
        assert done["data"]["has_active_shift"] is True

    async def test_extra_fields_surfaced_generically(self, monkeypatch):
        """AC1's "any other relevant detail" — non-noise fields beyond
        name/start/end are shown too, e.g. week_off_day when populated."""
        shift_with_week_off = {**ACTIVE_SHIFT, "week_off_day": ["Saturday", "Sunday"]}
        mock_active_shift(monkeypatch, shift_with_week_off)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        text = result["response_text"]
        assert "Saturday" in text and "Sunday" in text

    async def test_noise_fields_not_surfaced(self, monkeypatch):
        """Internal/technical fields confirmed on the live shift object
        (bookkeeping ids/flags, nested session data) must not leak into the
        employee-facing card."""
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        text = result["response_text"]
        for noisy in ("SHIFT-26-0063", "NORMAL", "540", "is_readonly",
                      "session_summary", "Sessions"):
            assert noisy not in text

    async def test_fetching_shift_progress_event_emitted(self, monkeypatch):
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        await shift_query.shift_query_node(base_state(), writer)

        assert writer.of_type("fetching_shift")

    async def test_shift_summary_event_carries_structured_data(self, monkeypatch):
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        await shift_query.shift_query_node(base_state(), writer)

        events = writer.of_type("shift_summary")
        assert len(events) == 1
        assert events[0]["data"]["has_active_shift"] is True
        # erp-api's shift, with its times as HH:MM - no seconds are sent.
        from services.regularisation_display import shift_hhmm
        assert events[0]["data"]["shift"] == shift_hhmm(ACTIVE_SHIFT)
        assert events[0]["data"]["shift"]["start_time"] == "10:00"

    async def test_no_target_mentioned_sends_own_token_only(self, monkeypatch):
        """Default case ("my shift" / no name or ID mentioned): the caller's
        own bearer_token is the only identity signal forwarded, with no
        employee_id/employee_name set."""
        captured = {}

        async def _fake(token, **kwargs):
            captured["kwargs"] = kwargs
            captured["token"] = token
            return {"http_status": 200, "body": {"success": True, "data": {"shift": ACTIVE_SHIFT}}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert captured["token"] == "caller-token"
        assert captured["kwargs"]["employee_id"] is None
        assert captured["kwargs"]["employee_name"] is None
        assert "You're currently assigned to" in result["response_text"]


class TestShiftQueryNodeTeammateDenial:
    """HA-192: a shift query that names another employee (id or name) is
    refused with the exact approved string, BEFORE any erp-api call — for
    EVERY role. A confirmed manager or HR-role caller gets the identical
    denial a non-manager or a caller whose role can't be confirmed does; this
    route only ever answers for the caller's own shift, regardless of role,
    and the wording is fixed so it never reveals whether the target exists."""

    def _erp_must_not_be_called(self, monkeypatch):
        async def _boom(token, **kwargs):
            raise AssertionError(
                f"get_active_shift called for a teammate query: {kwargs!r}"
            )
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _boom)

    async def test_employee_id_target_denied_pre_fetch(self, monkeypatch):
        mock_shift_target(monkeypatch, employee_id=770)
        self._erp_must_not_be_called(monkeypatch)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            base_state("what shift is employee 770 on?"), writer)

        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_employee_name_target_denied_pre_fetch(self, monkeypatch):
        mock_shift_target(monkeypatch, employee_name="Akash")
        self._erp_must_not_be_called(monkeypatch)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            base_state("what shift is Akash on?"), writer)

        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_denial_string_is_the_approved_copy_verbatim(self):
        """AC1 / FS-6: character-for-character, and deliberately NOT erp-api's
        own access-control wording."""
        assert shift_query.TEAMMATE_SHIFT_DENIAL == (
            "I can only provide shift details for your own account."
        )
        assert "cannot retrieve information for other employees" not in \
            shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_fabricated_target_gets_identical_denial(self, monkeypatch):
        """AC2 — enumeration prevention: a made-up name yields byte-for-byte
        the same reply as a real one, and still no lookup."""
        self._erp_must_not_be_called(monkeypatch)

        mock_shift_target(monkeypatch, employee_name="A Akash")
        real = (await shift_query.shift_query_node(
            base_state("what shift is A Akash on?"), FakeWriter()))["response_text"]

        mock_shift_target(monkeypatch, employee_name="FakeUser123")
        fake = (await shift_query.shift_query_node(
            base_state("what shift is FakeUser123 on?"), FakeWriter()))["response_text"]

        assert real == fake == shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_denial_payload_carries_no_target_detail(self, monkeypatch):
        """AC1/AC2 — no shift fields, no employee list, no name, no date in
        the structured payload behind the denial."""
        mock_shift_target(monkeypatch, employee_name="Akash")
        self._erp_must_not_be_called(monkeypatch)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            base_state("what shift is Akash on?"), writer)

        done = writer.of_type("done")[0]
        assert set(done["data"].keys()) == {"answer", "has_active_shift", "denied"}
        assert done["data"]["has_active_shift"] is False
        assert done["data"]["denied"] is True
        for ev in writer.events:
            data = ev.get("data", {})
            assert "shift" not in data and "employees" not in data
            assert "date" not in data
        assert "Akash" not in result["response_text"]

    async def test_confirmed_manager_is_allowed_through_to_erp(self, monkeypatch):
        """A manager (state["is_manager"] True, set by manager_gate_node from
        the JWT role claim or erp-api's is_manager) may look up a team
        member — the named target reaches erp-api, which is the authority on
        whether that employee is in their team."""
        mock_shift_target(monkeypatch, employee_name="geo6")
        calls = []

        async def _fake(token, **kwargs):
            calls.append(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": {
                "shift": ACTIVE_SHIFT, "employee": TARGET_EMPLOYEE}}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

        state = base_state("show me geo6 shift timing details")
        state["is_manager"] = True

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert result["response_text"] != shift_query.TEAMMATE_SHIFT_DENIAL
        assert len(calls) == 1
        assert calls[0]["employee_name"] == "geo6" and calls[0]["employee_id"] is None
        assert TARGET_EMPLOYEE["employee_name"] in result["response_text"]

    async def test_confirmed_manager_named_employee_id_also_reaches_erp(self, monkeypatch):
        """Same allowance for an id-shaped target, not just a name — erp-api's
        per-target team scope is what decides an id it doesn't recognise, and
        it answers that as a business failure (403 + its own message), which
        is surfaced rather than replaced."""
        mock_shift_target(monkeypatch, employee_id=99999)
        calls = []

        async def _fake(token, **kwargs):
            calls.append(kwargs)
            return {"http_status": 403, "body": {
                "success": False,
                "message": "I cannot retrieve information for other employees."}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

        state = base_state("shift details of employee 99999")
        state["is_manager"] = True

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert len(calls) == 1
        assert calls[0]["employee_id"] == 99999 and calls[0]["employee_name"] is None
        assert result["response_text"] == "I cannot retrieve information for other employees."

    async def test_explicit_non_manager_is_denied(self, monkeypatch):
        """is_manager is False (erp-api / JWT said not a manager) → denied."""
        mock_shift_target(monkeypatch, employee_name="Akash")
        self._erp_must_not_be_called(monkeypatch)

        state = base_state("what shift is Akash on?")
        state["is_manager"] = False

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_unconfirmed_role_fails_closed(self, monkeypatch):
        """is_manager unresolved (None, or the "unknown" sentinel from an
        erp-api outage in the gate) is not True → still a denial, no fetch."""
        mock_shift_target(monkeypatch, employee_name="Akash")
        self._erp_must_not_be_called(monkeypatch)

        for value in (None, "unknown"):
            state = base_state("what shift is Akash on?")
            if value is not None:
                state["is_manager"] = value
            writer = FakeWriter()
            result = await shift_query.shift_query_node(state, writer)
            assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_extraction_usage_still_recorded_on_denial(self, monkeypatch):
        """The @Employee-extraction call is billed even though the request is
        then refused — the token cost was really incurred."""
        mock_shift_target(monkeypatch, employee_name="Akash",
                           usage={"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12})
        self._erp_must_not_be_called(monkeypatch)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            base_state("what shift is Akash on?"), writer)

        sources = [ev.get("source") for ev in result["usage_events"]]
        assert "shift_target_extraction" in sources

    async def test_self_query_is_unaffected(self, monkeypatch):
        """No @Employee target → the gate does not fire; own shift as normal."""
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert "DEV Team" in result["response_text"]
        assert result["response_text"] != shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_own_shift_no_active_shift_uses_generic_message(self, monkeypatch):
        """Untargeted no-shift case keeps the plain AC4 constant."""
        mock_active_shift(monkeypatch, None)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE



class TestShiftQueryNodeCollectiveScopeDenial:
    """A shift query whose subject is a GROUP — "what shift assigned to my
    team", "shift timings of all employees" — goes through the same role gate
    a named teammate does, before any erp-api call: refused for an ordinary
    employee, answered for a manager/HR/admin.

    Regression-covers the live bug this class was written for: these queries
    name no individual, so the extractor reports no target, is_targeted_lookup
    stayed False, and the node answered as though the caller had asked about
    themselves — an employee saw their OWN shift card in reply to a question
    about their team. The gate is deterministic and runs before the extraction
    call, so it cannot depend on how an LLM reads the subject.
    """

    #: Both live phrasings, plus the other collective shapes that mean the
    #: same thing. Every one of these must be refused.
    COLLECTIVE_QUERIES = [
        "what shift assigned to my team",
        "show my team shift details",
        "team shift details",
        "what is my team's shift",
        "shift details of my team",
        "what shift is my team on",
        "show me the shift details for my team members",
        "shift timings of all employees",
        "what shift is everyone on",
        "shift details for my department",
        "what shift do my direct reports have",
        "shift assignment of other employees",
    ]

    #: Ordinary self phrasings the gate must leave alone. Pinned here because
    #: a collective-scope test that only checks denials would happily pass
    #: with a pattern that refuses everything.
    SELF_QUERIES = [
        "what shift am I assigned?",
        "my shift",
        "i want to know my shift timing",
        "what is my current shift",
        "shift details",
        "what shift do I have on Friday",
    ]

    def _erp_must_not_be_called(self, monkeypatch):
        async def _boom(token, **kwargs):
            raise AssertionError(
                f"get_active_shift called for a collective-scope query: {kwargs!r}"
            )
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _boom)

    def _extraction_must_not_be_called(self, monkeypatch):
        """The gate is deterministic and runs FIRST — no LLM call is paid for
        a question that is refused whatever the extractor would have said."""
        async def _boom(query, today=None):
            raise AssertionError(f"extract_shift_target_fields called for: {query!r}")
        monkeypatch.setattr(shift_query.ai_service, "extract_shift_target_fields", _boom)

    @pytest.mark.parametrize("query", COLLECTIVE_QUERIES)
    async def test_collective_query_denied_pre_fetch(self, monkeypatch, query):
        self._erp_must_not_be_called(monkeypatch)
        self._extraction_must_not_be_called(monkeypatch)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(query), writer)

        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL

    @pytest.mark.parametrize("query", COLLECTIVE_QUERIES)
    async def test_confirmed_manager_is_answered_with_their_team(self, monkeypatch, query):
        """A manager may see their team's shifts, so the same question is not
        refused for them: erp-api resolves the team from their token and the
        reply names it, to pick one of."""
        async def _fake(token, **kwargs):
            return {"http_status": 200, "body": {
                "success": True, "data": TEAM_SELECTION_DATA,
                "message": "Please select an employee to view shift details."}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

        state = base_state(query)
        state["is_manager"] = True

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert result["response_text"] != shift_query.TEAMMATE_SHIFT_DENIAL
        assert "A Emp" in result["response_text"]
        assert writer.of_type("done")[0]["data"]["action_required"] == "select_employee"

    @pytest.mark.parametrize("privilege", ["is_hr_role", "jwt_admin"])
    async def test_hr_and_admin_are_answered_like_a_manager(self, monkeypatch, privilege):
        """The two other privileged roles reach the same answer by their own
        route: is_hr from erp-api's context response, admin from the JWT role
        claim (erp-api reports no is_admin at all)."""
        async def _fake(token, **kwargs):
            return {"http_status": 200, "body": {
                "success": True, "data": TEAM_SELECTION_DATA,
                "message": "Please select an employee to view shift details."}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

        state = base_state("what shift assigned to my team")
        if privilege == "is_hr_role":
            state["is_hr_role"] = True
        else:
            monkeypatch.setattr(shift_query.attendance_mod, "_decode_jwt_claims",
                                lambda token: {"name": "A Sharma", "role_name": "admin"})

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert result["response_text"] != shift_query.TEAMMATE_SHIFT_DENIAL
        assert "A Emp" in result["response_text"]

    @pytest.mark.parametrize("is_manager", [False, "unknown", None])
    async def test_an_unconfirmed_role_fails_closed(self, monkeypatch, is_manager):
        """MANAGER_UNKNOWN (erp-api unreachable) is not an allow: an outage
        must never widen what a caller can see."""
        self._erp_must_not_be_called(monkeypatch)

        state = base_state("what shift assigned to my team")
        state["is_manager"] = is_manager

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_denial_payload_carries_no_team_detail(self, monkeypatch):
        """No shift fields, no employee list, no date — identical in shape to
        the named-teammate denial, so the two cannot be told apart."""
        self._erp_must_not_be_called(monkeypatch)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            base_state("what shift assigned to my team"), writer)

        done = writer.of_type("done")[0]
        assert set(done["data"].keys()) == {"answer", "has_active_shift", "denied"}
        assert done["data"]["has_active_shift"] is False
        assert done["data"]["denied"] is True
        for ev in writer.events:
            data = ev.get("data", {})
            assert "shift" not in data and "employees" not in data
            assert "date" not in data
        assert "team" not in result["response_text"].lower()

    async def test_an_employee_team_query_never_lists_the_team(self, monkeypatch):
        """Pinned for the caller the rule protects: even when erp-api would
        have answered with the "select an employee" roster, no name from it
        can reach an employee's reply — the call is never made."""
        async def _fake(token, **kwargs):
            return {"http_status": 200, "body": {
                "success": True, "data": TEAM_SELECTION_DATA,
                "message": "Please select an employee to view shift details."}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

        state = base_state("what shift assigned to my team")
        state["is_manager"] = False

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL
        for employee in TEAM_SELECTION_DATA["employees"]:
            assert employee["employee_name"] not in result["response_text"]

    @pytest.mark.parametrize("query", SELF_QUERIES)
    async def test_self_queries_still_answered(self, monkeypatch, query):
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(query), writer)

        assert result["response_text"] != shift_query.TEAMMATE_SHIFT_DENIAL
        assert "DEV Team" in result["response_text"]

    async def test_manager_own_shift_is_still_answered(self, monkeypatch):
        """The gate must not swallow the manager-asking-about-THEMSELVES
        case: "my shift timing" is a self question and gets the caller's own
        shift, resolved from punch-details when /shift-details answers with a
        team menu (TestManagerOwnShiftResolvedFromPunchDetails owns that)."""
        async def _fake(token, **kwargs):
            return {"http_status": 200, "body": {
                "success": True, "data": TEAM_SELECTION_DATA,
                "message": "Please select an employee to view shift details."}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

        async def _fake_punch(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "shift": {"id": 247, "name": "DEV Team",
                          "start_time": "10:00:00", "end_time": "19:00:00"}}}}
        monkeypatch.setattr(shift_query.erp_client, "get_attendance_punch_details", _fake_punch)

        state = base_state("i want to know my shift timing")
        state["is_manager"] = True

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert result["response_text"] != shift_query.TEAMMATE_SHIFT_DENIAL
        assert "DEV Team" in result["response_text"]

    @pytest.mark.parametrize("is_manager", [True, False])
    async def test_the_team_ask_never_swallows_the_next_own_shift_ask(
            self, monkeypatch, is_manager):
        """The reported flow end to end: ask about the team (refused for an
        employee, answered with the roster for a manager), then ask about
        yourself in the next turn and be answered. Neither outcome leaves
        anything behind that could swallow the follow-up."""
        async def _shift_details(token, **kwargs):
            if is_manager:
                return {"http_status": 200, "body": {
                    "success": True, "data": TEAM_SELECTION_DATA,
                    "message": "Please select an employee to view shift details."}}
            return {"http_status": 200, "body": {
                "success": True, "data": {"shift": ACTIVE_SHIFT}}}

        async def _punch_details(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {
                "shift": {"id": 247, "name": "DEV Team",
                          "start_time": "10:00:00", "end_time": "19:00:00"}}}}

        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _shift_details)
        monkeypatch.setattr(shift_query.erp_client, "get_attendance_punch_details", _punch_details)

        def _state(query):
            state = base_state(query)
            state["is_manager"] = is_manager
            return state

        team = await shift_query.shift_query_node(
            _state("what shift assigned to my team"), FakeWriter())
        if is_manager:
            assert "A Emp" in team["response_text"]
        else:
            assert team["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL

        answered = await shift_query.shift_query_node(
            _state("show my shift details"), FakeWriter())
        assert "DEV Team" in answered["response_text"]

    def test_detector_matches_the_collective_subject_only(self):
        """The detector on its own, away from the node — the list above is
        what the gate is FOR, and the self list is what it must not touch."""
        for query in self.COLLECTIVE_QUERIES:
            assert shift_query._is_collective_shift_scope(query), query
        for query in self.SELF_QUERIES:
            assert not shift_query._is_collective_shift_scope(query), query

    def test_named_single_employee_is_not_a_collective_scope(self):
        """A named teammate is refused by the extractor-driven gate, with its
        own logging and its own usage accounting — this detector must not
        pre-empt it, and must not read a singular "employee 3754" (possibly
        the caller's own id) as a group."""
        assert not shift_query._is_collective_shift_scope("what shift is Akash on?")
        assert not shift_query._is_collective_shift_scope("shift details of employee 3754")
        assert not shift_query._is_collective_shift_scope("Priya's shift timing")


class TestShiftQueryNodeNoActiveShift:
    """AC4: no active shift assignment must show the defined explicit
    state, never blank fields and never an error."""

    async def test_missing_shift_data_shows_no_active_shift_message(self, monkeypatch):
        mock_active_shift(monkeypatch, None)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE
        done = writer.of_type("done")[0]
        assert done["data"]["has_active_shift"] is False

    async def test_empty_shift_object_shows_no_active_shift_message(self, monkeypatch):
        mock_active_shift(monkeypatch, {})

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE

    async def test_shift_without_a_name_treated_as_no_active_shift(self, monkeypatch):
        """A malformed/partial record with no name is not a real assignment
        — must not render a blank-looking card."""
        mock_active_shift(monkeypatch, {"start_time": "09:00:00", "end_time": "18:00:00"})

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE


class TestManagerOwnShiftResolvedFromPunchDetails:
    """A manager asking about their OWN shift gets their own shift.

    erp-api's /shift-details cannot answer that for a caller with direct
    reports — it replies with a "pick one of your team" menu (live-verified:
    even the manager's own employee_id comes back 403 "not found in your
    team"). That menu used to be handed straight back, so a manager asking
    "my shift timing" was never answered and was shown their reports' names
    instead, on a route that is self-only for every role.

    /attendance/punch-details serves the caller's own record for a manager
    too, so the answer is resolved from there. No employee param is sent to
    either endpoint: the bearer token alone selects the record.
    """

    #: The shift block as /attendance/punch-details spells it — different
    #: field names for the same object (id/name/week_off_days rather than
    #: shift_id/shift_name/week_off_day).
    PUNCH_SHIFT = {
        "id": 247, "name": "DEV Team", "start_time": "10:00:00",
        "end_time": "19:00:00", "week_off_days": ["Sunday"],
        "relief_time": "15", "status": "1",
    }

    def _mock_team_menu(self, monkeypatch):
        async def _fake(token, **kwargs):
            return {"http_status": 200, "body": {
                "success": True, "data": TEAM_SELECTION_DATA,
                "message": "Please select an employee to view shift details."}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)

    def _mock_punch_details(self, monkeypatch, shift, calls=None, success=True,
                            message=None):
        async def _fake(token, **kwargs):
            if calls is not None:
                calls.append(kwargs)
            return {"http_status": 200, "body": {
                "success": success, "message": message,
                "data": {"requested_date": "2026-09-22", "shift": shift}}}
        monkeypatch.setattr(shift_query.erp_client, "get_attendance_punch_details", _fake)

    async def test_manager_gets_their_own_shift_card(self, monkeypatch):
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, self.PUNCH_SHIFT)

        state = base_state("i want to know my shift timing")
        state["is_manager"] = True

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state, writer)

        assert "DEV Team" in result["response_text"]
        assert "10:00" in result["response_text"]
        assert "19:00" in result["response_text"]
        assert writer.of_type("done")[0]["data"]["has_active_shift"] is True

    async def test_the_card_is_worded_as_the_callers_own(self, monkeypatch):
        """Not a targeted lookup, so no subject name — "You're currently
        assigned", exactly as an employee's own answer reads."""
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, self.PUNCH_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert "You're currently assigned" in result["response_text"]

    async def test_the_team_menu_is_never_shown(self, monkeypatch):
        """The reported symptom: a self question answered with other people's
        names, and no action_required left in the payload for a UI to render
        as a picker."""
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, self.PUNCH_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        for employee in TEAM_SELECTION_DATA["employees"]:
            assert employee["employee_name"] not in result["response_text"]
        assert "select an employee" not in result["response_text"].lower()
        for event in writer.events:
            data = event.get("data", {})
            assert "action_required" not in data
            assert "employees" not in data

    async def test_punch_details_is_asked_for_the_caller_not_an_employee(self, monkeypatch):
        """No employee_id/employee_name on the fallback call — the caller's
        own token is what selects the record, so this cannot widen access."""
        self._mock_team_menu(monkeypatch)
        calls = []
        self._mock_punch_details(monkeypatch, self.PUNCH_SHIFT, calls=calls)

        await shift_query.shift_query_node(base_state("my shift"), FakeWriter())

        assert len(calls) == 1
        assert calls[0].get("employee_id") is None
        assert calls[0].get("employee_name") is None

    async def test_week_off_survives_the_field_rename(self, monkeypatch):
        """punch-details says week_off_days, /shift-details says
        week_off_day — the card must not lose the line to the spelling."""
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, self.PUNCH_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert "Week off: Sunday" in result["response_text"]

    async def test_bookkeeping_fields_are_not_printed(self, monkeypatch):
        """id/relief_time/status are the same noise _SHIFT_NOISE_FIELDS
        suppresses under the other endpoint's names — a passthrough would
        print them back purely because the spelling changed."""
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, self.PUNCH_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert "Relief Time" not in result["response_text"]
        assert "Status" not in result["response_text"]

    async def test_no_shift_on_the_record_is_the_ac4_state(self, monkeypatch):
        """punch-details returns shift: null on a week off. Now that the
        caller's OWN record really was consulted, AC4's defined state is the
        honest answer rather than a false claim."""
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, None)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE
        assert writer.of_type("done")[0]["data"]["has_active_shift"] is False

    async def test_shift_without_a_name_is_also_the_ac4_state(self, monkeypatch):
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, {"id": 9, "start_time": "10:00:00"})

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE

    async def test_punch_details_business_failure_surfaces_its_message(self, monkeypatch):
        self._mock_team_menu(monkeypatch)
        self._mock_punch_details(monkeypatch, None, success=False,
                                 message="Employee record not found.")

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert result["response_text"] == "Employee record not found."

    @pytest.mark.parametrize("exc,expected", [
        (ErpApiTimeout, "I couldn't reach the HR system in time — please try again in a moment."),
        (ErpApiUnavailable, "I'm unable to reach the HR system right now — please try again shortly."),
    ])
    async def test_punch_details_transport_failure_reads_as_an_outage(
            self, monkeypatch, exc, expected):
        self._mock_team_menu(monkeypatch)

        async def _boom(token, **kwargs):
            raise exc("down")
        monkeypatch.setattr(shift_query.erp_client, "get_attendance_punch_details", _boom)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert result["response_text"] == expected

    async def test_employee_path_does_not_call_punch_details(self, monkeypatch):
        """The fallback is reached only through the team-menu response. An
        ordinary caller, whose /shift-details answer carries a shift, must
        still be served by that one call alone."""
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        async def _boom(token, **kwargs):
            raise AssertionError("punch-details called for a plain own-shift answer")
        monkeypatch.setattr(shift_query.erp_client, "get_attendance_punch_details", _boom)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift"), writer)

        assert "DEV Team" in result["response_text"]

    def test_normaliser_maps_the_field_names(self):
        assert shift_query._shift_from_punch_details(self.PUNCH_SHIFT) == {
            "shift_id": 247, "shift_name": "DEV Team",
            "start_time": "10:00:00", "end_time": "19:00:00",
            "week_off_day": ["Sunday"],
        }

    @pytest.mark.parametrize("block", [None, {}, {"id": 5}, "not a dict", []])
    def test_normaliser_treats_an_unusable_block_as_no_shift(self, block):
        assert shift_query._shift_from_punch_details(block) == {}


# HA-192 (FR-06.4) removed the pre-HA-192 targeted-lookup flow entirely: a
# query naming another employee is now refused before any erp-api call (see
# TestShiftQueryNodeTeammateDenial), so erp-api's name-search "select one"
# shape and its single-hit auto-resolve are no longer reachable from this
# node. The class that exercised that path
# (TestShiftQueryNodeUnambiguousNameMatchAutoResolves) was deleted with it.
# TestManagerOwnShiftResolvedFromPunchDetails above still applies: that is
# the MANAGER-with-no-target-named case, where the node sends no employee
# param at all and is_targeted_lookup is False, so the denial gate does not
# fire — the caller is asking about themselves, and now gets an answer.


class TestShiftQueryNodeFallbacks:

    async def test_timeout_gives_clean_message_not_a_crash(self, monkeypatch):
        async def _timeout(token, **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _timeout)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert "try again" in result["response_text"].lower()

    async def test_unavailable_gives_clean_message(self, monkeypatch):
        async def _down(token, **kwargs):
            raise ErpApiUnavailable("connection refused")
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _down)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert "unable to reach" in result["response_text"].lower()

    async def test_erp_api_business_failure_surfaces_its_own_message(self, monkeypatch):
        mock_active_shift(monkeypatch, None, success=False, message="Employee record not found.")

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert result["response_text"] == "Employee record not found."


# ═════════════════════════════════════════════════════════════════════════════
# Routing — classify_node → shift_query_node
# ═════════════════════════════════════════════════════════════════════════════

class TestShiftQueryRouting:

    def test_routes_to_shift_query_node(self):
        state = {"intent": "shift_query", "is_hr": True, "error": None}
        assert hr_graph._route_after_classify(state) == "shift_query_node"

    def test_error_state_still_routes_to_end_first(self):
        state = {"intent": "shift_query", "is_hr": True, "error": "flagged"}
        assert hr_graph._route_after_classify(state) == hr_graph.END

    def test_shift_query_is_a_valid_intent_label(self):
        assert "shift_query" in hr_graph._VALID_INTENT_LABELS


# ═════════════════════════════════════════════════════════════════════════════
# The date the answer is for
# ═════════════════════════════════════════════════════════════════════════════

class TestAnswerCarriesItsDate:
    """erp-api's /shift-details response carries no date of its own - it
    answers for "right now" - so the node stamps the day the answer was
    true for, on the payload and on the card."""

    async def test_success_payload_carries_todays_date(self, monkeypatch):
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)
        today = shift_query._today_in_app_timezone().isoformat()

        writer = FakeWriter()
        await shift_query.shift_query_node(base_state(), writer)

        assert writer.of_type("done")[0]["data"]["date"] == today
        assert writer.of_type("shift_summary")[0]["data"]["date"] == today

    async def test_card_states_the_day_in_words(self, monkeypatch):
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)
        today = shift_query._today_in_app_timezone()

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert f"Date: {today.strftime('%A, %d %B %Y')}" in result["response_text"]

    async def test_date_precedes_timing_on_the_card(self, monkeypatch):
        """Reads as "which day, then which hours" - the day is the context
        for the hours, not a trailing footnote."""
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        text = (await shift_query.shift_query_node(base_state(), writer))["response_text"]

        assert text.index("Date:") < text.index("Timing:")

    async def test_targeted_lookup_denial_carries_no_date(self, monkeypatch):
        """HA-192: a teammate query is refused before any lookup, so there is
        no day being answered for — the denial payload carries no date."""
        mock_shift_target(monkeypatch, employee_id=770)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("what shift is A Akash on"), writer)

        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL
        assert "date" not in writer.of_type("done")[0]["data"]

    async def test_no_active_shift_carries_the_date_without_touching_ac4_copy(self, monkeypatch):
        """AC4's wording is a defined state string - the date rides the
        payload rather than being appended to the message."""
        mock_active_shift(monkeypatch, None)
        today = shift_query._today_in_app_timezone().isoformat()

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE
        done = writer.of_type("done")[0]
        assert done["data"]["date"] == today
        assert done["data"]["has_active_shift"] is False

    async def test_transport_failure_carries_no_date(self, monkeypatch):
        """Nothing was looked up, so there is no day to report on."""
        async def _timeout(*args, **kwargs):
            raise ErpApiTimeout("boom")
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _timeout)

        writer = FakeWriter()
        await shift_query.shift_query_node(base_state(), writer)

        assert "date" not in writer.of_type("done")[0]["data"]

    async def test_uses_the_configured_timezone_not_server_local(self, monkeypatch):
        """Near midnight a server-local date can disagree with the company's
        actual day, which would label the shift with the wrong one."""
        monkeypatch.setenv("QUOTA_TIMEZONE", "Pacific/Kiritimati")
        east = shift_query._today_in_app_timezone()
        monkeypatch.setenv("QUOTA_TIMEZONE", "Pacific/Midway")
        west = shift_query._today_in_app_timezone()

        # UTC+14 to UTC-11 is a 25-hour spread, so the two extremes are 0, 1
        # or 2 calendar days apart depending on the hour - never negative,
        # which is what would show the env var being ignored.
        assert east >= west
        assert (east - west).days <= 2

    def test_render_without_a_date_omits_the_line(self):
        """as_of is optional - the renderer stays usable without it."""
        text = shift_query._render_shift_card(ACTIVE_SHIFT)
        assert "Date:" not in text
        assert "Timing:" in text


class TestDateNamedInTheQuery:
    """A day named in the query is reported back as the answer's date. It
    cannot select the data: erp-api's /shift-details takes no date param and
    is live-verified to return identical output for any date given, so the
    shift shown is always the current assignment - and the card says so."""

    async def test_requested_date_replaces_today_in_the_payload(self, monkeypatch):
        mock_shift_target(monkeypatch, requested_date="2026-09-04")
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        await shift_query.shift_query_node(base_state("what shift do I have on Friday"), writer)

        done = writer.of_type("done")[0]["data"]
        assert done["date"] == "2026-09-04"
        assert done["date_from_query"] is True

    async def test_requested_date_labels_the_card(self, monkeypatch):
        mock_shift_target(monkeypatch, requested_date="2026-09-04")
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("shift details for 4 September"), writer)

        assert "Date: Friday, 04 September 2026" in result["response_text"]

    async def test_requested_date_carries_the_no_record_caveat(self, monkeypatch):
        """The one thing that must never be silent: the shift shown is the
        current assignment, not a record for the day asked about."""
        mock_shift_target(monkeypatch, requested_date="2026-09-04")
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift on Friday"), writer)

        assert "current shift assignment" in result["response_text"]
        assert "separate shift record for that date" in result["response_text"]

    async def test_no_date_in_query_falls_back_to_today_without_the_caveat(self, monkeypatch):
        mock_shift_target(monkeypatch, requested_date=None)
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)
        today = shift_query._today_in_app_timezone()

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        done = writer.of_type("done")[0]["data"]
        assert done["date"] == today.isoformat()
        assert done["date_from_query"] is False
        assert "separate shift record" not in result["response_text"]

    async def test_requesting_today_explicitly_is_not_treated_as_a_caveat(self, monkeypatch):
        """"what shift do I have today" names a date, but it is the date the
        data is actually for - no caveat is warranted."""
        today = shift_query._today_in_app_timezone()
        mock_shift_target(monkeypatch, requested_date=today.isoformat())
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("what shift do I have today"), writer)

        done = writer.of_type("done")[0]["data"]
        assert done["date"] == today.isoformat()
        assert done["date_from_query"] is False
        assert "separate shift record" not in result["response_text"]

    async def test_unparseable_date_is_discarded_not_rendered(self, monkeypatch):
        """A bad value from the extractor must never reach the card."""
        mock_shift_target(monkeypatch, requested_date="next friday")
        mock_active_shift(monkeypatch, ACTIVE_SHIFT)
        today = shift_query._today_in_app_timezone()

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state(), writer)

        done = writer.of_type("done")[0]["data"]
        assert done["date"] == today.isoformat()
        assert done["date_from_query"] is False
        assert "next friday" not in result["response_text"]

    async def test_no_active_shift_still_reports_the_requested_date(self, monkeypatch):
        mock_shift_target(monkeypatch, requested_date="2026-09-04")
        mock_active_shift(monkeypatch, None)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(base_state("my shift on Friday"), writer)

        done = writer.of_type("done")[0]["data"]
        assert done["date"] == "2026-09-04"
        assert done["date_from_query"] is True
        assert result["response_text"] == shift_query.NO_ACTIVE_SHIFT_MESSAGE

    async def test_the_date_is_never_sent_to_erp_api(self, monkeypatch):
        """erp-api takes no date parameter. Sending one would be dead weight
        that reads like the lookup is date-aware when it is not."""
        captured = {}

        async def _fake(token, **kwargs):
            captured.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "message": None,
                                                 "data": {"shift": ACTIVE_SHIFT}}}
        monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)
        mock_shift_target(monkeypatch, requested_date="2026-09-04")

        await shift_query.shift_query_node(base_state("my shift on Friday"), FakeWriter())

        assert not any("date" in k for k in captured), captured

    def test_dated_shift_questions_reach_the_shortcut(self):
        """Now that a named day is handled, 'tomorrow'/'yesterday' no longer
        veto the deterministic route - but ranges and rosters still do."""
        hit = hr_graph._is_shift_lookup_query
        assert hit("what shift do i have tomorrow")
        assert hit("what was my shift yesterday")
        assert not hit("show me my weekly shift roster")
        assert not hit("what shift do i have next week")
        assert not hit("can i change my shift")

    def test_possessive_teammate_shift_reaches_the_shortcut(self):
        """Live misroute: "What's EMP001's shift?" fell to the LLM classifier
        (the phrase list can't express "<someone>'s shift") and came back as
        manager_leave_request_lookup - a LEAVE lookup for a SHIFT question.
        shift_query_node owns the FR-06.4 gate for a named target, so the
        possessive form must route here deterministically."""
        hit = hr_graph._is_shift_lookup_query
        assert hit("what's emp001's shift?")
        assert hit("what is geo6's shift")
        assert hit("priya's shift timing")
        assert hit("emp001's shift")
        assert hit("john's shift assignment")
        # a named DAY possessive is punch_details / out of scope, not this
        assert not hit("today's shift")
        assert not hit("yesterday's shift")
        assert not hit("tomorrow's shift")

    def test_current_and_active_shift_phrasings_reach_the_shortcut(self):
        """"current shift" / "active shift" / "assigned shift" are ordinary
        ways to ask for one's own standing assignment; they used to miss the
        phrase list and depend on the LLM."""
        hit = hr_graph._is_shift_lookup_query
        assert hit("what is my current shift")
        assert hit("show me my active shift")
        assert hit("current shift")
        assert hit("active shift")
        assert hit("can you show my assigned shift")


# ═════════════════════════════════════════════════════════════════════════════
# Hybrid (regex + LLM) intent routing for the shift route — FR-06.1
# ═════════════════════════════════════════════════════════════════════════════
# The phrase list is closed by construction, so it now produces a SCORE and
# only the uncertain middle of that score pays for a second opinion. Three
# properties are worth holding still, and each has its own class below:
#
#   1. every phrasing that routed here on the regex alone still does, at the
#      same cost — no LLM call, whatever an LLM would have said;
#   2. the uncertain band asks, and the two judgements combine rather than
#      either one deciding alone;
#   3. no other route loses a query to the new weak tier.

async def _resolve(query: str):
    """(routed, confidence, usage) for a query, lowercasing the way
    classify_node does before it calls in."""
    return await classify_node._resolve_shift_route(query, query.lower())


def _stub_adjudicator(monkeypatch, is_shift, confidence, calls=None):
    """Replace the LLM adjudication with a fixed verdict. Passing calls=[]
    records every query that actually reached it, which is how the tests below
    assert that the deterministic tiers never pay for a call."""
    async def _fake(query):
        if calls is not None:
            calls.append(query)
        return is_shift, confidence, {"prompt_tokens": 350, "completion_tokens": 12}
    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _fake)


# Every phrasing the deterministic path owns today. If one of these ever needs
# an LLM call to reach shift_query, the shortcut has regressed — the whole
# point of the phrase list is that these cost nothing.
DETERMINISTIC_SHIFT_QUERIES = [
    # own shift, canonical
    "what shift am I on", "which shift am I in", "what's my shift",
    "whats my shift", "my shift", "my shift timing", "my shift timings",
    "my shift details", "shift details", "shift detail", "shift assignment",
    "shift assigned", "current shift", "active shift", "assigned shift",
    "working shift", "what is my current shift", "show me my active shift",
    "can you show my assigned shift", "shift", "shift?",
    # own shift, conversational wrapping
    "hey can you tell me what shift I am assigned to",
    "I need to know my shift timing",
    "could you please share my shift details",
    "what time does my shift start",
    "tell me about my shift",
    # a named colleague (shift_query_node applies FR-06.4's gate itself)
    "what's EMP001's shift?", "what is geo6's shift", "Priya's shift timing",
    "EMP001's shift", "John's shift assignment", "shift details of Akash",
    "what shift is Sarah on?", "shift details of geo3",
    "provide me shift detail of employee id is 770",
    "check Akash Kumar's shift assignment", "shift for geo6",
    # a single named day is in scope — the node reports the day back
    "what shift do I have tomorrow", "what was my shift yesterday",
    "my shift on Friday", "what shift am I on today",
]

# Out of scope for FR-06.1 (a change, a swap, a range, a roster). These share
# the vocabulary and must still reach the main classifier — and must not spend
# an LLM call on the way, since the veto is not a close call.
OUT_OF_SCOPE_SHIFT_QUERIES = [
    "can I change my shift", "I want to swap my shift", "please switch my shift",
    "update my shift", "modify my shift timing", "request a shift change",
    "apply for night shift", "show me my weekly shift roster",
    "what shift do I have next week", "my shift last week",
    "what is the shift rotation policy", "schedule for my shifts",
]

# Shift vocabulary in a shape the phrase list cannot express. These are what
# the adjudication call exists for: today they fall to the ~3.5k-token main
# classifier with no shift-specific guidance at all.
AMBIGUOUS_SHIFT_QUERIES = [
    "am I on the morning shift", "am I assigned a shift", "do I have a shift",
    "any info on the shift for me", "is there a shift for me",
    "the shift I work",
    "what are my duty hours", "my duty timing", "when do I start",
    "what time do I start", "what are my work timings", "my reporting time",
]

# Plainly another route's question, and caught by an explicit veto keyword —
# the adjudicator is never even asked about these, regardless of what it
# would have said.
OTHER_ROUTE_QUERIES = [
    # no shift vocabulary at all
    "what is my leave balance", "apply for casual leave tomorrow",
    "what is the maternity leave policy", "my payslip for August",
    "show John Doe leave request", "approve Priya's leave",
    # shift-adjacent vocabulary owned by a sibling route
    "plan next month's shifts", "who is on the night shift",
    "what time did I punch in",
    "why was I marked absent yesterday", "my attendance for the shift",
    "am I late today", "what time did I check in today",
]

# A misspelled "shift" scores 0.0 on the regex with no veto match, so these
# still reach the LLM - the typo-tolerance fix.
ZERO_SIGNAL_NON_VETOED_QUERIES = ["whats my shfit", "my shif today", "sihft for tomorrow?"]

# Nothing shift-like at all: these used to pay for the adjudicator call too
# (Oct 26: "What is Ashwagandha?" spent ~450 tokens and a serial round trip
# on it). The main classifier, which has its own shift_query label, decides.
NO_SHIFT_SIGNAL_QUERIES = ["What is Ashwagandha?", "no way", "how many hours did I work",
                           "what is photosynthesis", "hi"]


class TestDeterministicShiftPhrasingsNeverPayForACall:
    """Tier 1: an unmistakable phrasing routes on the pattern score alone."""

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", DETERMINISTIC_SHIFT_QUERIES)
    async def test_routes_without_an_llm_call(self, query, monkeypatch):
        calls = []
        # Stubbed to the WRONG answer on purpose: if the deterministic tier
        # ever consulted it, the route would flip and this would fail loudly
        # rather than silently getting slower.
        _stub_adjudicator(monkeypatch, False, 1.0, calls)

        routed, confidence, usage = await _resolve(query)

        assert routed is True, f"{query!r} lost the deterministic shift route"
        assert confidence >= classify_node._SHIFT_ROUTE_CONFIDENCE
        assert usage is None, f"{query!r} paid for an adjudication call"
        assert calls == [], f"{query!r} reached the LLM: {calls}"

    @pytest.mark.parametrize("query", DETERMINISTIC_SHIFT_QUERIES)
    def test_scores_at_or_above_the_route_threshold(self, query):
        """The scoring function delegates its certain tier to
        _is_shift_lookup_query, so the two can never disagree — this pins that
        contract rather than trusting the delegation to stay."""
        assert classify_node._is_shift_lookup_query(query.lower()) is True
        assert (classify_node._score_shift_lookup_query(query.lower())
                >= classify_node._SHIFT_ROUTE_CONFIDENCE)


class TestOutOfScopeShiftAsksAreVetoed:
    """Tier 3 (veto): same vocabulary, a question this node cannot answer."""

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", OUT_OF_SCOPE_SHIFT_QUERIES)
    async def test_falls_through_without_an_llm_call(self, query, monkeypatch):
        calls = []
        # Stubbed to an emphatic yes: a veto that can be talked out of by the
        # adjudicator is not a veto.
        _stub_adjudicator(monkeypatch, True, 1.0, calls)

        routed, confidence, usage = await _resolve(query)

        assert routed is False, f"{query!r} was swallowed by the shift route"
        assert confidence == 0.0
        assert usage is None
        assert calls == [], f"{query!r} reached the LLM: {calls}"


class TestAmbiguousShiftAsksAreAdjudicated:
    """Tier 2: enough signal to ask, not enough to route on."""

    @pytest.mark.parametrize("query", AMBIGUOUS_SHIFT_QUERIES)
    def test_scores_inside_the_adjudication_band(self, query):
        score = classify_node._score_shift_lookup_query(query.lower())
        assert classify_node._SHIFT_ADJUDICATE_FLOOR <= score
        assert score < classify_node._SHIFT_ROUTE_CONFIDENCE, (
            f"{query!r} would route without the LLM ever being asked")

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", AMBIGUOUS_SHIFT_QUERIES)
    async def test_a_confident_yes_wins_the_route(self, query, monkeypatch):
        calls = []
        _stub_adjudicator(monkeypatch, True, 0.9, calls)

        routed, confidence, usage = await _resolve(query)

        assert routed is True
        assert confidence >= classify_node._SHIFT_ROUTE_CONFIDENCE
        assert calls == [query], "the adjudicator gets the query as written"
        assert usage is not None, "an adjudicated turn must report its tokens"

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", AMBIGUOUS_SHIFT_QUERIES)
    async def test_a_confident_no_gives_the_turn_back(self, query, monkeypatch):
        _stub_adjudicator(monkeypatch, False, 0.9)

        routed, confidence, _ = await _resolve(query)

        assert routed is False
        assert confidence < classify_node._SHIFT_ADJUDICATE_FLOOR

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", AMBIGUOUS_SHIFT_QUERIES)
    async def test_a_hedging_yes_does_not_win_the_route(self, query, monkeypatch):
        """A 0.3-confidence "yes" is the adjudicator saying it can't tell -
        its prompt asks for exactly that - so the verdict is discarded rather
        than blended. Without the floor, a query at the top of the band
        (regex 0.69) rode a 0.3 "yes" over the threshold at 0.783, which is a
        shortcut taken on nobody's confidence.

        The main classifier, which weighs every other label, is the better
        place for a turn nobody is sure about: falling through costs a call
        this turn would have made anyway, a wrong shortcut costs an answer."""
        _stub_adjudicator(monkeypatch, True, 0.3)

        routed, confidence, _ = await _resolve(query)

        assert routed is False
        assert confidence == classify_node._score_shift_lookup_query(query.lower()), (
            "an unsure verdict must leave the pattern score untouched")

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", AMBIGUOUS_SHIFT_QUERIES)
    async def test_a_hedging_no_is_discarded_the_same_way(self, query, monkeypatch):
        """The floor is about certainty, not about which way the verdict
        points - an unsure "no" is no more actionable than an unsure "yes"."""
        _stub_adjudicator(monkeypatch, False, 0.3)

        routed, confidence, _ = await _resolve(query)

        assert routed is False
        assert confidence == classify_node._score_shift_lookup_query(query.lower())

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", AMBIGUOUS_SHIFT_QUERIES)
    async def test_a_verdict_right_at_the_floor_still_counts(self, query, monkeypatch):
        """The floor is a minimum, not an exclusive bound - pinned because an
        off-by-one here silently turns the whole adjudication tier off."""
        _stub_adjudicator(monkeypatch, True, classify_node._SHIFT_MIN_VERDICT_CONFIDENCE)

        _, confidence, _ = await _resolve(query)

        assert confidence > classify_node._score_shift_lookup_query(query.lower())

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", AMBIGUOUS_SHIFT_QUERIES)
    async def test_a_failed_call_degrades_to_the_regex_score(self, query, monkeypatch):
        """A provider blip must land on the behaviour that predates this call
        - the main classifier - not on an error and not on a guess."""
        async def _boom(query):
            return None, 0.0, None
        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _boom)

        routed, confidence, usage = await _resolve(query)

        assert routed is False
        assert confidence == classify_node._score_shift_lookup_query(query.lower())
        assert usage is None


class TestOtherRoutesKeepTheirQueries:
    """The weak tier is new reach, so the thing to prove is that it reaches
    nowhere it shouldn't - not even far enough to spend a call."""

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", OTHER_ROUTE_QUERIES)
    async def test_falls_through_without_an_llm_call(self, query, monkeypatch):
        calls = []
        _stub_adjudicator(monkeypatch, True, 1.0, calls)

        routed, confidence, usage = await _resolve(query)

        assert routed is False, f"the shift route took {query!r}"
        assert confidence < classify_node._SHIFT_ADJUDICATE_FLOOR
        assert usage is None
        assert calls == [], f"{query!r} reached the LLM: {calls}"


class TestZeroSignalQueriesAreAdjudicatedNotSkipped:
    """The typo-tolerance fix: a query with no veto keyword and no regex
    match (a misspelled "shift" scores identically) must still reach the
    adjudicator rather than being silently declined for free."""

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", ZERO_SIGNAL_NON_VETOED_QUERIES)
    async def test_reaches_the_adjudicator(self, query, monkeypatch):
        calls = []
        _stub_adjudicator(monkeypatch, False, 0.9, calls)

        routed, confidence, usage = await _resolve(query)

        assert calls == [query], f"{query!r} did not reach the LLM"
        assert usage is not None
        assert routed is False

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", ZERO_SIGNAL_NON_VETOED_QUERIES)
    async def test_a_confident_yes_still_wins_the_route(self, query, monkeypatch):
        """Proves the call result actually matters here, unlike the vetoed
        list above where even an emphatic yes is discarded."""
        _stub_adjudicator(monkeypatch, True, 0.95)

        routed, confidence, usage = await _resolve(query)

        assert routed is True
        assert usage is not None


class TestNoShiftSignalSkipsTheCall:

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", NO_SHIFT_SIGNAL_QUERIES)
    async def test_does_not_reach_the_adjudicator(self, query, monkeypatch):
        calls = []
        # An emphatic yes: if it were asked, the route would flip.
        _stub_adjudicator(monkeypatch, True, 1.0, calls)

        routed, confidence, usage = await _resolve(query)

        assert calls == [], f"{query!r} paid for an adjudication call"
        assert (routed, usage) == (False, None)

    @pytest.mark.parametrize("word", ["shift", "shifts", "shfit", "shif", "shiftt", "sihft"])
    def test_near_misses_of_shift_count(self, word):
        assert classify_node._mentions_shift_loosely(f"what is my {word}")

    # "swift" IS one letter from "shift" and pays for the call; harmless.
    @pytest.mark.parametrize("text", ["what is ashwagandha", "no way", "shy", "fifth day"])
    def test_other_words_do_not(self, text):
        assert not classify_node._mentions_shift_loosely(text)


class TestConfidenceBlending:
    """The two judgements combine; neither decides alone."""

    def test_agreement_moves_toward_certainty(self):
        blend = classify_node._blend_shift_confidence
        assert blend(0.45, True, 0.9) > 0.9
        assert blend(0.45, True, 1.0) == 1.0
        # a stronger pattern score reaches further on the same verdict
        assert blend(0.64, True, 0.5) > blend(0.45, True, 0.5)

    def test_disagreement_shrinks_toward_zero(self):
        blend = classify_node._blend_shift_confidence
        assert blend(0.69, False, 0.8) < classify_node._SHIFT_ADJUDICATE_FLOOR
        assert blend(0.69, False, 1.0) == 0.0
        # an unsure "no" leaves more of the pattern score standing
        assert blend(0.69, False, 0.2) > blend(0.69, False, 0.8)

    def test_no_verdict_leaves_the_regex_score_untouched(self):
        assert classify_node._blend_shift_confidence(0.57, None, 0.0) == 0.57

    def test_the_result_stays_a_probability(self):
        blend = classify_node._blend_shift_confidence
        for regex_score in (0.0, 0.4, 0.57, 0.69, 0.9, 1.0):
            for verdict in (True, False):
                for llm_confidence in (0.0, 0.25, 0.5, 0.75, 1.0):
                    assert 0.0 <= blend(regex_score, verdict, llm_confidence) <= 1.0


class TestClassifyNodeWiring:
    """The branch inside classify_node, not just the helper it calls."""

    @pytest.fixture
    def classify(self, monkeypatch):
        # Every mid-flow state checked before the shift branch, emptied so
        # this exercises one branch rather than Redis.
        monkeypatch.setattr(classify_node.leave_disambiguation_state,
                            "get_candidates", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.leave_history_clarify_state,
                            "get_state", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.leave_type_clarify_state,
                            "get_state", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.leave_cancel_state,
                            "get_state", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda *a, **k: {})
        monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: {})

        # Records rather than raises: classify_node wraps the main classifier
        # in its own try/except, so an exception here would be swallowed.
        reached = []

        async def _classifier(*a, **k):
            reached.append(True)
            return "general_hr", None, False

        monkeypatch.setattr(classify_node, "classify_intent_structured", _classifier)

        async def _moderate(*a, **k):
            return {}

        monkeypatch.setattr(classify_node, "_check_moderation", _moderate)

        async def _run(query):
            writer = FakeWriter()
            result = await classify_node.classify_node(
                {"query": query, "context": [], "intent": "general", "usage_events": [],
                 "company_id": 7, "conversation_id": "conv-1"},
                writer,
            )
            return result, writer, reached

        return _run

    @pytest.mark.asyncio
    async def test_an_adjudicated_yes_reaches_shift_query(self, classify, monkeypatch):
        _stub_adjudicator(monkeypatch, True, 0.95)

        result, writer, reached = await classify("am I assigned a shift")

        assert result["intent"] == "shift_query"
        assert writer.of_type("intent")[0]["intent"] == "shift_query"
        assert not reached, "the adjudicator settled this; the main classifier ran anyway"

    @pytest.mark.asyncio
    async def test_an_adjudicated_turn_reports_its_tokens(self, classify, monkeypatch):
        """The adjudication call is billable, so it has to show up in
        usage_events like every other LLM call the graph makes - otherwise it
        is spend nothing accounts for."""
        _stub_adjudicator(monkeypatch, True, 0.95)

        result, _, _ = await classify("am I assigned a shift")

        assert "shift_intent" in [e["source"] for e in result["usage_events"]]

    @pytest.mark.asyncio
    async def test_an_adjudicated_no_falls_through_to_the_main_classifier(
            self, classify, monkeypatch):
        _stub_adjudicator(monkeypatch, False, 0.9)

        result, _, reached = await classify("what are the office timings")

        assert result["intent"] != "shift_query"
        assert reached, "a declined shift ask must still be classified"

    @pytest.mark.asyncio
    async def test_a_deterministic_route_reports_no_tokens(self, classify, monkeypatch):
        _stub_adjudicator(monkeypatch, False, 1.0)

        result, _, reached = await classify("what shift am I on")

        assert result["intent"] == "shift_query"
        assert [e["source"] for e in result["usage_events"]] == []
        assert not reached

    @pytest.mark.asyncio
    async def test_the_emitted_frame_is_unchanged_by_adjudication(
            self, classify, monkeypatch):
        """Confidence is a routing detail and belongs in the log. Putting it on
        the stream would change a frame every client already parses."""
        _stub_adjudicator(monkeypatch, True, 0.95)

        _, adjudicated, _ = await classify("am I assigned a shift")
        _, deterministic, _ = await classify("what shift am I on")

        assert (adjudicated.of_type("intent")[0]
                == deterministic.of_type("intent")[0])


# ═════════════════════════════════════════════════════════════════════════════
# An erp-api refusal is an answer, not an outage
# ═════════════════════════════════════════════════════════════════════════════

class TestErpRefusalReachesTheUserIntact:
    """The regression this class exists for, from a live run (back when a
    named target still reached erp-api — see TestShiftQueryNodeTeammateDenial
    for why that path is denied pre-fetch now):

        {"query": "What shift is EMP-4092 working on Friday?"}
        -> "I'm unable to reach the HR system right now - please try again
            shortly."

    Nothing was unreachable. erp-api had answered, and _request's default
    "any non-2xx is an outage" rule turned its answer into ErpApiUnavailable
    on the way back. That status-code handling in erp_client.get_active_shift
    applies just as much to a SELF query (the only kind that still reaches
    erp-api at all) as it did to the targeted one this regression was first
    found on, so these now exercise the self-only path instead.

    Every other test of this refusal stubs get_active_shift itself, so the
    whole of erp_client's status handling sat below the seam and none of them
    could see it. These run the node through the REAL client and stub only
    the transport underneath it.
    """

    def _erp_responds(self, monkeypatch, status, body):
        async def _request(method, url, headers=None, params=None, **kwargs):
            resp = MagicMock()
            resp.status_code = status
            resp.json.return_value = body
            return resp
        monkeypatch.setattr(erp_client, "ERP_API_URL", "http://erp.test")
        monkeypatch.setattr(erp_client._http, "request", _request)
        monkeypatch.setattr(erp_client, "_log_call_background", lambda **k: None)

    async def _ask(self, monkeypatch, status, body):
        self._erp_responds(monkeypatch, status, body)
        state = base_state("what shift am I working on Friday?")
        state["is_manager"] = True
        return await shift_query.shift_query_node(state, FakeWriter())

    async def test_a_403_refusal_is_surfaced_not_reported_as_an_outage(self, monkeypatch):
        message = ("I cannot retrieve information for other employees. "
                   "You can only access your own records.")

        result = await self._ask(monkeypatch, 403, {"success": False, "message": message})

        assert result["response_text"] == message
        assert "unable to reach the HR system" not in result["response_text"]

    async def test_an_unknown_employee_code_is_surfaced(self, monkeypatch):
        """A 400 for an employee code erp-api doesn't know. Telling the user
        the HR system is down sends them back to retype a code that will be
        just as unknown next time."""
        result = await self._ask(monkeypatch, 400,
                                 {"success": False, "message": "Employee not found."})

        assert result["response_text"] == "Employee not found."

    async def test_a_genuine_outage_still_reads_as_one(self, monkeypatch):
        """The point is to stop mislabelling answers, not to stop reporting
        outages - a 5xx must still say the HR system is unreachable."""
        result = await self._ask(monkeypatch, 500, {"success": False, "message": "boom"})

        assert "unable to reach the HR system" in result["response_text"]

    async def test_a_missing_route_still_reads_as_an_outage(self, monkeypatch):
        """/shift-details takes no id, so a 404 is the route not being there
        - a deploy gap, which must not be dressed up as an answer about the
        employee who was asked about."""
        result = await self._ask(monkeypatch, 404, {"success": False, "message": "Not Found"})

        assert "unable to reach the HR system" in result["response_text"]
