"""The two halves of one reported bug, from a screenshot of the live flow:

    user: apply regularization
    bot:  Sure - which date(s) would you like to regularize?
    user: 9 sept
    bot:  <a SHIFT card for Wednesday, 09 Sep 2026>

The reply to the assistant's own question was classified as a fresh question
about that date. Two things were wrong at once:

  1. classify_node's mid-flow regularisation block knew only two states -
     "an entry is missing a field" and "an entry is complete, awaiting
     confirmation". "apply regularization" with no date produces neither: it
     stores {"entries": []} and asks for the date. That fell to the COMPLETE
     branch, whose continuation test is a confirm/cancel regex a bare date
     never matches, and whose LLM hint says in as many words "do NOT
     classify this as regularisation".

  2. Because the turn never reached regularisation_eligibility_node, nothing
     checked whether the day was regularizable at all. And even when it did
     run, a day erp-api answered for with NO attendance record read as "I
     couldn't check" and failed open - so a date with nothing to correct was
     answered "Good news - that day is eligible".

The first is a routing test, the second an eligibility one; they are in one
module because they are one user-visible bug.
"""

import pytest

import services.classify_node as classify_node
import services.regularisation_node as regularisation_node


# =============================================================================
# 1. The reply to "which date(s)?" continues the flow
# =============================================================================

class TestTheDateReplyContinuesTheFlow:

    #: What slot_flow saves when "apply regularization" names no date (see
    #: its "Sure - which date(s) would you like to regularize?" branch).
    AWAITING_FIRST_DATE = {"entries": [], "employee_name": None}

    @pytest.fixture(autouse=True)
    def _pending_flow(self, monkeypatch):
        monkeypatch.setattr(classify_node.slot_store, "get_slots",
                            lambda ns, c, v: self.AWAITING_FIRST_DATE
                            if ns == "regularization" else None)

    @pytest.fixture(autouse=True)
    def _no_llm(self, monkeypatch):
        """Every assertion here is about a DETERMINISTIC decision, so the
        LLM tiers are stubbed out rather than called: a routing fix that
        only works when an LLM happens to agree is not a fix."""
        async def _no_shift_verdict(query):
            return None, 0.0, None

        async def _no_classification(prompt, labels, fallback_label="unknown"):
            return fallback_label, None, True

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent",
                            _no_shift_verdict)
        monkeypatch.setattr(classify_node, "classify_intent_structured",
                            _no_classification)

    class _Writer:
        def __init__(self):
            self.events = []

        def __call__(self, event):
            self.events.append(event)

    def _state(self, query):
        return {"query": query, "company_id": 1, "conversation_id": "conv-1",
                "bearer_token": "t", "usage_events": [], "is_manager": False}

    @pytest.mark.parametrize("reply", [
        "9 sept",                 # the exact reported message
        "9 september 2026",
        "yesterday",
        "18th",
        "9 sept 10am to 7pm",     # date plus the times, in one go
    ])
    async def test_a_date_reply_is_classified_as_regularisation(self, reply):
        """Deterministic: it must not depend on an LLM call, which is what
        produced the shift card."""
        writer = self._Writer()
        out = await classify_node.classify_node(self._state(reply), writer)

        assert out["intent"] == "regularisation", reply

    async def test_the_reported_message_does_not_become_a_shift_query(self):
        writer = self._Writer()
        out = await classify_node.classify_node(self._state("9 sept"), writer)

        assert out["intent"] != "shift_query"
        assert out["intent"] != "punch_details"

    @pytest.mark.parametrize("query,expected", [
        ("what is my leave balance", "leave_balance"),
        ("show my team attendance", "HRMS_TEAM_ATTENDANCE_QUERY"),
    ])
    async def test_a_genuine_new_question_still_interrupts(self, query, expected):
        """The flow must not swallow everything typed while it is open - a
        real question is still answered, and the pending request is left
        alone rather than being fed the message as its date."""
        writer = self._Writer()
        out = await classify_node.classify_node(self._state(query), writer)

        assert out["intent"] == expected

    @pytest.mark.parametrize("topic", ["payroll", "salary", "policy", "appraisal"])
    async def test_a_bare_hr_topic_is_not_swallowed_as_the_date(self, topic):
        """The flow asked for a DATE, so only something that could be one is
        taken as the answer. A single HR topic word is the same SHAPE as a
        date reply - short, not a question - and an earlier version of this
        fix accepted any such message, which answered "payroll" by asking for
        a start time."""
        writer = self._Writer()
        out = await classify_node.classify_node(self._state(topic), writer)

        assert out["intent"] != "regularisation", topic

    async def test_a_bare_date_is_untouched_when_no_flow_is_open(self, monkeypatch):
        """The continuation must be scoped to the pending flow: with no
        regularisation in progress, a bare date is classified on its own
        merits exactly as before."""
        monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda ns, c, v: None)

        writer = self._Writer()
        out = await classify_node.classify_node(self._state("9 sept"), writer)

        assert out["intent"] != "regularisation"


class TestThePendingHint:
    """The LLM fallback's own instruction for this state. Only reached when
    the deterministic route above declines, but it was actively steering the
    classifier the wrong way, so it is pinned too."""

    def test_awaiting_the_first_date_encourages_regularisation(self):
        hint = classify_node._build_regularisation_pending_hint(
            [], has_free_text_pending=False, awaiting_first_entry=True)

        assert "classify it as 'regularisation'" in hint
        assert "do NOT classify" not in hint

    def test_a_complete_request_still_discourages_it(self):
        """The opposite framing, unchanged: a complete request sitting
        unconfirmed must not pull every message about the same date back
        into the flow."""
        hint = classify_node._build_regularisation_pending_hint(
            [{"date": "2026-09-09"}], has_free_text_pending=False)

        assert "do NOT classify it as 'regularisation'" in hint

    def test_a_half_filled_entry_still_encourages_it(self):
        hint = classify_node._build_regularisation_pending_hint(
            [{"date": "2026-09-09"}], has_free_text_pending=True)

        assert "classify it as 'regularisation'" in hint


# =============================================================================
# 2. The date is checked against the day's actual attendance
# =============================================================================

class TestADayWithNoAttendanceRecordIsRefused:
    """erp-api answers 200 with attendance: null for a day that has nothing
    on file (live-verified, see erp_client.get_attendance_punch_details).
    That is an answer - "there is no record here" - and a request to correct
    a record that does not exist cannot be honoured."""

    def test_no_record_on_a_day_that_was_read_is_blocked(self):
        reason = regularisation_node._attendance_status_block_reason(
            "2026-09-09", None, attendance_known=True)

        assert reason
        assert "no attendance record" in reason
        assert "Absent or Half Day Absent" in reason

    def test_a_day_nothing_could_be_read_for_still_fails_open(self):
        """An unreachable HR system must not refuse a legitimate request -
        erp-api's own post_regularization remains the real authority."""
        assert regularisation_node._attendance_status_block_reason(
            "2026-09-09", None, attendance_known=False) is None

    def test_the_default_is_the_old_fail_open_behaviour(self):
        """Any caller not yet passing the flag keeps failing open rather
        than silently starting to refuse."""
        assert regularisation_node._attendance_status_block_reason(
            "2026-09-09", None) is None

    @pytest.mark.parametrize("code", ["A", "PA"])
    def test_a_regularizable_day_is_still_allowed(self, code):
        assert regularisation_node._attendance_status_block_reason(
            "2026-09-09", code, attendance_known=True) is None

    @pytest.mark.parametrize("code,label", [
        ("P", "Present"), ("WO", "Week Off"), ("HD", "Holiday"), ("L", "On Leave"),
    ])
    def test_a_non_regularizable_day_still_names_what_it_is(self, code, label):
        reason = regularisation_node._attendance_status_block_reason(
            "2026-09-09", code, attendance_known=True)

        assert reason and label in reason


class TestThePreviewSaysWhetherTheDayWasRead:
    """The flag the gate above depends on. Without it the two kinds of
    "no status code" are indistinguishable, which is the whole bug."""

    async def _prefill(self, monkeypatch, response):
        async def _fake(token, **kwargs):
            if isinstance(response, Exception):
                raise response
            return response
        monkeypatch.setattr(regularisation_node.attendance_client, "get_punch_time", _fake)

        return await regularisation_node._get_attendance_prefill(
            bearer_token="t", date_iso="2026-09-09", company_id=1,
            conversation_id="conv-1", writer=lambda e: None,
        )

    async def test_a_day_with_no_record_is_known(self, monkeypatch):
        """200 + attendance: null + punch_status "no_records" - the shape
        erp-api actually returns for an empty day."""
        result = await self._prefill(monkeypatch, {"http_status": 200, "body": {
            "success": True, "data": {"attendance": None, "punch_status": "no_records",
                                      "punches": [], "shift": None}}})

        assert result["preview"]["attendance_known"] is True
        assert result["preview"]["attendance_status_code"] is None

    async def test_a_day_with_a_record_is_known(self, monkeypatch):
        result = await self._prefill(monkeypatch, {"http_status": 200, "body": {
            "success": True, "data": {"attendance": {"attendance": "A"},
                                      "punch_status": "no_records",
                                      "punches": [], "shift": None}}})

        assert result["preview"]["attendance_known"] is True
        assert result["preview"]["attendance_status_code"] == "A"

    async def test_an_unreachable_hr_system_is_not_known(self, monkeypatch):
        result = await self._prefill(
            monkeypatch, regularisation_node.attendance_client.ErpApiUnavailable("down"))

        assert result["preview"]["attendance_known"] is False

    async def test_a_business_failure_is_not_known(self, monkeypatch):
        result = await self._prefill(monkeypatch, {"http_status": 200, "body": {
            "success": False, "message": "something went wrong"}})

        assert result["preview"]["attendance_known"] is False
