"""
Tests for the attendance-explain feature (FR-04.1 / FR-04.2):
  - services/erp_client.py::get_attendance_status (real, confirmed erp-api
    contract — GET /api/v1/ai/attendance/query) — authoritative status LABEL
  - services/erp_client.py::get_punch_time (real, confirmed erp-api contract
    — GET /api/v1/ai/attendance/punch-details) — supporting shift/punch evidence
  - services/erp_client.py::get_attendance_explanation (originally-intended
    richer contract with grace-period/variance fields — erp-api doesn't
    expose these anywhere yet, kept for when/if it does)
  - services/attendance_explain.py::attendance_explain_node

attendance_explain_node is exercised directly (not through the HTTP layer)
with a fake StreamWriter, same pattern as test_leave_action.py /
test_punch_details.py. The date extraction LLM call is mocked so tests
don't depend on a real model.

REMAINING GAP: neither real erp-api endpoint returns a grace-period
threshold or a rule-engine-computed variance/delta — attendance_explain_node
says so explicitly rather than computing it itself (AC5). AC1/AC2/AC3's
shift-timing and punch-time references are now fully covered via
get_punch_time; AC4 (compound violations) still isn't testable since
neither endpoint returns multiple simultaneous violations for one day.
"""

import json
import pytest
from unittest.mock import MagicMock, patch

import services.hr_graph as hr_graph
import services.attendance_explain as attendance_explain
import services.date_query_resolver as date_query_resolver
import services.erp_client as erp_client
from services.erp_client import ErpApiTimeout, ErpApiUnavailable, ErpApiUnauthorized


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, context: list | None = None) -> dict:
    return {
        "query": query, "intent": "attendance_explain", "context": context or [],
        "usage_events": [], "bearer_token": "caller-token",
        "company_id": 1, "conversation_id": "conv-1",
    }


def mock_date_extraction(monkeypatch, date: str | None):
    """Patches attendance_explain._call_llm + _extract_text so date
    resolution returns exactly `date` (or null, forcing the today-fallback).

    Mocked in the SYMBOLIC schema _resolve_date_expression actually expects
    ("explicit_single" + "explicit_date") — attendance_explain.py's date
    extraction was migrated from an old flat {"date": ...} contract to this
    one (see _resolve_attendance_date's own docstring), but this mock
    still returned the old shape: _resolve_date_expression silently didn't
    recognise it, always falling through to today's date regardless of
    what was mocked here."""
    async def _fake_call_llm(prompt, max_tokens=None, model=None, **kwargs):
        return {"__date__": date}

    def _fake_extract_text(response):
        raw_date = response.get("__date__")
        if raw_date is None:
            return json.dumps({"type": "unknown"})
        return json.dumps({"type": "explicit_single", "explicit_date": raw_date, "employee_name": None})

    monkeypatch.setattr(attendance_explain, "_call_llm", _fake_call_llm)
    monkeypatch.setattr(attendance_explain, "_extract_text", _fake_extract_text)


@pytest.fixture(autouse=True)
def _disable_llm_reason_by_default(monkeypatch):
    """Most tests in this file validate the deterministic card / reason /
    punch logic, not the LLM reason-generation feature — default it to
    'unavailable' (mirrors attendance_explain_node's own fallback path) so
    those tests keep asserting the exact deterministic _build_status_reason
    text. TestGenerateStatusReasonViaLLM and TestAttendanceExplainNodeLLMReason
    override this explicitly to exercise the LLM path itself."""
    async def _disabled(*a, **kw):
        return None, None
    monkeypatch.setattr(attendance_explain, "_generate_status_reason_via_llm", _disabled)


def mock_llm_reason(monkeypatch, text: str | None, usage: dict | None = None):
    async def _fake(*a, **kw):
        return text, usage
    monkeypatch.setattr(attendance_explain, "_generate_status_reason_via_llm", _fake)


# Fixture for the originally-intended richer contract (not erp-api's actual
# response shape today) — used only by TestErpClientAttendanceExplanation
# below, which tests get_attendance_explanation() as currently written.
LATE_VIOLATION = {
    "type": "late",
    "reason": "Check-in exceeded the grace threshold by 7 minutes.",
    "policy_rule": "Standard Shift Grace Policy",
    "shift": {"start": "09:00", "end": "18:00", "grace_minutes": 15},
    "actual": {"check_in": "09:22", "check_out": "18:05"},
    "variance": "Exceeded grace period by 7 minutes",
}


# ═════════════════════════════════════════════════════════════════════════════
# erp_client — get_attendance_explanation
# ═════════════════════════════════════════════════════════════════════════════

class TestErpClientAttendanceExplanation:

    async def test_forwards_token_date_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": {"status": "late", "violations": [LATE_VIOLATION]}}
            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_attendance_explanation("caller-token-abc", "2026-08-14")

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/attendance/explain?date=2026-08-14"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        assert result["body"]["data"]["status"] == "late"

    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_attendance_explanation("tok", "2026-08-14")

    async def test_401_raises_unauthorized(self):
        """401 means the caller's own token was rejected — distinct from a
        5xx/unreachable erp-api, and split into its own exception class so
        callers can show "log in again" rather than "system is down"."""
        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(ErpApiUnauthorized):
                await erp_client.get_attendance_explanation("tok", "2026-08-14")


class TestErpClientAttendanceStatus:
    """Real, confirmed erp-api contract: GET /api/v1/ai/attendance/query —
    status label per day only, no explanation fields."""

    async def test_forwards_token_range_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, "message": "Attendance retrieved successfully.",
                "data": {
                    "type": "daily", "from": "2026-06-02", "to": "2026-06-03", "total_days": 2,
                    "records": [
                        {"date": "2026-06-02", "day": "Tuesday", "status": "Present"},
                        {"date": "2026-06-03", "day": "Wednesday", "status": "Late"},
                    ],
                },
            }
            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_attendance_status("caller-token-abc", "2026-06-02", "2026-06-03")

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/attendance/query?from=2026-06-02&to=2026-06-03"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        records = result["body"]["data"]["records"]
        assert records[1]["status"] == "Late"

    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_attendance_status("tok", "2026-06-02", "2026-06-03")


class TestErpClientGetPunchTime:
    """Real, confirmed erp-api contract: GET /api/v1/ai/attendance/punch-details
    — shift timing + raw punch records for one day."""

    async def test_forwards_token_date_param_and_url(self):
        captured = {}

        async def _request(method, url, headers=None, params=None, **kwargs):
            captured.update(method=method, url=url, headers=headers, params=params)
            resp = MagicMock()
            resp.status_code = 200
            resp.json.return_value = {"success": True, "data": {
                "requested_date": "2026-06-02", "shift": {"start_time": "10:05:00", "end_time": "19:00:00"},
                "punch_status": "complete", "punches": [],
            }}
            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_punch_time("caller-token-abc", date="2026-06-02")

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/attendance/punch-details"
        assert captured["params"] == {"date": "2026-06-02"}
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        assert result["body"]["data"]["requested_date"] == "2026-06-02"

    async def test_omitted_date_sends_no_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_punch_time("tok")

        assert captured["params"] is None

    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_punch_time("tok", date="2026-06-02")


# ═════════════════════════════════════════════════════════════════════════════
# attendance_explain_node
# ═════════════════════════════════════════════════════════════════════════════

def mock_status(monkeypatch, records: list, capture: dict | None = None):
    """Patches erp_client.get_attendance_status (the real, confirmed
    endpoint) to return the given records list, optionally capturing the
    from/to args the node called it with. Also defaults get_punch_time to
    'unavailable' so tests that don't care about punch-details enrichment
    exercise the graceful-degrade (status-only) path — override afterward
    with mock_punch_details() for tests that do care."""
    async def _status(token, from_date, to_date, **kwargs):
        if capture is not None:
            capture["from_date"] = from_date
            capture["to_date"] = to_date
        return {"http_status": 200, "body": {
            "success": True, "message": "Attendance retrieved successfully.",
            "data": {"type": "daily", "from": from_date, "to": to_date,
                      "total_days": len(records), "records": records},
        }}
    monkeypatch.setattr(attendance_explain.erp_client, "get_attendance_status", _status)

    async def _no_punch_data(token, **kwargs):
        raise erp_client.ErpApiUnavailable("not mocked for this test")
    monkeypatch.setattr(attendance_explain.erp_client, "get_punch_time", _no_punch_data)


def mock_punch_details(monkeypatch, data: dict):
    async def _punch(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": data}}
    monkeypatch.setattr(attendance_explain.erp_client, "get_punch_time", _punch)


class TestResolveAttendanceDateDeterministicLayer:
    """Weekday/today/yesterday/ordinal-weekday-of-month arithmetic must be
    deterministic, not LLM-guessed — a live test against gpt-4o-mini showed
    it resolving a bare 'Monday' to the wrong day (a Sunday).

    Regression test — this class used to test the removed private
    _resolve_relative_date_deterministically/_WEEKDAY_NAMES directly;
    attendance_explain.py now delegates all of this to the shared
    services/date_query_resolver.py module (see _resolve_attendance_date),
    so these test the public async entry point instead, asserting no LLM
    usage was reported (usage_events == []) as the "resolved without an
    LLM round-trip" signal."""

    async def test_today_and_yesterday(self):
        import datetime
        today = attendance_explain._today()
        date, usage = await attendance_explain._resolve_attendance_date("why late today", [])
        assert (date, usage) == (today.isoformat(), [])
        date, usage = await attendance_explain._resolve_attendance_date("attendance for yesterday", [])
        assert (date, usage) == ((today - datetime.timedelta(days=1)).isoformat(), [])

    async def test_bare_weekday_name_resolves_to_most_recent_occurrence(self):
        import datetime
        today = attendance_explain._today()
        for name, idx in date_query_resolver.WEEKDAYS.items():
            expected = today - datetime.timedelta(days=(today.weekday() - idx) % 7)
            date, usage = await attendance_explain._resolve_attendance_date(f"why was I marked late on {name}", [])
            assert date == expected.isoformat(), f"{name}: expected {expected}, got {date}"
            assert usage == []

    async def test_next_weekday_resolves_forward(self):
        import datetime
        today = attendance_explain._today()
        for name, idx in date_query_resolver.WEEKDAYS.items():
            delta = (idx - today.weekday()) % 7 or 7
            expected = today + datetime.timedelta(days=delta)
            date, usage = await attendance_explain._resolve_attendance_date(f"attendance next {name}", [])
            assert (date, usage) == (expected.isoformat(), [])

    async def test_explicit_word_form_date_now_resolves_deterministically(self):
        """"June 2nd 2026" is now resolved by the shared date_query_resolver
        module directly (day+named-month is a closed, unambiguous shape) —
        no LLM round-trip needed, an improvement over the previous behavior
        this class used to assert (which deferred it to the LLM)."""
        date, usage = await attendance_explain._resolve_attendance_date(
            "why was I marked present on June 2nd 2026", [],
        )
        assert (date, usage) == ("2026-06-02", [])

    async def test_genuinely_unresolvable_query_falls_through_to_llm(self, monkeypatch):
        """A query with no date reference at all must still fall through to
        the LLM-based extraction (mocked here to a known date) rather than
        being guessed by the deterministic layer."""
        mock_date_extraction(monkeypatch, "2026-03-04")
        date, usage = await attendance_explain._resolve_attendance_date("why was I marked that way", [])
        assert date == "2026-03-04"

    async def test_nonexistent_ordinal_weekday_returns_the_sentinel(self):
        """"5th Wednesday" of a month that only has 4 must surface as the
        distinguishable NoSuchOrdinalWeekday case, not silently fall
        through to the LLM or default to today — see
        attendance_explain_node's own handling of this."""
        result, usage = await attendance_explain._resolve_attendance_date(
            "why was I marked absent fifth wednesday of june 2026", [],
        )
        assert isinstance(result, date_query_resolver.NoSuchOrdinalWeekday)
        assert (result.ordinal_word, result.weekday_name, result.year, result.month) == (
            "fifth", "wednesday", 2026, 6,
        )
        assert usage == []


class TestBuildStatusReason:
    """The 'reason' field must only ever restate facts already present in
    the fetched data (is_regularized flag, punch presence/completeness,
    future-date check) — never a computed comparison of punch times against
    shift start/end, which would cross into the classification logic AC5
    forbids."""

    def test_future_date_reason(self):
        import datetime
        future = (attendance_explain._today() + datetime.timedelta(days=5)).isoformat()
        reason = attendance_explain._build_status_reason("Upcoming", future, None)
        assert "future" in reason.lower()

    def test_no_punch_data_at_all_returns_none(self):
        """Punch-details lookup itself failed — nothing factual to report,
        must not guess."""
        assert attendance_explain._build_status_reason("Present", "2026-06-02", None) is None

    def test_regularized_flag_takes_priority(self):
        punch_data = {
            "attendance": {"is_regularized": True},
            "punches": [{"complete": True}],
            "punch_status": "complete",
        }
        reason = attendance_explain._build_status_reason("Regularized", "2026-06-02", punch_data)
        assert "regularized" in reason.lower()

    def test_no_records_reason(self):
        punch_data = {"attendance": {}, "punches": [], "punch_status": "no_records"}
        reason = attendance_explain._build_status_reason("Not Recorded", "2026-06-02", punch_data)
        assert "no punch records" in reason.lower()

    def test_all_complete_punches_reason(self):
        punch_data = {
            "attendance": {},
            "punches": [{"complete": True}, {"complete": True}],
            "punch_status": "complete",
        }
        reason = attendance_explain._build_status_reason("Present", "2026-06-02", punch_data)
        assert "2 punch session" in reason

    def test_mixed_complete_and_incomplete_punches_reason(self):
        punch_data = {
            "attendance": {},
            "punches": [{"complete": True}, {"complete": False}, {"complete": False}],
            "punch_status": "complete",
        }
        reason = attendance_explain._build_status_reason("Half Day Absent", "2026-06-02", punch_data)
        assert "1 complete" in reason and "2 incomplete" in reason

    def test_all_incomplete_punches_reason(self):
        punch_data = {
            "attendance": {},
            "punches": [{"complete": False}, {"complete": False}],
            "punch_status": "complete",
        }
        reason = attendance_explain._build_status_reason("Absent", "2026-06-02", punch_data)
        assert "2 punch session" in reason and "incomplete" in reason

    def test_never_mentions_shift_time_comparison(self):
        """Guard against regressions that would smuggle in a computed
        on-time/late judgement — the word 'shift' or a time comparison must
        never appear in a reason string."""
        punch_data = {
            "attendance": {},
            "shift": {"start_time": "10:05:00", "end_time": "19:00:00"},
            "punches": [{"complete": True, "check_in": "09:05:00"}],
            "punch_status": "complete",
        }
        reason = attendance_explain._build_status_reason("Present", "2026-06-02", punch_data)
        assert "shift" not in reason.lower()
        assert "10:05" not in reason and "09:05" not in reason


class TestClassifyAttendanceStatus:
    """"Half Day Absent" maps to "Missing Punch"; every other status maps
    to None. Deterministic lookup, no inference."""

    def test_half_day_absent_maps_to_missing_punch(self):
        assert attendance_explain._classify_attendance_status("Half Day Absent") == "Missing Punch"

    def test_half_day_absent_case_insensitive(self):
        assert attendance_explain._classify_attendance_status("half day absent") == "Missing Punch"
        assert attendance_explain._classify_attendance_status("HALF DAY ABSENT") == "Missing Punch"

    @pytest.mark.parametrize("status_label", [
        "Present", "Absent", "Leave", "Off", "Regularized", "Not Recorded",
        "Upcoming", "Late", "Half Day", "Missing Punch", "",
    ])
    def test_other_statuses_map_to_none(self, status_label):
        assert attendance_explain._classify_attendance_status(status_label) is None


class TestAttendanceExplainNodeClassification:
    """The "classification" key is always present in the card (never
    omitted) — "Missing Punch" for Half Day Absent, None otherwise."""

    async def test_half_day_absent_status_gets_missing_punch_classification(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": "Half Day Absent"}])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked half day absent"), writer)

        card = writer.of_type("attendance_explanation")[0]["data"]
        assert card["classification"] == "Missing Punch"
        assert result["response_text"]  # sanity: still produced an answer

    @pytest.mark.parametrize("status_label", ["Present", "Absent", "Off", "Not Recorded"])
    async def test_other_statuses_get_none_classification(self, monkeypatch, status_label):
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": status_label}])

        writer = FakeWriter()
        await attendance_explain.attendance_explain_node(base_state("why was I marked that way"), writer)

        card = writer.of_type("attendance_explanation")[0]["data"]
        assert card["classification"] is None

    async def test_classification_key_present_even_without_punch_data(self, monkeypatch):
        """Must not be omitted like "reason"/"shift"/"punches" are when
        punch-details is unavailable — classification comes purely from the
        status label, so it's always derivable."""
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": "Half Day Absent"}])
        # mock_status already defaults get_punch_time to unavailable

        writer = FakeWriter()
        await attendance_explain.attendance_explain_node(base_state("why was I marked half day absent"), writer)

        card = writer.of_type("attendance_explanation")[0]["data"]
        assert "classification" in card
        assert card["classification"] == "Missing Punch"
        assert "shift" not in card  # confirms punch_data really was unavailable in this test


class TestAttendanceExplainNodeDateResolution:

    async def test_resolved_date_is_passed_to_erp_client(self, monkeypatch):
        # "the 10th" is now itself resolved deterministically by
        # date_query_resolver (see TestBareOrdinalDayOfMonth in
        # test_date_query_resolver.py) and would never reach the mocked
        # LLM below at all. This test isn't about THAT rule — it's plumbing
        # (does a resolved date reach erp_client?) — so the deterministic
        # layer is forced off here to isolate the LLM-fallback path being
        # tested, independent of whichever phrasings it currently covers.
        monkeypatch.setattr(attendance_explain.date_query_resolver, "resolve", lambda *a, **kw: None)
        mock_date_extraction(monkeypatch, "2026-08-10")
        captured = {}
        mock_status(monkeypatch, [{"date": "2026-08-10", "day": "Monday", "status": "Present"}], capture=captured)

        writer = FakeWriter()
        await attendance_explain.attendance_explain_node(base_state("why was I marked present on the 10th"), writer)

        assert captured["from_date"] == "2026-08-10"
        assert captured["to_date"] == "2026-08-10"

    async def test_no_date_mentioned_asks_for_clarification_instead_of_defaulting(self, monkeypatch):
        """A query that names no date at all (the LLM extractor reports
        type "unknown") now asks the employee which date they mean, rather
        than silently defaulting to today and answering about a day they
        never asked about — see NoDateMentioned's own docstring. erp-api
        must never even be called in this case."""
        mock_date_extraction(monkeypatch, None)

        async def _status_must_not_be_called(*args, **kwargs):
            raise AssertionError("get_attendance_status should not be called with no date")
        monkeypatch.setattr(attendance_explain.erp_client, "get_attendance_status", _status_must_not_be_called)

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked that way"), writer)

        assert "which date" in result["response_text"].lower()


class TestAttendanceExplainNodeRendering:
    """Status label always comes from get_attendance_status(); when
    get_punch_time() also succeeds, shift timing and punch records enrich
    the card (AC1-AC3). No grace-period or variance is ever invented (AC5)
    since neither real endpoint returns one."""

    async def test_status_and_day_are_reported(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-06-03")
        mock_status(monkeypatch, [{"date": "2026-06-03", "day": "Wednesday", "status": "Late"}])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked late"), writer)

        text = result["response_text"]
        assert "2026-06-03" in text
        assert "Wednesday" in text
        assert "Late" in text
        events = writer.of_type("attendance_explanation")
        assert events[0]["data"] == {
            "date": "2026-06-03", "day": "Wednesday", "status": "Late", "classification": None,
        }

    @pytest.mark.parametrize("status_label,expected_action", [
        ("Missing Punch", "check your attendance details"),
    ])
    async def test_adverse_statuses_get_next_best_action(self, monkeypatch, status_label, expected_action):
        """AC6: relevant follow-up action for adverse outcomes — status
        labels normalized from erp-api's Title Case to internal slugs.

        "Late"/"Absent" are deliberately excluded from this parametrize
        list (see _ATTENDANCE_NEXT_ACTION_PROMPTS's own comment):
        attendance.py's _is_regularizable/HALF_DAY_ABSENT_STATUS treats
        ONLY "Half Day Absent" as regularizable, so offering the
        regularization follow-up for plain "Late"/"Absent" would invite a
        request the flow doesn't actually seed a date for — reproducing a
        previously-fixed broken-review-card bug. Covered instead by
        test_non_adverse_statuses_get_no_next_best_action below."""
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": status_label}])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why"), writer)

        assert expected_action in result["response_text"]

    @pytest.mark.parametrize("status_label", ["Late", "Absent"])
    async def test_late_and_absent_deliberately_get_no_regularization_offer(self, monkeypatch, status_label):
        """See _ATTENDANCE_NEXT_ACTION_PROMPTS's comment: only "Half Day
        Absent" is regularizable, so plain "Late"/"Absent" must never get
        the regularization follow-up offer."""
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": status_label}])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why"), writer)

        assert "Attendance Regularization" not in result["response_text"]

    @pytest.mark.parametrize("status_label", ["Present", "Half Day"])
    async def test_non_adverse_statuses_get_no_next_best_action(self, monkeypatch, status_label):
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": status_label}])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why"), writer)

        assert "Regularization" not in result["response_text"]
        assert "check your attendance details" not in result["response_text"]


class TestAttendanceExplainNodePunchDetails:
    """AC1-AC3: shift timing and punch-time evidence, sourced from the real
    get_punch_time() endpoint and rendered as pure string formatting — no
    grace-period/variance is invented (AC5)."""

    async def test_shift_and_punches_enrich_the_card(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-06-02")
        mock_status(monkeypatch, [{"date": "2026-06-02", "day": "Tuesday", "status": "Present"}])
        mock_punch_details(monkeypatch, {
            "requested_date": "2026-06-02",
            "shift": {"id": 166, "name": "Testing Manual Shift", "start_time": "10:05:00", "end_time": "19:00:00"},
            "attendance": {"attendance": "P", "working_type": "1", "is_regularized": False},
            "punch_status": "complete", "punch_count": 1,
            "punches": [{"punch_number": 1, "check_in": "2026-06-02 15:54:20",
                         "check_out": "2026-06-02 15:54:23", "complete": True, "missing": None}],
            "work_hours": {"available": True, "value": "09:00", "source": "users_attendence", "reason": None},
        })

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked present on June 2nd"), writer)

        text = result["response_text"]
        assert "Testing Manual Shift" in text
        assert "10:05" in text and "19:00" in text
        assert "2026-06-02 15:54:20" in text
        assert "09:00" in text  # total work hours
        # Grace period/variance still explicitly acknowledged as unavailable, never invented.
        assert "grace-period" in text.lower()

        card = writer.of_type("attendance_explanation")[0]["data"]
        assert card["shift"]["start_time"] == "10:05"
        assert card["punches"][0]["check_in"] == "2026-06-02 15:54:20"
        assert card["work_hours"]["value"] == "09:00"
        assert "reason" in card
        assert "1 punch session" in card["reason"]

    async def test_no_punch_records_is_stated_explicitly(self, monkeypatch):
        """AC2: explicit indication when a required punch is missing, never
        silently omitted."""
        mock_date_extraction(monkeypatch, "2026-08-17")
        mock_status(monkeypatch, [{"date": "2026-08-17", "day": "Monday", "status": "Missing Punch"}])
        mock_punch_details(monkeypatch, {
            "requested_date": "2026-08-17",
            "shift": {"name": "Testing Manual Shift", "start_time": "10:05:00", "end_time": "19:00:00"},
            "attendance": None, "punch_status": "no_records", "punch_count": 0, "punches": [],
            "work_hours": {"available": False, "value": None, "source": "users_attendence", "reason": "No punch records found"},
        })

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why is my attendance showing missing punch"), writer)

        assert "none found for this date" in result["response_text"].lower()

    async def test_punch_details_unavailable_degrades_to_status_only(self, monkeypatch):
        """Punch-details is supporting evidence only — its failure must not
        block the status answer the user actually asked for."""
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": "Present"}])

        async def _timeout(token, **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(attendance_explain.erp_client, "get_punch_time", _timeout)

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked present"), writer)

        assert "Present" in result["response_text"]
        assert "2026-08-14" in result["response_text"]
        card = writer.of_type("attendance_explanation")[0]["data"]
        assert card == {
            "date": "2026-08-14", "day": "Friday", "status": "Present", "classification": None,
        }


class TestMessageSmugglesComputedReasoning:
    """The AC5 backstop: even though the LLM prompt forbids computed
    reasoning language, models don't follow instructions with 100%
    reliability — this scan is the actual enforcement mechanism."""

    @pytest.mark.parametrize("text", [
        "Marked Late — you exceeded the grace period by 10 minutes.",
        "Present, but your check-in was 15 minutes late by comparison to your shift start.",
        "Off, with a variance between your punch and your shift time.",
        "Half Day Absent, showing a deviation from your scheduled shift.",
        "You were marked absent because you checked in late.",
        "Present, you were early by 5 minutes.",
    ])
    def test_forbidden_language_detected(self, text):
        assert attendance_explain._message_smuggles_computed_reasoning(text) is True

    @pytest.mark.parametrize("text", [
        "Marked Present, with 1 punch session recorded for this date.",
        "Off, with 3 complete and 3 incomplete punch sessions recorded.",
        "Not Recorded — no punch records were found for this day.",
        "Regularized — this attendance record was manually adjusted.",
    ])
    def test_clean_facts_not_flagged(self, text):
        assert attendance_explain._message_smuggles_computed_reasoning(text) is False


class TestGenerateStatusReasonViaLLM:
    """Tests the real _generate_status_reason_via_llm implementation
    directly — must undo the module's autouse stub first, or every call
    here would just hit that stub instead."""

    async def test_successful_generation_returns_text_and_usage(self, monkeypatch):
        monkeypatch.undo()

        async def _fake_call_llm(prompt, max_tokens=None, model=None, **kwargs):
            return {"__text__": "Marked Off, with three punch sessions completed and three left incomplete."}

        def _fake_extract_text(response):
            return response["__text__"]

        monkeypatch.setattr(attendance_explain, "_call_llm", _fake_call_llm)
        monkeypatch.setattr(attendance_explain, "_extract_text", _fake_extract_text)

        text, usage = await attendance_explain._generate_status_reason_via_llm(
            "Off", "3 complete and 3 incomplete punch session(s) were recorded for this date.",
        )
        assert text == "Marked Off, with three punch sessions completed and three left incomplete."

    async def test_no_deterministic_reason_skips_the_llm_call_entirely(self, monkeypatch):
        """Nothing to rephrase — must not call the LLM at all, just return
        (None, None) immediately."""
        monkeypatch.undo()

        async def _should_not_be_called(*a, **kw):
            raise AssertionError("must not call the LLM when there's no deterministic reason")
        monkeypatch.setattr(attendance_explain, "_call_llm", _should_not_be_called)

        text, usage = await attendance_explain._generate_status_reason_via_llm("Present", None)
        assert text is None and usage is None

    async def test_forbidden_language_in_output_is_discarded(self, monkeypatch):
        monkeypatch.undo()

        async def _fake_call_llm(prompt, max_tokens=None, model=None, **kwargs):
            return {"__text__": "Marked Late because you exceeded the grace period."}

        def _fake_extract_text(response):
            return response["__text__"]

        monkeypatch.setattr(attendance_explain, "_call_llm", _fake_call_llm)
        monkeypatch.setattr(attendance_explain, "_extract_text", _fake_extract_text)

        text, usage = await attendance_explain._generate_status_reason_via_llm(
            "Late", "No punch records were found for this date.",
        )
        assert text is None
        assert usage is None

    async def test_empty_output_returns_none(self, monkeypatch):
        monkeypatch.undo()

        async def _fake_call_llm(prompt, max_tokens=None, model=None, **kwargs):
            return {"__text__": ""}

        monkeypatch.setattr(attendance_explain, "_call_llm", _fake_call_llm)
        monkeypatch.setattr(attendance_explain, "_extract_text", lambda r: r["__text__"])

        text, usage = await attendance_explain._generate_status_reason_via_llm(
            "Present", "1 punch session(s) were recorded for this date.",
        )
        assert text is None

    async def test_llm_call_failure_returns_none_not_raises(self, monkeypatch):
        monkeypatch.undo()

        async def _boom(*a, **kw):
            raise RuntimeError("provider down")
        monkeypatch.setattr(attendance_explain, "_call_llm", _boom)

        text, usage = await attendance_explain._generate_status_reason_via_llm(
            "Present", "1 punch session(s) were recorded for this date.",
        )
        assert text is None and usage is None


class TestAttendanceExplainNodeLLMReason:
    """Node-level integration: the LLM-rephrased text (mentioning BOTH
    status and the underlying fact) populates ONLY the "reason" field —
    "answer"/"message" (response_text) is always the deterministic card,
    regardless of whether the LLM reason path succeeded, failed, or was
    rejected."""

    async def test_clean_llm_reason_is_used_in_the_reason_field_only(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-06-03")
        mock_status(monkeypatch, [{"date": "2026-06-03", "day": "Wednesday", "status": "Present"}])
        mock_punch_details(monkeypatch, {
            "shift": {"name": "Day Shift"}, "attendance": {"is_regularized": False},
            "punch_status": "complete", "punches": [{"complete": True}],
            "work_hours": {"available": False},
        })
        mock_llm_reason(monkeypatch, "Marked Present, with one punch session recorded for this day.",
                         usage={"prompt_tokens": 30, "completion_tokens": 8, "total_tokens": 38})

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked present"), writer)

        card = writer.of_type("attendance_explanation")[0]["data"]
        assert card["reason"] == "Marked Present, with one punch session recorded for this day."
        # response_text (answer/message) must stay the deterministic card —
        # never the LLM-authored reason text.
        text = result["response_text"]
        assert "Marked Present, with one punch session recorded for this day." not in text
        assert "Your attendance for 2026-06-03 (Wednesday) was marked **Present**." in text
        sources = [ev["source"] for ev in result["usage_events"]]
        assert "attendance_reason_generation" in sources

    async def test_rejected_llm_reason_falls_back_to_deterministic_reason(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-14", "day": "Friday", "status": "Late"}])
        mock_punch_details(monkeypatch, {
            "shift": {"name": "Day Shift"}, "attendance": {"is_regularized": False},
            "punch_status": "complete", "punches": [{"complete": True}],
            "work_hours": {"available": False},
        })
        # Simulates _generate_status_reason_via_llm already having rejected
        # the output and returned None (its own internal contract).
        mock_llm_reason(monkeypatch, None)

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked late"), writer)

        card = writer.of_type("attendance_explanation")[0]["data"]
        assert card["reason"] == "1 punch session(s) were recorded for this date."
        text = result["response_text"]
        assert "Your attendance for 2026-08-14 (Friday) was marked **Late**." in text
        # "Late" deliberately never gets the regularization offer (see
        # _ATTENDANCE_NEXT_ACTION_PROMPTS's own comment) — only "Half Day
        # Absent" is regularizable. This test's real point is the LLM-
        # reason fallback above, unaffected by that.
        assert "Attendance Regularization" not in text


class TestAttendanceExplainNodeFallbacks:

    async def test_no_matching_record_for_date_says_nothing_was_recorded(self, monkeypatch):
        """AC7's spirit: the range query returns records for OTHER days but
        not the one asked about — must not guess. erp-api DID answer, so
        this is "no attendance on file for that day", NOT the generic
        "unavailable, try again" (which read as a transient system error)."""
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [{"date": "2026-08-13", "day": "Thursday", "status": "Present"}])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked late"), writer)

        assert "No attendance was recorded for you on" in result["response_text"]
        assert "2026-08-14" in result["response_text"]
        assert "currently unavailable" not in result["response_text"]
        assert writer.of_type("attendance_explanation") == []
        assert writer.of_type("done")[0]["data"]["status"] is None

    async def test_empty_records_says_nothing_was_recorded(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-08-14")
        mock_status(monkeypatch, [])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked late"), writer)

        assert "No attendance was recorded for you on" in result["response_text"]
        assert "currently unavailable" not in result["response_text"]

    async def test_unusable_erp_body_still_says_try_again(self, monkeypatch):
        """The ONE case that keeps the generic message: erp-api's response
        carries no data/records key at all — it did not actually answer."""
        mock_date_extraction(monkeypatch, "2026-08-14")

        async def _broken(token, from_date, to_date, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": {}}}
        monkeypatch.setattr(attendance_explain.erp_client, "get_attendance_status", _broken)

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked late"), writer)

        assert "currently unavailable" in result["response_text"]

    async def test_future_date_is_refused_before_any_erp_call(self, monkeypatch):
        """This route explains PAST + TODAY only. A future date is refused up
        front — no erp-api call — same as the manager attendance-explanation
        route."""
        import datetime
        future = (attendance_explain._today() + datetime.timedelta(days=3)).isoformat()
        mock_date_extraction(monkeypatch, future)

        called = []
        async def _must_not_run(*a, **k):
            called.append(True)
            raise AssertionError("erp-api was called for a future date")
        monkeypatch.setattr(attendance_explain.erp_client, "get_attendance_status", _must_not_run)

        # query carries no date phrase, so the mocked extraction date wins
        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(
            base_state("why was I marked absent"), writer)

        assert "hasn't happened yet" in result["response_text"]
        assert future in result["response_text"]
        assert writer.of_type("done")[0]["data"].get("is_future") is True
        assert not called
        assert writer.of_type("attendance_explanation") == []

    async def test_today_is_not_treated_as_future(self, monkeypatch):
        """Boundary: today must still be answered normally."""
        today = attendance_explain._today().isoformat()
        mock_date_extraction(monkeypatch, today)
        mock_status(monkeypatch, [{"date": today, "day": "Monday", "status": "Present"}])

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(
            base_state("why was I marked present today"), writer)

        assert "hasn't happened yet" not in result["response_text"]
        assert "marked **Present**" in result["response_text"]

    async def test_timeout_gives_clean_message_not_a_crash(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-08-14")

        async def _timeout(token, from_date, to_date, **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(attendance_explain.erp_client, "get_attendance_status", _timeout)

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked late"), writer)

        assert "try again" in result["response_text"].lower()
        assert writer.of_type("attendance_explanation") == []

    async def test_unavailable_gives_clean_message(self, monkeypatch):
        mock_date_extraction(monkeypatch, "2026-08-14")

        async def _down(token, from_date, to_date, **kwargs):
            raise ErpApiUnavailable("connection refused")
        monkeypatch.setattr(attendance_explain.erp_client, "get_attendance_status", _down)

        writer = FakeWriter()
        result = await attendance_explain.attendance_explain_node(base_state("why was I marked late"), writer)

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


# ═════════════════════════════════════════════════════════════════════════════
# Routing — classify_node → attendance_explain_node
# ═════════════════════════════════════════════════════════════════════════════

class TestAttendanceExplainRouting:

    def test_routes_to_attendance_explain_node(self):
        state = {"intent": "attendance_explain", "is_hr": True, "error": None}
        assert hr_graph._route_after_classify(state) == "attendance_explain_node"

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