"""Replies to a flow's own question must continue that flow, for a MANAGER too.

Two live reports, one mechanism:

    user: apply regularization for today
    bot:  Good news - 23 Sep is eligible. Reply **apply now** ...
    user: aply now
    bot:  I'm unable to reach the HR system right now   (intent: manager_leave_request_lookup)

    user: show my check in check out for this week
    bot:  ... which date between 21 Sep 2026 and 27 Sep 2026 would you like?
    user: 18 sept
    bot:  <employee picker>   (seen live; shift_query on another run)

In both, the reply was not recognised as an answer, fell through to the
general classifier, and for a manager ended in a team lookup: "aply now" is
name-shaped, so the bare-name fallback read it as an employee called
"Aply Now"; "18 sept" had no deterministic continuation before the LLM.

The apply-now wait also looked like "waiting for the first date" to the
mid-flow regularisation block (both have no entries), which is how it
bypassed that block's confirm check in the first place.
"""

import pytest

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


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

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


@pytest.fixture(autouse=True)
def _no_llm(monkeypatch):
    """Deterministic decisions only: a fix that works only 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)


def _manager_state(query, last_intent=None):
    return {"query": query, "company_id": 1, "conversation_id": "conv-1",
            "bearer_token": "t", "usage_events": [], "is_manager": True,
            "is_manager_jwt": True, "last_intent": last_intent}


def _slots(monkeypatch, regularization):
    monkeypatch.setattr(classify_node.slot_store, "get_slots",
                        lambda ns, c, v: regularization if ns == "regularization" else None)


# =============================================================================
# "Reply apply now"
# =============================================================================

class TestTheApplyNowReply:

    #: What regularisation_eligibility_node saves after "... is eligible".
    AWAITING_APPLY = {"entries": [], "awaiting_apply_confirmation": True,
                      "classified_date": "2026-09-23"}

    @pytest.mark.parametrize("reply", [
        "aply now",      # the exact reported message
        "apply now", "Apply Now!", "applynow", "apply nw", "yes", "ok",
        "cancel", "25 sept",  # the other two answers the prompt allows
    ])
    async def test_it_continues_the_regularisation_flow(self, monkeypatch, reply):
        _slots(monkeypatch, self.AWAITING_APPLY)
        out = await classify_node.classify_node(
            _manager_state(reply, last_intent="regularisation_classify"), _Writer())

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

    async def test_a_new_question_still_interrupts(self, monkeypatch):
        _slots(monkeypatch, self.AWAITING_APPLY)
        out = await classify_node.classify_node(
            _manager_state("what is my leave balance", last_intent="regularisation_classify"),
            _Writer())

        assert out["intent"] == "leave_balance"

    @pytest.mark.parametrize("reply", ["aply now", "apply nw", "appy now", "applynow"])
    def test_the_gate_itself_accepts_the_typo(self, reply):
        """classify_node sending it back is only half: the eligibility gate
        must then take it as the confirmation, or it re-asks forever."""
        assert regularisation_node._is_apply_now_confirmation(reply) is True

    @pytest.mark.parametrize("reply", ["apply no", "now", "apply leave now?"])
    def test_the_gate_is_not_loosened_past_the_phrase(self, reply):
        assert regularisation_node._is_apply_now_confirmation(reply) is False


class TestFlowRepliesAreNotNames:

    @pytest.mark.parametrize("reply", ["aply now", "apply now", "proceed", "submit", "continue"])
    def test_not_a_bare_person_fragment(self, reply):
        assert classify_node._is_bare_person_fragment(reply, False) is False

    @pytest.mark.parametrize("name", ["ayush", "ayush jio", "abctest"])
    def test_real_names_still_are(self, name):
        assert classify_node._is_bare_person_fragment(name, False) is True


# =============================================================================
# "which date would you like?" -> a bare date
# =============================================================================

class TestTheBareDateReply:

    @pytest.fixture(autouse=True)
    def _no_pending_flow(self, monkeypatch):
        _slots(monkeypatch, None)

    @pytest.mark.parametrize("last_intent", ["punch_details", "attendance", "attendance_explain"])
    @pytest.mark.parametrize("reply", ["18 sept", "18th september", "sept 18", "last friday"])
    async def test_it_continues_the_lookup_that_asked(self, last_intent, reply):
        out = await classify_node.classify_node(_manager_state(reply, last_intent=last_intent),
                                                _Writer())

        assert out["intent"] == last_intent, (reply, out["intent"])

    async def test_a_date_with_no_date_question_behind_it_is_not_forced(self):
        """Only a date-driven previous turn makes a bare date a continuation."""
        out = await classify_node.classify_node(
            _manager_state("18 sept", last_intent="leave_balance"), _Writer())

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