"""Switching topic mid-chat must not be read as continuing the last one.

Reported live: asking about an employee and then typing "sick leave for
tomorrow" was answered about THAT EMPLOYEE's sick leave. The message names a
leave type, and a bare leave type after an employee lookup legitimately means
"narrow that lookup to this type" -- so the continuation claimed the whole
sentence, verb, date and all. It did the same to "apply sick leave for
tomorrow", where the verb says plainly whose leave it is.

The rule: context may complete a FRAGMENT, never swallow a message that asks
for something in its own right. A bare "sick leave" is a fragment. "Sick leave
for tomorrow" is a request.
"""
import pytest
import services.classify_node as cn
from services.classify_node import _reads_as_a_fresh_request as fresh

pytestmark = pytest.mark.asyncio


class _W:
    def __call__(self, ev): pass


async def _classify(query, last_intent=None, context=None):
    state = {"query": query, "company_id": 1, "conversation_id": "ctx-test",
             "bearer_token": "t", "usage_events": [], "messages": [],
             "context": context or [], "is_manager": True, "is_hr": False,
             "role": "manager"}
    if last_intent:
        state["last_intent"] = last_intent
    return (await cn.classify_node(state, _W())).get("intent")


LOOKUP = "manager_leave_request_lookup"


@pytest.mark.parametrize("query,expected", [
    ("sick leave for tomorrow", "apply_leave"),
    ("apply sick leave for tomorrow", "apply_leave"),
    ("casual leave on 5 october", "apply_leave"),
    ("what is my leave balance", "leave_balance"),
    ("what is the sick leave policy", "policy"),
])
async def test_a_whole_request_is_not_swallowed_by_the_previous_lookup(query, expected):
    assert await _classify(query, LOOKUP) == expected, (
        "a self-service request was answered as a continuation of the "
        "employee lookup before it")


@pytest.mark.parametrize("query", ["sick leave", "short leave", "casual leave"])
async def test_a_bare_leave_type_still_narrows_that_lookup(query):
    """The continuation is real and must keep working -- a bare type after
    looking at someone's requests means THAT person's leave of that type."""
    assert await _classify(query, LOOKUP) == LOOKUP


async def test_the_same_request_classifies_identically_with_no_prior_context():
    """The control that proves the bug was the context and not the wording."""
    for query, expected in [("sick leave for tomorrow", "apply_leave"),
                            ("casual leave on 5 october", "apply_leave")]:
        assert await _classify(query) == expected


# ── The fragment/request line itself, with no model call ────────────────────
# Grammar, not an intent lookup: fast_classify scores "show my payslip for
# august" as nothing at all, so an intent-based test could never have caught
# the second bug this file records.

@pytest.mark.parametrize("fragment", [
    "sick leave", "short leave", "casual leave", "his sick leave",
    "yesterday", "19 september", "last friday", "20 september",
    "4th wednesday of august",
])
def test_fragments_are_not_fresh_requests(fragment):
    """These complete an earlier question; context MUST still apply to them."""
    assert not fresh(fragment)


@pytest.mark.parametrize("request_", [
    "show my payslip for august",
    "how many WFH days do we get",
    "apply sick leave for tomorrow",
    "sick leave for tomorrow",
    "what is the notice period",
    "show my attendance for yesterday",
    "regularise my attendance for 19 september",
    "is my leave approved",
    "cancel my leave",
])
def test_whole_requests_are_fresh(request_):
    """These stand on their own; context must NOT be applied to them."""
    assert fresh(request_)


DATE_REFINABLE = ["attendance", "regularisation", "leave_status", "punch_details"]


@pytest.mark.parametrize("last_intent", DATE_REFINABLE)
# "show my payslip for august" -- the message that exposed this -- is checked
# in test_whole_requests_are_fresh above instead. At classify_node level it
# needs the LLM (fast_classify scores it as nothing), and a suite that calls a
# live model is a suite that fails for reasons unrelated to the code.
@pytest.mark.parametrize("query,expected", [
    ("apply sick leave for tomorrow", "apply_leave"),
    ("regularise my attendance for 19 september", "regularisation"),
])
async def test_a_dated_request_is_not_re_aimed_at_the_previous_lookup(
        last_intent, query, expected):
    """A message containing a date is not automatically a re-targeting of the
    last date-driven lookup. "show my payslip for august" after "show my
    attendance for last week" was answered as an ATTENDANCE lookup."""
    got = await _classify(query, last_intent)
    assert got == expected, f"{query!r} was swallowed by last_intent={last_intent}"


@pytest.mark.parametrize("last_intent,bare,expected", [
    ("attendance", "yesterday", "attendance"),
    ("attendance", "19 september", "attendance"),
    ("leave_status", "20 september", "leave_status"),
])
async def test_a_bare_date_still_re_aims_the_previous_lookup(
        last_intent, bare, expected):
    """The other direction: context must NOT be lost for real follow-ups."""
    assert await _classify(bare, last_intent) == expected
