"""
Tests for Team Attendance Summary (FR-07.2, Sprint 5):
  - services/erp_client.py::get_team_attendance_summary (LIVE — confirmed
    against GET /api/v1/ai/attendance/summary on erp-api14.studyineurope.xyz)
  - services/nlp_service.py's HRMS_TEAM_ATTENDANCE_QUERY fast-path
  - services/hr_graph.py::team_attendance_summary_node (role gate, date
    resolution, Summary Card rendering, zero-exception empty state)

team_attendance_summary_node is exercised directly with a fake StreamWriter
and a mocked erp_client, the same pattern as TestTeamLeaveQueryNode in
test_leave_action.py — this node is FR-07.2's direct sibling of FR-07.1's
team_leave_query_node (same manager-only inverted role-gate polarity, same
"full body over the wire, text is the accessible fallback" event pattern).

The response shape asserted throughout (access via summary_cards.<key>.value,
missing_punch_details.employees, etc.) is the CONFIRMED LIVE contract, not a
guess — see erp_client.get_team_attendance_summary's own docstring.
"""

from datetime import date, timedelta

import pytest
from unittest.mock import MagicMock

import services.hr_graph as hr_graph
import services.nlp_service as nlp_service
import services.erp_client as erp_client
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, has_date_expression: bool = False) -> dict:
    return {
        "query": query, "intent": "HRMS_TEAM_ATTENDANCE_QUERY", "usage_events": [],
        "bearer_token": "caller-token", "company_id": 1, "conversation_id": "conv-1",
        "has_date_expression": has_date_expression,
    }


def manager_context():
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": True}}}
    return _f


def not_manager_context():
    async def _f(token, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": {"is_manager": False}}}
    return _f


def summary_body(
    *, date_str="2026-08-31", scope="direct_reports", total_team=5, present=3,
    absent=1, on_leave=1, missing_punches=1, missed_punch_count=1,
    employees=None, not_recorded=0,
):
    """Builds a response shaped exactly like the confirmed-live erp-api
    payload (see the story's own example + the missing-punch-employee
    fixture below, both captured from real GET /api/v1/ai/attendance/summary
    calls)."""
    return {
        "type": "team_attendance_summary",
        "date": date_str,
        "scope": scope,
        "summary_cards": {
            "total_team": {"label": "Total Team", "value": total_team},
            "present": {"label": "Present", "value": present},
            "absent": {"label": "Absent", "value": absent},
            "on_leave": {"label": "On Leave", "value": on_leave},
            "missing_punches": {"label": "Missing Punches", "value": missing_punches,
                                 "missed_punch_count": missed_punch_count},
        },
        "breakdown": {
            "attendance_recorded": present + absent, "not_recorded": not_recorded, "off": 0,
        },
        "missing_punch_details": {
            "employee_count": len(employees or []),
            "incomplete_session_count": len(employees or []),
            "missing_check_ins": 0,
            "missing_check_outs": missed_punch_count,
            "missed_punch_count": missed_punch_count,
            "employees": employees or [],
        },
    }


# ═════════════════════════════════════════════════════════════════════════════
# nlp_service.fast_classify — HRMS_TEAM_ATTENDANCE_QUERY keyword/regex layer
# ═════════════════════════════════════════════════════════════════════════════

class TestFastClassifyTeamAttendanceQuery:

    @pytest.mark.parametrize("query", [
        "How many employees are absent today?",
        "Who was absent yesterday?",
        "Show missing punches for Monday.",
        "Who is absent?",
        "Show employees with missing punches.",
        "Give me my team's attendance summary",
        "team attendance summary",
    ])
    def test_recognizes_team_attendance_queries(self, query):
        intent, is_hr, confidence = nlp_service.fast_classify(query)
        assert intent == "HRMS_TEAM_ATTENDANCE_QUERY"
        assert is_hr is True
        assert confidence >= 0.5

    def test_does_not_shadow_individual_attendance_explanation(self):
        # AC scope boundary — an individual explanation must still route to
        # manager_attendance_explanation, not the team-aggregate intent.
        # (fast_classify's keyword layer only recognizes pronoun phrasing —
        # a NAMED person like "John" needs the full LLM classifier, which is
        # a separate disambiguation covered in hr_graph.py's prompt, not here.)
        intent, _, _ = nlp_service.fast_classify("Why was he marked half-day?")
        assert intent == "manager_attendance_explanation"

    def test_does_not_shadow_team_leave_query(self):
        intent, _, _ = nlp_service.fast_classify("Show pending leave requests for my team")
        assert intent == "HRMS_TEAM_LEAVE_QUERY"

    def test_generic_attendance_policy_question_is_unaffected(self):
        intent, _, _ = nlp_service.fast_classify("What is the work from home policy")
        assert intent == "attendance"


# ═════════════════════════════════════════════════════════════════════════════
# erp_client.get_team_attendance_summary — LIVE endpoint contract
# ═════════════════════════════════════════════════════════════════════════════

class TestErpClientTeamAttendanceSummary:

    async def test_forwards_token_url_and_date_param(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": summary_body()}
            return resp

        from unittest.mock import patch
        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_team_attendance_summary(
                "caller-token-abc", date="2026-08-25",
            )

        assert captured["method"] == "GET"
        assert captured["url"] == "http://erp.test/api/v1/ai/attendance/summary"
        assert captured["headers"]["Authorization"] == "Bearer caller-token-abc"
        assert captured["params"] == {"date": "2026-08-25"}
        assert result["body"]["data"]["scope"] == "direct_reports"

    async def test_no_date_sends_no_params_and_erp_api_defaults_to_today(self):
        """Confirmed live: omitting `date` makes erp-api default to today in
        its own server timezone — this layer must not invent a default
        itself (that's team_attendance_summary_node's job, in the app's own
        configured timezone, not erp-api's)."""
        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": summary_body()}
            return resp

        from unittest.mock import patch
        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_team_attendance_summary("tok")

        assert captured["params"] is None


# ═════════════════════════════════════════════════════════════════════════════
# team_attendance_summary_node
# ═════════════════════════════════════════════════════════════════════════════

class TestTeamAttendanceSummaryNode:

    # -- AC1 / AC6: Summary Card for today, structured event + metrics -----

    async def test_manager_sees_summary_card_for_today_by_default(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        captured = {}

        async def _summary(token, **kwargs):
            captured.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": summary_body()}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        events = writer.of_type("team_attendance_summary")
        assert len(events) == 1
        card = events[0]["data"]
        assert card["summary_cards"]["total_team"]["value"] == 5
        assert card["summary_cards"]["present"]["value"] == 3
        assert card["summary_cards"]["absent"]["value"] == 1
        assert card["summary_cards"]["on_leave"]["value"] == 1
        assert card["summary_cards"]["missing_punches"]["value"] == 1

        assert "Total Team: 5" in result["response_text"]
        assert "Present: 3" in result["response_text"]
        assert "Absent: 1" in result["response_text"]
        assert "On Leave: 1" in result["response_text"]
        assert "Missing Punches: 1" in result["response_text"]

        done = writer.of_type("done")
        assert done[0]["intent"] == "HRMS_TEAM_ATTENDANCE_QUERY"

        # No date named in the query -> defaults to today (AC#4), passed
        # through to erp_client as an explicit date, not left implicit.
        assert captured.get("date") == hr_graph._today_in_app_timezone().isoformat()

    async def test_response_is_never_an_unformatted_wall_of_text(self, monkeypatch):
        """AC#6 — the structured `team_attendance_summary` event (the
        Summary Card's actual data source) must always be emitted alongside
        any non-empty-state text reply."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body()}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(base_state("team attendance summary"), writer)

        assert len(writer.of_type("team_attendance_summary")) == 1

    # -- AC5: standard employee cannot access team view ---------------------

    async def test_non_manager_is_blocked_before_summary_call(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())
        summary_mock = MagicMock(side_effect=AssertionError("should never be called for a non-manager"))
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", summary_mock)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        summary_mock.assert_not_called()
        assert writer.of_type("team_attendance_summary") == []
        done = writer.of_type("done")
        assert done[0]["intent"] == "team_attendance_restricted"
        assert "manager" in result["response_text"].lower()

    async def test_403_from_summary_call_is_handled_gracefully(self, monkeypatch):
        """A role change between the get_leave_context check and this call
        (or any other disagreement with erp-api's own authoritative gate)
        must not crash the turn — mirrors team_leave_query_node's own
        403-fallback test."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 403, "body": {"success": False, "message": "Forbidden"}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        assert writer.of_type("done")[0]["intent"] == "team_attendance_restricted"
        assert "manager" in result["response_text"].lower()

    # -- Transport failures --------------------------------------------------

    async def test_context_timeout_gives_clean_message_not_a_crash(self, monkeypatch):
        async def _timeout(token, **kwargs):
            raise ErpApiTimeout("timed out")
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", _timeout)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

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

    async def test_summary_call_unavailable_gives_clean_message_not_a_crash(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _unavailable(token, **kwargs):
            raise ErpApiUnavailable("connection refused")
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _unavailable)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        assert "unable to reach" in result["response_text"].lower()
        assert writer.of_type("team_attendance_summary") == []

    # -- AC2: specific/explicit date query -----------------------------------

    async def test_explicit_date_is_resolved_and_forwarded(self, monkeypatch):
        """'Who was absent on August 10' — an explicit absolute date the
        deterministic layer doesn't recognize (see _resolve_team_attendance_
        date's own docstring) falls through to _resolve_date_range's LLM
        tier; mocked here to isolate the node's OWN wiring from the LLM."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _fake_resolve_date_range(query, today, purpose_hint=None):
            return ("2026-08-10", "2026-08-10")
        monkeypatch.setattr(hr_graph, "_resolve_date_range", _fake_resolve_date_range)

        captured = {}

        async def _summary(token, **kwargs):
            captured.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": summary_body(date_str="2026-08-10")}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("Who was absent on August 10", has_date_expression=True), writer,
        )

        assert captured.get("date") == "2026-08-10"
        assert "2026-08-10" in result["response_text"]

    # -- AC3: relative date resolution ("yesterday") -------------------------

    async def test_yesterday_resolves_deterministically_to_the_prior_day(self, monkeypatch):
        """Deterministic, zero-LLM-cost path (date_resolver.resolve_relative_
        date_phrase with allow_past=True) — must not fall through to the LLM
        tier at all for an unambiguous phrase like this."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        def _fail_if_called(*args, **kwargs):
            raise AssertionError("LLM date-range fallback should never be called for 'yesterday'")
        monkeypatch.setattr(hr_graph, "_resolve_date_range", _fail_if_called)

        captured = {}

        async def _summary(token, **kwargs):
            captured.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": summary_body()}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state("Who was absent yesterday?", has_date_expression=True), writer,
        )

        expected = (hr_graph._today_in_app_timezone() - timedelta(days=1)).isoformat()
        assert captured.get("date") == expected

    @pytest.mark.parametrize("query,weekday", [
        ("Show missing punches for Monday.", 0),
        ("Who was absent on Tuesday?", 1),
        ("Show team attendance for Wednesday.", 2),
        ("Show attendance exceptions for Friday.", 4),
    ])
    async def test_a_bare_weekday_resolves_backwards_not_to_today(
            self, monkeypatch, query, weekday):
        """AC#3's other named example. A bare weekday used to resolve to
        TODAY: date_resolver.mentions_date_expression didn't match weekday
        names, so has_date_expression was False and this node skipped date
        resolution entirely - a plausible-looking summary for the wrong day.
        Attendance is read-only and past-tolerant, so "for Monday" means the
        Monday that has already passed."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        def _fail_if_called(*args, **kwargs):
            raise AssertionError("a bare weekday must resolve deterministically, not via the LLM")
        monkeypatch.setattr(hr_graph, "_resolve_date_range", _fail_if_called)

        captured = {}

        async def _summary(token, **kwargs):
            captured.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": summary_body()}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        # classify_node computes the flag from the query - mirror that here
        # rather than hard-coding True, so this also pins the pre-check.
        import services.date_resolver as date_resolver
        assert date_resolver.mentions_date_expression(query) is True

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state(query, has_date_expression=True), writer,
        )

        today = hr_graph._today_in_app_timezone()
        expected = today - timedelta(days=(today.weekday() - weekday) % 7)
        assert captured.get("date") == expected.isoformat()
        assert captured.get("date") != today.isoformat() or today.weekday() == weekday

    async def test_last_weekday_resolves_to_the_previous_calendar_week(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        captured = {}

        async def _summary(token, **kwargs):
            captured.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": summary_body()}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state("How many employees were present last Monday?", has_date_expression=True),
            writer,
        )

        today = hr_graph._today_in_app_timezone()
        start_of_week = today - timedelta(days=today.weekday())
        assert captured.get("date") == (start_of_week - timedelta(days=7)).isoformat()

    async def test_no_date_expression_flag_skips_only_the_llm_tier(self, monkeypatch):
        """has_date_expression=False used to skip ALL date resolution, and that
        is how a query whose date reference the pre-check did not recognise
        got answered for today. The deterministic tier is a few regexes and
        now always runs; the flag (or the query itself) only gates the LLM
        call. For a query with no date reference at all, that LLM call must
        still never be made and the date must still default to today."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        def _fail_if_called(*args, **kwargs):
            raise AssertionError("LLM date-range fallback must not run for a query with no date")
        monkeypatch.setattr(hr_graph, "_resolve_date_range", _fail_if_called)

        captured = {}
        async def _summary(token, **kwargs):
            captured.update(kwargs)
            return {"http_status": 200, "body": {"success": True, "data": summary_body()}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent?", has_date_expression=False), writer,
        )
        assert captured.get("date") == hr_graph._today_in_app_timezone().isoformat()
    # -- AC5: missing-punch employee list ------------------------------------

    async def test_missing_punch_employee_list_is_rendered(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        employees = [
            {"employee_id": 3735, "employee_number": "geo3", "employee_name": "B Geo",
             "attendance_status": "missing punch"},
            {"employee_id": 3736, "employee_number": "geo4", "employee_name": "C Geo",
             "attendance_status": "missing punch"},
        ]

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                absent=0, missing_punches=2, missed_punch_count=2, employees=employees,
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("Show employees with missing punches."), writer,
        )

        events = writer.of_type("team_attendance_summary")
        assert events[0]["data"]["missing_punch_details"]["employees"] == employees
        assert "B Geo" in result["response_text"]
        assert "C Geo" in result["response_text"]
        assert "Impacted employees:" in result["response_text"]

    async def test_no_impacted_employee_list_rendered_when_none_exist(self, monkeypatch):
        """AC#6/AC#8 — 'No impacted-employee list shall be displayed when
        there are no impacted employees', even outside the perfect-
        attendance branch (e.g. on_leave > 0 but nobody has a missing punch)."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                present=3, absent=1, on_leave=1, missing_punches=0, missed_punch_count=0, employees=[],
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        assert "Impacted employees:" not in result["response_text"]

    # -- AC7: reporting hierarchy scope is erp-api's, passed through --------

    async def test_scope_field_is_passed_through_from_erp_api_unmodified(self, monkeypatch):
        """Direct/indirect-report scoping (AC#7) is enforced server-side by
        erp-api (the `scope` field, e.g. "direct_reports") — this node
        neither computes nor filters that itself, only surfaces what erp-api
        already scoped, same division of responsibility as
        team_leave_query_node's own hierarchy handling."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(scope="direct_reports")}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        events = writer.of_type("team_attendance_summary")
        assert events[0]["data"]["scope"] == "direct_reports"

    # -- AC8: perfect attendance / zero exception state ----------------------

    async def test_perfect_attendance_returns_exact_empty_state_message(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                total_team=5, present=5, absent=0, on_leave=0, missing_punches=0,
                missed_punch_count=0, employees=[],
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        # AC#8 — exact required copy, verbatim; only [X] is substituted.
        assert result["response_text"] == "All 5 members of your team are present today with no missing punches!"
        assert "Impacted employees:" not in result["response_text"]
        # The Summary Card itself is still emitted (metrics must still show,
        # per AC#8) — only the text reply is the special empty-state copy.
        events = writer.of_type("team_attendance_summary")
        assert len(events) == 1
        assert events[0]["data"]["summary_cards"]["absent"]["value"] == 0
        assert events[0]["data"]["summary_cards"]["missing_punches"]["value"] == 0

    async def test_perfect_attendance_message_uses_actual_team_count(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                total_team=12, present=12, absent=0, on_leave=0, missing_punches=0, employees=[],
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("Who is absent?"), writer,
        )

        assert result["response_text"] == "All 12 members of your team are present today with no missing punches!"


# ═════════════════════════════════════════════════════════════════════════════
# Regression: the day nothing has been punched yet, and the missing-punch view
#
# Live bug (2026-09-07, conversation a52f4bd1): "show employee with missing
# punch in" answered "All 5 members of your team are present today with no
# missing punches!" for a team whose payload said present 0, attendance_
# recorded 0, not_recorded 5 — nobody had been recorded at all, and the
# question was about punches, not presence. Both halves are covered here.
# ═════════════════════════════════════════════════════════════════════════════

LIVE_NOT_RECORDED_KWARGS = dict(
    total_team=5, present=0, absent=0, on_leave=0, missing_punches=0,
    missed_punch_count=0, employees=[], not_recorded=5,
)

SAMEER = {
    "employee_id": 4101, "employee_number": "sn01", "employee_name": "Sameer Nair",
    "attendance_status": "missing punch", "relation": "indirect",
    "reporting_manager": "Team Lead, Rohit S.",
    "check_in": "2026-08-31 09:14:00", "check_out": None,
}


class TestPunchRowRendering:
    """The two display strings the missing-punch card needs, built ONLY from
    fields erp-api actually sent."""

    @pytest.mark.parametrize("stamp,expected", [
        ("2026-08-31 09:14:00", "09:14 AM"),
        ("09:14:00", "09:14 AM"),
        ("2026-08-31 13:05:00", "01:05 PM"),
        ("2026-08-31 00:30:00", "12:30 AM"),
        ("2026-08-31 12:00:00", "12:00 PM"),
        (None, None),
    ])
    def test_punch_clock_12h(self, stamp, expected):
        assert hr_graph._punch_clock_12h(stamp) == expected

    def test_unparseable_stamp_is_passed_through_untouched(self):
        assert hr_graph._punch_clock_12h("not a clock") == "not a clock"

    def test_relation_and_punch_detail_are_rendered_from_erp_api_fields(self):
        row = hr_graph._missing_punch_rows([SAMEER])[0]
        assert row["relation_label"] == "Indirect report · via Team Lead, Rohit S."
        assert row["punch_detail"] == "Check-in 09:14 AM · no check-out"
        # The original fields survive untouched for the client.
        assert row["employee_id"] == 4101

    def test_no_relation_label_is_invented_when_erp_api_sent_none(self):
        """The live summary endpoint's employee rows carry no relation field
        — the row must render without one rather than asserting a place in
        the org chart the payload never stated."""
        row = hr_graph._missing_punch_rows([
            {"employee_id": 3735, "employee_name": "B Geo", "attendance_status": "missing punch"},
        ])[0]
        assert "relation_label" not in row
        assert row["punch_detail"] == "missing punch"

    def test_which_punch_is_missing_is_its_own_field(self):
        """"Punch Type Missing" is what the question asks for — reading it
        out of a timestamp string is the reader's work, not theirs."""
        assert hr_graph._missing_punch_rows([SAMEER])[0]["missing_punch_type"] == "Out-punch missing"

        checked_out_only = {**SAMEER, "check_in": None, "check_out": "2026-08-31 18:02:00"}
        assert hr_graph._missing_punch_rows(
            [checked_out_only])[0]["missing_punch_type"] == "In-punch missing"

    @pytest.mark.parametrize("stamps", [
        {"check_in": None, "check_out": None},
        {"check_in": "2026-08-31 09:14:00", "check_out": "2026-08-31 18:02:00"},
    ])
    def test_no_punch_type_is_asserted_without_evidence_for_one(self, stamps):
        """Neither stamp cannot distinguish an in-punch from an out-punch,
        and both stamps name no missing punch at all. Either way the payload
        never established a type, so none is claimed - the row falls back to
        erp-api's own status text."""
        row = hr_graph._missing_punch_rows([{**SAMEER, **stamps}])[0]
        assert "missing_punch_type" not in row


class TestAC7HierarchyScope:
    """AC#7 / QA TC4 - employees outside the manager's hierarchy never appear.

    erp-api resolves the hierarchy and is the only thing that CAN: it owns the
    org chart, and its `scope` field is its statement of what it applied.
    What this service must guarantee is the other half - that it never widens
    that answer. These tests pin exactly that: the rendered rows are erp-api's
    rows, nothing is merged in from a second source, and no roster fallback
    exists on this path.

    The end-to-end audit (returned employee IDs vs the backend org chart) needs
    a live manager token and erp-api itself - see
    tests/verify_attendance_hierarchy_scope.py.
    """

    async def test_only_the_employees_erp_api_returned_are_rendered(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                present=3, absent=0, on_leave=0, missing_punches=1,
                missed_punch_count=1, employees=[SAMEER],
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("Show employees with missing punches"), writer)

        rows = writer.of_type("team_attendance_summary")[0]["data"]["missing_punch_view"]["employees"]
        assert [r["employee_id"] for r in rows] == [SAMEER["employee_id"]]
        assert result["response_text"].count("- ") == 1

    async def test_no_second_erp_call_can_widen_the_employee_list(self, monkeypatch):
        """The leave-approval path narrows a returned ROSTER when erp-api
        cannot match a name (_resolve_from_roster). No such fallback exists
        here, and none may be added: on this path a roster lookup would be a
        second, differently-scoped source of employees feeding a list that is
        supposed to be erp-api's hierarchy answer verbatim."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                present=4, absent=0, on_leave=0, missing_punches=1,
                missed_punch_count=1, employees=[SAMEER],
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        async def _must_not_run(*a, **k):
            raise AssertionError("a second employee source was consulted on the "
                                 "team-attendance path - it can only widen scope")
        monkeypatch.setattr(hr_graph.erp_client, "get_team_pending_leaves", _must_not_run)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state("Show employees with missing punches"), writer)

        rows = writer.of_type("team_attendance_summary")[0]["data"]["missing_punch_view"]["employees"]
        assert len(rows) == 1

    async def test_erp_apis_own_scope_is_passed_through_untouched(self, monkeypatch):
        """The card carries erp-api's `scope` verbatim, so an auditor reading
        the payload can see WHICH hierarchy produced the rows rather than
        having to infer it."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                scope="direct_and_indirect_reports", employees=[SAMEER])}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state("Show employees with missing punches"), writer)

        assert writer.of_type("team_attendance_summary")[0]["data"]["scope"] == \
            "direct_and_indirect_reports"

    async def test_a_403_shows_no_employees_at_all(self, monkeypatch):
        """erp-api disagreeing with the role gate must empty the answer, not
        fall back to anything."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 403, "body": {"success": False, "data": {}}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("Show employees with missing punches"), writer)

        assert not writer.of_type("team_attendance_summary")
        assert "Sameer" not in result["response_text"]


class TestNotRecordedDayAndMissingPunchView:

    async def test_unrecorded_day_is_not_reported_as_perfect_attendance(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True,
                                                  "data": summary_body(**LIVE_NOT_RECORDED_KWARGS)}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        text = result["response_text"]
        assert "All 5 members of your team are present" not in text
        assert "hasn't been recorded yet for 5 of 5" in text
        assert "- Present: 0" in text

    async def test_missing_punch_query_answers_about_punches_not_presence(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True,
                                                  "data": summary_body(**LIVE_NOT_RECORDED_KWARGS)}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("show employee with missing punch in"), writer,
        )

        text = result["response_text"]
        assert text.startswith("No missing punches for your team")
        assert "present" not in text.lower()
        assert "hasn't been recorded yet for 5 of 5" in text

    async def test_missing_punch_query_leads_with_the_missing_punch_view(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                date_str=hr_graph._today_in_app_timezone().isoformat(),
                present=4, absent=0, on_leave=0, missing_punches=1,
                missed_punch_count=1, employees=[SAMEER],
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("Show employees with missing punches"), writer,
        )

        card = writer.of_type("team_attendance_summary")[0]["data"]
        assert card["view"] == "missing_punches"
        view = card["missing_punch_view"]
        assert view["title"] == "Missing Punches — Today"
        assert view["employee_count"] == 1
        assert view["employees"][0]["relation_label"] == "Indirect report · via Team Lead, Rohit S."
        assert view["employees"][0]["punch_detail"] == "Check-in 09:14 AM · no check-out"
        assert view["footnote"]
        # erp-api's own body still goes over the wire alongside the view.
        assert card["summary_cards"]["missing_punches"]["value"] == 1
        assert card["scope"] == "direct_reports"

        text = result["response_text"]
        assert text.startswith("Missing Punches — Today (1 employee)")
        assert "Sameer Nair" in text
        assert "Check-in 09:14 AM · no check-out" in text
        # QA TC2 — "Punch Type Missing" is named outright, in the text and
        # on the structured row, not left to be inferred from the stamps.
        assert "Out-punch missing" in text
        assert view["employees"][0]["missing_punch_type"] == "Out-punch missing"

    async def test_a_general_team_question_keeps_the_summary_view(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body()}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        card = writer.of_type("team_attendance_summary")[0]["data"]
        assert card["view"] == "team_attendance_summary"
        assert "missing_punch_view" not in card

    async def test_missing_punch_count_without_an_employee_list_renders_no_list(self, monkeypatch):
        """AC#6/AC#8 — erp-api can report a non-zero counter while naming no
        employees; the header still states the count, but no list is invented."""
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())

        async def _summary(token, **kwargs):
            return {"http_status": 200, "body": {"success": True, "data": summary_body(
                present=4, absent=0, on_leave=0, missing_punches=2,
                missed_punch_count=2, employees=[],
            )}}
        monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("Show employees with missing punches"), writer,
        )

        assert "(2 employees)" in result["response_text"]
        assert "Impacted employees:" not in result["response_text"]

    async def test_non_manager_message_points_at_own_attendance(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", not_manager_context())

        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state("How many employees are absent today?"), writer,
        )

        text = result["response_text"]
        assert "direct or indirect reports" in text
        assert "your own" in text
        assert writer.of_type("done")[0]["intent"] == "team_attendance_restricted"


class TestMissingPunchQueryDetection:
    """Only a question that NAMES missing punches gets the focused view — the
    generic team question must still get the five-metric board."""

    @pytest.mark.parametrize("query", [
        "show employee with missing punch in",
        "Show employees with missing punches.",
        "Show missing punches for Monday.",
        "who missed a punch today",
        "anyone with incomplete punches?",
        "who forgot to punch out",
        "employees with no check-out",
    ])
    def test_focused_queries_are_recognized(self, query):
        assert hr_graph._MISSING_PUNCH_QUERY_RE.search(query)

    @pytest.mark.parametrize("query", [
        "How many employees are absent today?",
        "Who was absent yesterday?",
        "team attendance summary",
        "Give me my team's attendance summary",
    ])
    def test_general_queries_are_not_treated_as_missing_punch_queries(self, query):
        assert not hr_graph._MISSING_PUNCH_QUERY_RE.search(query)


# ═════════════════════════════════════════════════════════════════════════════
# AC#2-4 — the date in the question is the date that is fetched AND shown
# ═════════════════════════════════════════════════════════════════════════════

# Fixed "today" so every expectation below is a literal calendar date, not a
# computation that mirrors the code under test. Thursday 17 September 2026.
TODAY = date(2026, 9, 17)


def _fixed_today(monkeypatch):
    monkeypatch.setattr(hr_graph, "_today_in_app_timezone", lambda: TODAY)


def _llm_tier_must_not_run(monkeypatch):
    def _fail(*args, **kwargs):
        raise AssertionError("_resolve_date_range (LLM tier) must not be consulted for this query")
    monkeypatch.setattr(hr_graph, "_resolve_date_range", _fail)


def _erp_echoing_the_requested_date(monkeypatch, captured, echo=None):
    """erp-api serves the date it is asked for and echoes it back; `echo`
    forces a different echoed date to test what the header then follows."""
    async def _summary(token, **kwargs):
        captured.update(kwargs)
        return {"http_status": 200, "body": {"success": True,
                                             "data": summary_body(date_str=echo or kwargs.get("date"))}}
    monkeypatch.setattr(hr_graph.erp_client, "get_team_attendance_summary", _summary)


class TestDateResolutionDrivesTheFetchAndTheHeader:
    """Live (2026-09-16): "Who was absent in my team on 20 August 2026?"
    answered about the current day, card headed "Team Attendance - Today,
    16 Sept 2026". The deterministic resolver had no explicit-calendar-date
    step, so the only thing standing between that question and today was one
    LLM call that fails open to None."""

    @pytest.fixture(autouse=True)
    def _manager_with_fixed_clock(self, monkeypatch):
        monkeypatch.setattr(hr_graph.erp_client, "get_leave_context", manager_context())
        _fixed_today(monkeypatch)
        _llm_tier_must_not_run(monkeypatch)

    async def _run(self, monkeypatch, query, has_date_expression=True, echo=None):
        captured = {}
        _erp_echoing_the_requested_date(monkeypatch, captured, echo=echo)
        writer = FakeWriter()
        result = await hr_graph.team_attendance_summary_node(
            base_state(query, has_date_expression=has_date_expression), writer)
        events = writer.of_type("team_attendance_summary")
        assert len(events) == 1, "exactly one Summary Card event"
        return captured, events[0]["data"], result["response_text"]

    # -- AC#2: explicit date ---------------------------------------------------

    async def test_explicit_date_with_year_is_fetched_and_shown(self, monkeypatch):
        captured, card, text = await self._run(
            monkeypatch, "Who was absent in my team on 20 August 2026?")
        assert captured["date"] == "2026-08-20"
        assert card["date"] == "2026-08-20"
        assert "for 2026-08-20" in text
        assert "2026-09-17" not in text

    @pytest.mark.parametrize("query,expected", [
        ("who was absent in my team on 20 August", "2026-08-20"),   # this year: already passed
        ("show team attendance for 5 October", "2025-10-05"),      # not yet this year -> last year
        ("who was absent on 20th Aug", "2026-08-20"),
        ("team attendance on Aug 20, 2026", "2026-08-20"),
    ])
    async def test_explicit_date_without_year_is_the_most_recent_occurrence(
            self, monkeypatch, query, expected):
        """Attendance is read-only and past-tolerant: an unqualified month/day
        means the most recent one that has happened, never a future date an
        attendance record cannot exist for."""
        captured, card, _ = await self._run(monkeypatch, query)
        assert captured["date"] == expected
        assert card["date"] == expected

    async def test_numeric_date_is_read_day_first(self, monkeypatch):
        captured, _, _ = await self._run(monkeypatch, "who was absent in my team on 20/08/2026")
        assert captured["date"] == "2026-08-20"

    # -- AC#3: relative expressions -------------------------------------------

    async def test_yesterday_resolves_to_the_prior_calendar_day(self, monkeypatch):
        captured, card, text = await self._run(monkeypatch, "who was absent in my team yesterday")
        assert captured["date"] == "2026-09-16"
        assert card["date"] == "2026-09-16"
        assert "for 2026-09-16" in text

    async def test_bare_weekday_resolves_to_the_most_recent_one(self, monkeypatch):
        # Thursday 17 Sept -> the Monday that has passed is 14 Sept, not next week.
        captured, card, _ = await self._run(monkeypatch, "who was absent in my team on Monday")
        assert captured["date"] == "2026-09-14"
        assert card["date"] == "2026-09-14"

    # -- AC#4: no date reference at all ---------------------------------------

    async def test_no_date_reference_means_today_and_the_header_says_so(self, monkeypatch):
        captured, card, text = await self._run(
            monkeypatch, "who was absent in my team", has_date_expression=False)
        assert captured["date"] == "2026-09-17"
        assert card["date"] == "2026-09-17"
        assert "for 2026-09-17" in text

    # -- the two ways the date used to get dropped ----------------------------

    async def test_a_stale_has_date_expression_flag_cannot_drop_an_explicit_date(self, monkeypatch):
        """The deterministic tier is not gated on the flag any more: the query
        names a date, so the date wins even when has_date_expression is False."""
        captured, card, _ = await self._run(
            monkeypatch, "Who was absent in my team on 20 August 2026?", has_date_expression=False)
        assert captured["date"] == "2026-08-20"
        assert card["date"] == "2026-08-20"

    async def test_header_follows_the_queried_date_not_the_echoed_one(self, monkeypatch):
        """If erp-api ever echoes a different date than it was asked for, the
        card is still labelled with the date the manager asked about (and the
        disagreement is logged), instead of being silently relabelled 'Today'."""
        captured, card, text = await self._run(
            monkeypatch, "Who was absent in my team on 20 August 2026?", echo="2026-09-17")
        assert captured["date"] == "2026-08-20"
        assert card["date"] == "2026-08-20"
        assert "for 2026-08-20" in text
        assert "2026-09-17" not in text


class TestResolveTeamAttendanceDateUnit:
    """The resolver on its own, all tiers, fixed clock."""

    @pytest.mark.parametrize("query,expected", [
        ("Who was absent in my team on 20 August 2026?", "2026-08-20"),
        ("who was absent on 20 August", "2026-08-20"),
        ("who was absent on 20/08/2026", "2026-08-20"),
        ("who was absent yesterday", "2026-09-16"),
        ("who was absent on Monday", "2026-09-14"),
        ("who was absent last Monday", "2026-09-07"),
        ("who was absent today", "2026-09-17"),
    ])
    def test_resolves(self, query, expected):
        assert hr_graph._resolve_team_attendance_date(query, TODAY) == expected

    def test_no_date_reference_resolves_to_nothing(self):
        """None, not today: the NODE applies the today default, so a query
        with no date must be distinguishable from one that named today."""
        assert hr_graph._resolve_team_attendance_date("who was absent in my team", TODAY) is None
