"""
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.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):
        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 TestResolveRelativeDateDeterministically:
    """Weekday/today/yesterday 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). This function must never
    call an LLM and must be exactly right for these cases."""

    def test_today_and_yesterday(self):
        import datetime
        today = attendance_explain._today()
        assert attendance_explain._resolve_relative_date_deterministically("why late today") == today.isoformat()
        assert attendance_explain._resolve_relative_date_deterministically("attendance for yesterday") == \
            (today - datetime.timedelta(days=1)).isoformat()

    def test_bare_weekday_name_resolves_to_most_recent_occurrence(self):
        import datetime
        today = attendance_explain._today()
        for name, idx in attendance_explain._WEEKDAY_NAMES.items():
            expected = today - datetime.timedelta(days=(today.weekday() - idx) % 7)
            result = attendance_explain._resolve_relative_date_deterministically(f"why was I marked late on {name}")
            assert result == expected.isoformat(), f"{name}: expected {expected}, got {result}"

    def test_next_weekday_resolves_forward(self):
        import datetime
        today = attendance_explain._today()
        for name, idx in attendance_explain._WEEKDAY_NAMES.items():
            delta = (idx - today.weekday()) % 7 or 7
            expected = today + datetime.timedelta(days=delta)
            result = attendance_explain._resolve_relative_date_deterministically(f"attendance next {name}")
            assert result == expected.isoformat()

    def test_explicit_dates_and_ordinals_return_none(self):
        """Anything not deterministically resolvable must return None so
        the caller falls through to the LLM-based extraction — this
        function must never guess."""
        assert attendance_explain._resolve_relative_date_deterministically("why was I marked present on June 2nd 2026") is None
        assert attendance_explain._resolve_relative_date_deterministically("why was I marked that way") is None
        assert attendance_explain._resolve_relative_date_deterministically("attendance on the 10th") is None


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):
        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_unresolvable_date_defaults_to_today_not_a_clarifying_loop(self, monkeypatch):
        """Rather than stalling the conversation, an unresolvable day
        defaults to today so the flow always completes in one turn."""
        mock_date_extraction(monkeypatch, None)
        today = attendance_explain._today().isoformat()
        captured = {}
        mock_status(monkeypatch, [{"date": today, "day": "Monday", "status": "Present"}], capture=captured)

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

        assert captured["from_date"] == today


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:00" in text and "19:00: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:00"
        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):
            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):
            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):
            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_gives_controlled_fallback(self, monkeypatch):
        """AC7's spirit: the range query returns records for OTHER days but
        not the one asked about — must not guess, must fall back."""
        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 "currently unavailable" in result["response_text"]
        assert writer.of_type("attendance_explanation") == []

    async def test_empty_records_falls_back(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 "currently unavailable" 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
