"""QA: "c l tomorrow / s l" came back as a Cancel Leave card.

    * leave codes are recognised spaced or dotted too ("c l", "c.l", "sh l");
    * a leave type plus a day is apply_leave - decided before the shift
      adjudicator ("sh l tomorrow" was read as a shift question) and without
      either LLM call;
    * the apply flow keeps the type when its own extraction cannot read the
      code;
    * short leave asks which half, counts as one unit, and says so.
"""

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

import pytest

import services.classify_node as classify_node
import services.leave_action_service as las
from services.nlp_service import fast_classify, fold_leave_typos, is_leave_type_apply_request


@pytest.mark.parametrize("query,folded", [
    ("c l tomorrow", "casual leave tomorrow"),
    ("s l tomorrow", "sick leave tomorrow"),
    ("e l tomorrow", "earned leave tomorrow"),
    ("sh l tomorrow", "short leave tomorrow"),
    ("shl tomorrow", "short leave tomorrow"),
    ("c.l tomorrow", "casual leave tomorrow"),
    ("c l tomorrow / s  l", "casual leave tomorrow / sick leave"),
])
def test_spaced_and_dotted_codes_fold(query, folded):
    assert fold_leave_typos(query) == folded


@pytest.mark.parametrize("query", [
    "c l tomorrow", "s l tomorrow", "e l tomorrow", "sh l tomorrow", "CL tomorrow",
    "sl on friday", "casual leave tomorrow", "short leave for 28th sept", "need cl tomorrow",
    "apply el for monday", "i want sick leave on 2nd oct", "c l tomorrow / s  l",
])
def test_a_leave_type_plus_a_day_is_apply_leave(query):
    assert fast_classify(query) == ("apply_leave", True, 1.0)


@pytest.mark.parametrize("query,intent", [
    ("what is the casual leave policy", "policy"),
    ("how many cl do i have", "leave_balance"),
    ("show me cl", "leave_balance"),
    ("is my cl tomorrow approved", "leave_status"),
    ("cancel my cl tomorrow", "cancel_leave"),
    ("my approved cl", "leave_status"),
    ("can i take cl tomorrow", "leave_eligibility"),
])
def test_neighbouring_intents_keep_their_route(query, intent):
    assert fast_classify(query)[0] == intent


@pytest.mark.parametrize("query", ["casual leave", "casual leave balance", "sick leave policy",
                                   "casual leave tomorrow?", "casual leave status for tomorrow"])
def test_no_day_or_a_question_is_not_an_application(query):
    assert not is_leave_type_apply_request(query)


# =============================================================================
# classify_node
# =============================================================================

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

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

    def of_type(self, t):
        return [e for e in self.events if e.get("type") == t]


@pytest.fixture
def _quiet(monkeypatch):
    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)


@pytest.mark.usefixtures("_quiet")
@pytest.mark.parametrize("query", ["c l tomorrow / s  l", "sh l tomorrow", "e l tomorrow"])
async def test_routed_without_the_shift_adjudicator_or_the_classifier(monkeypatch, query):
    shift = AsyncMock(return_value=(True, 0.99, None))        # would claim "sh l"
    llm = AsyncMock(return_value=("cancel_leave", None, False))
    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", llm)

    out = await classify_node.classify_node(
        {"query": query, "company_id": 1, "conversation_id": "c", "bearer_token": "t",
         "usage_events": [], "is_manager": False}, _Writer())

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


# =============================================================================
# The apply flow
# =============================================================================

TYPES = ["casual_leave", "sick_leave", "earned_leave", "short_leave"]

# "Today" for the leave flow in these tests. Their leave dates are fixed
# (2026-11-16, 2026-11-18), and the flow refuses a date before today — so on
# the real clock they would start failing once the calendar passed them ("You
# can't apply for leave on a past date"), for a reason unrelated to what they
# test. Pinned only inside _turn, where the flow runs.
TEST_TODAY = date(2026, 9, 28)


async def _turn(query, slots, extracted):
    ok = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "Abcd Test", "is_manager": False,
        "leave_quota": {k: {"total": 20, "remaining": 11} for k in TYPES},
        "leave_settings": {"leave_type": [{"slug": s, "name": s.replace("_", " ").title()}
                                          for s in TYPES]},
        "leaves": [], "abbreviations": []}}})
    store, writer = dict(slots), _Writer()

    def _set(c, cid, s):
        store.clear()
        store.update(s)

    with patch.object(las, "_today", lambda: TEST_TODAY), \
            patch.object(las, "_today_in_app_timezone", lambda: TEST_TODAY), \
            patch.object(las.erp_client, "get_leave_context", ok), \
            patch.object(las.erp_client, "get_leave_balance", ok), \
            patch.object(las.erp_client, "get_applied_leaves", ok), \
            patch.object(las, "_call_llm", AsyncMock(return_value={})), \
            patch.object(las, "_extract_text", lambda raw: json.dumps(extracted)), \
            patch.object(las.leave_slot_service, "get_slots", lambda *a, **k: dict(store) or None), \
            patch.object(las.leave_slot_service, "set_slots", _set), \
            patch.object(las.leave_slot_service, "clear_slots", lambda *a, **k: True):
        out = await las.leave_action_node(
            {"query": query, "intent": "apply_leave", "bearer_token": "t", "company_id": 1,
             "conversation_id": "ap", "usage_events": [], "is_manager": False}, writer)
    return out["response_text"], writer, store


async def test_the_type_survives_an_extraction_that_cannot_read_the_code():
    """Extraction returned the date but no type for "e l ..."."""
    text, _, store = await _turn("e l on 18th nov", {}, {"from_date": "2026-11-18",
                                                       "to_date": "2026-11-18"})

    assert store["leave_type"] == "earned_leave"
    assert "what type of leave" not in text.lower()


@pytest.mark.parametrize("session", [None, "full_day", "half_day"])
async def test_short_leave_asks_which_half(session):
    extracted = {"leave_type": "short_leave", "from_date": "2026-11-16", "to_date": "2026-11-16"}
    if session:
        extracted["session_type_slug"] = session
    text, _, store = await _turn("sh l on 16th nov", {}, extracted)

    assert text == "Would that be the first half or second half of the day?"
    assert store.get("session_type_slug") is None


async def test_short_leave_is_one_unit_and_the_card_names_the_half():
    ready = {"step": "collecting", "leave_type": "short_leave", "from_date": "2026-11-16",
             "to_date": "2026-11-16", "session_type_slug": "first_half_day",
             "reason": "Bank work", "reason_confirmed": True, "_leave_abbreviations": {}}
    text, writer, _ = await _turn("bank work", ready, {})

    card = writer.of_type("leave_confirmation")[0]["data"]
    assert card["total_days"] == 1.0
    assert "To confirm: short leave on 2026-11-16 (first half)." in text
    assert "0.5" not in text


def test_a_half_day_of_other_leave_is_still_half():
    assert las._compute_requested_days({"leave_type": "casual_leave", "from_date": "2026-11-16",
                                        "to_date": "2026-11-16",
                                        "session_type_slug": "first_half_day"}) == 0.5
