"""A date typed with a letter in it is asked about - in every flow - and the
answer re-reads the ORIGINAL message with the chosen date, so whichever flow
was running (or being started) carries on as if it had been typed right.

Live (Oct 14): "sept 3o" became 30 Sep, "apply regularization for 2o" 30 Sep,
"o3 oct" 3 Oct - all without a word. The question used to be asked only when
a NEW regularization was starting; inside an open form, a leave, an
attendance question or an approval it was still guessed.
"""
from datetime import date

import pytest

import services.classify_node as classify_node
import services.date_query_resolver as dqr
import services.leave_slot_service as leave_slot_service

TODAY = date(2026, 10, 14)


class Writer(list):
    def __call__(self, event):
        self.append(event)

    def done(self):
        return [e for e in self if e.get("type") == "done"][-1]


@pytest.fixture
def store(monkeypatch):
    slots = {}
    monkeypatch.setattr(classify_node.slot_store, "get_slots",
                        lambda ns, c, v: slots.get((ns, str(c), v)))
    monkeypatch.setattr(classify_node.slot_store, "set_slots",
                        lambda ns, c, v, d: slots.__setitem__((ns, str(c), v), d) or True)
    monkeypatch.setattr(classify_node.slot_store, "clear_slots",
                        lambda ns, c, v: slots.pop((ns, str(c), v), None) or True)
    monkeypatch.setattr(classify_node, "_today_in_app_timezone", lambda: TODAY)
    monkeypatch.setattr(leave_slot_service, "get_manager_action", lambda c, v: None)
    monkeypatch.setattr(leave_slot_service, "get_report_state", lambda c, v: None)

    async def _no_shift(q):
        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)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _no_classification)
    return slots


def _state(query, last_intent=None, context=None, is_manager=False):
    return {"query": query, "company_id": 1, "conversation_id": "conv-typo",
            "bearer_token": "t", "usage_events": [], "is_manager": is_manager,
            "is_manager_jwt": True, "is_hr_role": False, "last_intent": last_intent,
            "context": context or []}


# -- detecting, choosing, rewriting -------------------------------------------

@pytest.mark.parametrize("text,options", [
    ("i want to apply regularization for 3o sept", ["2026-09-03", "2026-09-30"]),
    ("apply casual leave for 2o oct", ["2026-10-02", "2026-10-20"]),
    ("change the date to o3 oct", ["2026-10-03"]),
    ("show my attendance for sept 3o 2025", ["2025-09-03", "2025-09-30"]),
    ("apply regularization for 2o", ["2026-10-02", "2026-10-20"]),
])
def test_find(text, options):
    assert dqr.find_typo_day(text, TODAY).options == options


@pytest.mark.parametrize("text", ["h2o", "co2 levels", "apply for 2 oct", "my id is o3",
                                  "reason: arrived at 10 for o2 meeting"])
def test_not_a_typo_day(text):
    assert dqr.find_typo_day(text, TODAY) is None


@pytest.mark.parametrize("reply,chosen", [
    ("30 sept", "2026-09-30"), ("30", "2026-09-30"), ("3", "2026-09-03"),
    ("the second one", "2026-09-30"), ("first", "2026-09-03"),
    ("4 sept", "2026-09-04"),           # a third date is taken as given
    ("thanks", None), ("yes", None),    # "yes" picks nothing between two
    ("2o", None),                       # another typo is asked about again
])
def test_pick(reply, chosen):
    assert dqr.pick_typo_option(reply, ["2026-09-03", "2026-09-30"], TODAY) == chosen


def test_yes_confirms_a_single_option():
    assert dqr.pick_typo_option("yes", ["2026-10-03"], TODAY) == "2026-10-03"


@pytest.mark.parametrize("text,chosen,rewritten", [
    ("i want to apply regularization for 3o sept", "2026-09-30",
     "i want to apply regularization for 30 Sep 2026"),
    ("sept 3o", "2026-09-03", "3 Sep 2026"),
    ("apply regularization for 2o", "2026-10-20", "apply regularization for 20 Oct 2026"),
    ("accept for o7 oct", "2026-10-07", "accept for 7 Oct 2026"),
    ("show my attendance for sept 3o 2025", "2025-09-30", "show my attendance for 30 Sep 2025"),
])
def test_rewrite(text, chosen, rewritten):
    assert dqr.apply_typo_choice(text, dqr.find_typo_day(text, TODAY), chosen) == rewritten


# -- classify_node -------------------------------------------------------------

@pytest.mark.parametrize("query", [
    "i want to apply regularization for 3o sept", "apply casual leave for 2o oct",
    "show my attendance for 3o sept", "change the date to o3 oct", "accept for o7 oct",
])
async def test_asked_in_every_flow(store, query):
    writer = Writer()
    out = await classify_node.classify_node(_state(query, "manager_regularisation_view"), writer)
    assert out["intent"] == classify_node.DATE_CLARIFY_INTENT
    assert "looks like a typo - did you mean" in writer.done()["data"]["answer"]
    assert writer.done()["data"]["input_required"] == "date"


async def test_the_answer_resumes_the_flow_that_was_running(store):
    """Under the team list, "accept for o7 oct" -> "yes" is "accept for 7 Oct
    2026" read with the team list still the previous turn."""
    await classify_node.classify_node(
        _state("accept for o7 oct", "manager_regularisation_view", is_manager=True), Writer())
    out = await classify_node.classify_node(
        _state("yes", classify_node.DATE_CLARIFY_INTENT, is_manager=True), Writer())
    assert out["query"] == "accept for 7 Oct 2026"
    assert out["last_intent"] == "manager_regularisation_view"
    assert out["intent"] == "manager_regularisation_approval"


async def test_the_answer_starts_a_new_flow(store):
    await classify_node.classify_node(_state("i want to apply regularization for 3o sept"), Writer())
    out = await classify_node.classify_node(_state("30 sept", classify_node.DATE_CLARIFY_INTENT),
                                            Writer())
    assert out["query"] == "i want to apply regularization for 30 Sep 2026"
    assert out["intent"] == "regularisation"


async def test_redis_lost_the_question_is_rebuilt_from_history(store):
    """Nothing stored (Redis lost on Live): the question and the message it
    asked about are read back from the conversation history."""
    history = [{"role": "user", "content": "i want to apply regularization for 3o sept"},
               {"role": "assistant", "content": "\"3o sept\" looks like a typo - did you mean "
                                                "03 Sep 2026 or 30 Sep 2026? Please reply with the date."}]
    out = await classify_node.classify_node(
        _state("the second one", classify_node.DATE_CLARIFY_INTENT, context=history), Writer())
    assert out["query"] == "i want to apply regularization for 30 Sep 2026"


async def test_a_reply_that_is_not_an_answer_is_read_on_its_own(store):
    await classify_node.classify_node(_state("apply regularization for 3o sept"), Writer())
    out = await classify_node.classify_node(
        _state("show my leave balance", classify_node.DATE_CLARIFY_INTENT), Writer())
    assert out["intent"] != classify_node.DATE_CLARIFY_INTENT
    assert "query" not in out or out["query"] == "show my leave balance"
    assert not store, "the question is not left armed"


async def test_a_bare_typo_with_no_month_is_only_a_date_in_an_hr_context(store):
    out = await classify_node.classify_node(_state("2o"), Writer())
    assert out["intent"] != classify_node.DATE_CLARIFY_INTENT
    out = await classify_node.classify_node(_state("2o", "regularization_incomplete"), Writer())
    assert out["intent"] == classify_node.DATE_CLARIFY_INTENT


async def test_a_card_payload_is_never_asked_about(store):
    out = await classify_node.classify_node(
        _state('{"action": "confirm", "date": "2026-09-30", "reason": "3o sept"}'), Writer())
    assert out["intent"] != classify_node.DATE_CLARIFY_INTENT


def test_the_graph_stops_after_the_question():
    import services.hr_graph as hr_graph
    assert hr_graph._route_after_classify(
        {"intent": classify_node.DATE_CLARIFY_INTENT, "response_text": "x"}) == hr_graph.END


# -- a refusal that asks for another date keeps the flow open ------------------

@pytest.mark.parametrize("message,held", [
    ("You can't regularize future dates — 20 Oct 2026 hasn't happened yet. Regularization is "
     "only for attendance that's already happened, so please give me a date on or before "
     "today (14 Oct 2026).", True),
    ("Regularization period has expired for 05 Sep 2026 — you can only regularize dates within "
     "the last 20 days. Could you give me a more recent date instead?", True),
    ("I can't regularize 02 Oct 2026 — that day is marked **Holiday**. Could you give me a "
     "different date instead?", True),
    ("You've already applied for regularization on 01-Oct-2026, currently Pending approval "
     "(Ref: REG-201).", False),
    ("Your regularization quota for 21 Sep – 20 Oct 2026 has been used (2 of 2), so I can't "
     "take a new request for 02 Oct 2026.", False),
])
def test_which_refusals_wait_for_another_date(message, held):
    """Live: after "20 oct" was refused as a future date, the reply "2 oct"
    went to the shift lookup - the refusal asked for a date and then closed
    the flow it was asking for."""
    import services.regularisation_node as reg
    assert reg._asks_for_another_date(message) is held
