"""QA: "pls shoe me checkin checkout before 9th sept" showed the 9th's own
punches - the one day the employee had just excluded.

punch_details answers one day, so a date named only as an anchor ("before" /
"after" / "prior to" it) is now offered back as the adjacent day - "Did you
mean 08 Sep 2026?" - and the bare yes/no that answers it is routed straight
to punch_details without an LLM call. "checkin"/"checkout" as one word now
reach punch_details from the keyword layer instead of waiting on the LLM.
"""

from datetime import date
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

import services.classify_node as classify_node
import services.erp_client as erp_client
import services.punch_date_suggestion_state as offer_state
import services.punch_details as punch_details
from services.nlp_service import fast_classify

TODAY = date(2026, 9, 24)


# =============================================================================
# Detection
# =============================================================================

@pytest.mark.parametrize("query,step", [
    ("pls shoe me checkin checkout before 9th sept", -1),
    ("show my check in before 9th sept", -1),
    ("punches prior to 9 sept", -1),
    ("checkin checkout after 22nd sept", 1),
])
def test_an_anchor_date_is_detected(query, step):
    found = punch_details._relative_anchor(query)
    assert found is not None and found[0] == step
    assert "before" not in found[1] and "after" not in found[1]


@pytest.mark.parametrize("query", [
    "punch details for the day before yesterday",   # names one day exactly
    "the day after 9th sept punches",
    "punch details before yesterday",
    "check in time for 9th sept",
    "what were my punch times",
])
def test_an_exact_day_is_not_an_anchor(query):
    assert punch_details._relative_anchor(query) is None


@pytest.mark.parametrize("query", [
    "pls shoe me checkin checkout before 9th sept", "my checkin time yesterday",
    "what time did i checkin", "show checkouts for 9 sept", "clockin time today",
])
def test_one_word_checkin_is_punch_details(query):
    assert fast_classify(query) == ("punch_details", True, 1.0)


@pytest.mark.parametrize("reply", ["yes", "YES", "yess", "ok", "y", "sure", "yes please", "go ahead"])
def test_yes(reply):
    assert offer_state.is_yes(reply) and not offer_state.is_no(reply)


@pytest.mark.parametrize("reply", ["no", "noo", "nope", "no thanks"])
def test_no(reply):
    assert offer_state.is_no(reply) and not offer_state.is_yes(reply)


@pytest.mark.parametrize("reply", ["yes show 7th sept instead", "show my leave balance", "7th sept",
                                   "no, 7th sept"])
def test_anything_else_is_neither(reply):
    assert not offer_state.is_yes(reply) and not offer_state.is_no(reply)


# =============================================================================
# punch_details_node
# =============================================================================

@pytest.fixture
def stores(monkeypatch):
    """In-memory stand-ins for both Redis stores."""
    offers, remembered = {}, {"date": "2026-09-09"}   # classify_node remembered the anchor
    monkeypatch.setattr(offer_state, "get_state", lambda c, cid: offers.get("x"))
    monkeypatch.setattr(offer_state, "set_state", lambda c, cid, d: offers.update(x={"date": d}))
    monkeypatch.setattr(offer_state, "clear_state", lambda c, cid: offers.pop("x", None))
    lrd = punch_details.last_resolved_date_state
    monkeypatch.setattr(lrd, "set_last_resolved_date", lambda c, cid, d: remembered.update(date=d))
    monkeypatch.setattr(lrd, "consume_last_resolved_date", lambda c, cid: remembered.pop("date", None))
    monkeypatch.setattr(lrd, "clear_last_resolved_date", lambda c, cid: remembered.pop("date", None))
    monkeypatch.setattr(punch_details, "_today", lambda: TODAY)
    return offers, remembered


def _punches(day):
    return {"http_status": 200, "body": {"success": True, "data": {
        "requested_date": day, "shift": {"name": "General-Shift"},
        "punches": [{"check_in": f"{day} 10:02:00", "check_out": f"{day} 18:54:00", "complete": True}],
        "work_hours": {"available": True, "value": "08:16"}}}}


async def _turn(query, resolves_to=None):
    writer = MagicMock()
    erp = AsyncMock(side_effect=lambda token, date=None, **k: _punches(date))
    resolver = AsyncMock(return_value=resolves_to)
    with patch.object(punch_details, "_resolve_requested_date", resolver), \
            patch.object(erp_client, "get_punch_details", erp):
        out = await punch_details.punch_details_node(
            {"query": query, "bearer_token": "t", "company_id": 1,
             "conversation_id": "c", "usage_events": []}, writer)
    return out["response_text"], erp, resolver


async def test_before_offers_the_day_before_instead_of_answering_the_anchor(stores):
    offers, remembered = stores
    text, erp, resolver = await _turn("pls shoe me checkin checkout before 9th sept",
                                      resolves_to="2026-09-09")

    assert "Did you mean 08 Sep 2026, the day before 09 Sep 2026?" in text
    erp.assert_not_awaited()
    assert offers["x"] == {"date": "2026-09-08"}
    # The anchor was resolved as a plain date, not handed over with "before".
    assert "before" not in resolver.await_args.args[0]
    # And it is no longer remembered as the day under discussion.
    assert "date" not in remembered


async def test_yes_shows_the_offered_day(stores):
    offers, _ = stores
    offers["x"] = {"date": "2026-09-08"}
    text, erp, resolver = await _turn("yes")

    assert erp.await_args.kwargs["date"] == "2026-09-08"
    resolver.assert_not_awaited()                     # no LLM date call for "yes"
    assert "x" not in offers


async def test_no_asks_for_a_date(stores):
    offers, _ = stores
    offers["x"] = {"date": "2026-09-08"}
    text, erp, _ = await _turn("no")

    assert text == "No problem — which date would you like the punch details for?"
    erp.assert_not_awaited()
    assert "x" not in offers


async def test_after_a_date_that_is_today_is_offered(stores):
    text, _, _ = await _turn("checkin checkout after 23rd sept", resolves_to="2026-09-23")
    assert "Did you mean 24 Sep 2026, the day after 23 Sep 2026?" in text


async def test_after_today_is_not_offered(stores):
    offers, _ = stores
    text, erp, _ = await _turn("checkin checkout after 24th sept", resolves_to="2026-09-24")

    assert "hasn't happened yet" in text
    assert "x" not in offers
    erp.assert_not_awaited()


# =============================================================================
# classify_node: the reply is routed without the LLM
# =============================================================================

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

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


@pytest.fixture
def _quiet(monkeypatch):
    async def _no_shift(query):
        return None, 0.0, None
    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda *a, **k: None)
    monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: None)
    monkeypatch.setattr(classify_node.leave_cancel_state, "get_state", lambda *a, **k: None)


def _state(query):
    return {"query": query, "company_id": 1, "conversation_id": "c", "bearer_token": "t",
            "usage_events": [], "is_manager": False, "last_intent": "punch_details"}


@pytest.mark.usefixtures("_quiet")
@pytest.mark.parametrize("reply", ["yes", "yess", "ok", "no"])
async def test_a_bare_answer_goes_to_punch_details_without_the_llm(monkeypatch, reply):
    monkeypatch.setattr(classify_node.punch_date_suggestion_state, "get_state",
                        lambda *a: {"date": "2026-09-08"})
    llm = AsyncMock(return_value=("small_talk", None, False))
    monkeypatch.setattr(classify_node, "classify_intent_structured", llm)

    out = await classify_node.classify_node(_state(reply), _Writer())

    assert out["intent"] == "punch_details"
    llm.assert_not_awaited()


@pytest.mark.usefixtures("_quiet")
async def test_moving_on_drops_the_offer(monkeypatch):
    cleared = []
    monkeypatch.setattr(classify_node.punch_date_suggestion_state, "get_state",
                        lambda *a: {"date": "2026-09-08"})
    monkeypatch.setattr(classify_node.punch_date_suggestion_state, "clear_state",
                        lambda *a: cleared.append(1))
    monkeypatch.setattr(classify_node, "classify_intent_structured",
                        AsyncMock(return_value=("leave_balance", None, False)))

    out = await classify_node.classify_node(_state("show my leave balance"), _Writer())

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