"""QA batch, 2026-09-23 - seven screenshots, each the wrong intent or the
wrong answer for a plainly worded question:

    Has my leave been approved?                -> 24 leaves in one "which one?" sentence
    Has my manager approved my leave for 25th? -> "I can only share attendance details..."
    I don't need the leave anymore, withdraw it -> a NEW leave application, twice
    How many regularizations do I have left?   -> the LEAVE balance table
    Can I apply leave if my balance is zero?   -> a Cancel Leave card
    Show me Rahul's leave balance              -> "I can only share attendance details..."
"""

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
import services.ownership_guard as og
from services.nlp_service import extract_other_balance_target, fast_classify


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]


# =============================================================================
# Keyword routing
# =============================================================================

@pytest.mark.parametrize("query", [
    "I don't need the leave anymore, withdraw it",
    "i no longer need my leave on friday",
    "withdraw my leave", "please withdraw it", "take back my leave request",
])
def test_a_withdrawal_is_a_cancellation_not_an_application(query):
    assert fast_classify(query)[0] == "cancel_leave"


@pytest.mark.parametrize("query", [
    "Can I apply leave if my balance is zero?",
    "can i cancel leave after approval",
    "can i take leave without approval",
    "can we carry forward leave if unused",
    "How many regularizations do I have left this month?",
])
def test_a_rules_question_is_policy(query):
    assert fast_classify(query)[0] == "policy"


@pytest.mark.parametrize("query,intent", [
    ("can i apply leave for tomorrow", "apply_leave"),
    ("can i apply leave tomorrow if possible", "apply_leave"),
    ("apply leave for tomorrow", "apply_leave"),
    ("i need leave tomorrow", "apply_leave"),
    ("can i cancel my leave for 25th", "cancel_leave"),
    ("am i eligible for leave if i joined last month", "leave_eligibility"),
    ("show my cancelled leaves", "leave_status"),
])
def test_actions_and_eligibility_keep_their_intent(query, intent):
    assert fast_classify(query)[0] == intent


@pytest.mark.parametrize("query,name", [
    ("Show me Rahul's leave balance", "Rahul"),
    ("what is priya sharma's casual leave balance", "Priya Sharma"),
    ("leave balance of Ravi Kumar", "Ravi Kumar"),
    ("show my leave balance", None),
    ("my team's leave balance", None),
    ("leave balance for this month", None),
])
def test_the_balance_target_is_found_only_when_someone_is_named(query, name):
    assert extract_other_balance_target(query) == name


# =============================================================================
# classify_node: deterministic rules win over a mislabelling LLM
# =============================================================================

def _llm_says(label):
    async def _classify(prompt, labels, fallback_label="unknown"):
        return label, None, False
    return _classify


@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, **extra):
    s = {"query": query, "company_id": 1, "conversation_id": "c", "bearer_token": "t",
         "usage_events": [], "is_manager": False}
    s.update(extra)
    return s


@pytest.mark.usefixtures("_quiet")
@pytest.mark.parametrize("query,llm_label,expected", [
    ("How many regularizations do I have left this month?", "leave_balance", "policy"),
    ("How many WFH days can I take in a month?", "attendance", "policy"),
    # A non-manager asking for someone else's balance is refused by the
    # access gate (single deny intent + card); a manager's version is covered
    # by the named-balance tests further down.
    ("Show me Rahul's leave balance", "HRMS_TEAM_LEAVE_QUERY", "team_attendance_restricted"),
])
async def test_the_llm_mislabel_is_corrected(monkeypatch, query, llm_label, expected):
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm_says(llm_label))
    out = await classify_node.classify_node(_state(query), _Writer())

    assert out["intent"] == expected


@pytest.mark.usefixtures("_quiet")
@pytest.mark.parametrize("step", ["awaiting_reason", "awaiting_confirmation", "awaiting_selection"])
async def test_a_rules_question_is_not_swallowed_by_a_pending_cancel(monkeypatch, step):
    """The Cancel Leave card came back for "Can I apply leave if my balance is
    zero?" - with a cancellation open, "apply ... leave" read as an apply
    instruction and the leave node re-showed the pending card."""
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm_says("cancel_leave"))
    monkeypatch.setattr(classify_node.leave_cancel_state, "get_state",
                        lambda *a, **k: {"step": step, "request_id": 306})
    out = await classify_node.classify_node(
        _state("Can I apply leave if my balance is zero?", last_intent="cancel_leave"), _Writer())

    assert out["intent"] == "policy"


# =============================================================================
# The ownership guard: a leave question is not an attendance question
# =============================================================================

async def test_a_manager_approval_question_is_not_refused_as_attendance(monkeypatch):
    called = []

    async def _manager_label(prompt, labels, fallback_label="unknown"):
        called.append(prompt)
        return "manager", None, True

    monkeypatch.setattr(og, "classify_intent_structured", _manager_label)
    out = await og.ownership_guard_node(
        {"query": "Has my manager approved my leave for 25th?", "bearer_token": "a.e30.c",
         "is_manager": False}, lambda e: None)

    assert out["blocked"] is False
    assert called == []


# =============================================================================
# leave_action_node: a named person's balance
# =============================================================================

async def _balance(query, *, is_manager):
    ctx = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "Abcd Test", "is_manager": is_manager, "is_hr": False}}})
    bal = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "leave_quota": {"casual_leave": {"total": 12, "remaining": 5}}}}})
    writer = _Writer()
    with patch.object(las.erp_client, "get_leave_context", ctx), \
            patch.object(las.erp_client, "get_leave_balance", bal), \
            patch.object(las.leave_slot_service, "get_slots", lambda *a, **k: None):
        out = await las.leave_action_node(
            {"query": query, "intent": "leave_balance", "bearer_token": "t", "company_id": 1,
             "conversation_id": "b", "usage_events": [], "is_manager": is_manager}, writer)
    return out["response_text"], bal, writer


async def test_an_employee_is_refused_someone_elses_balance_without_an_erp_call():
    text, bal, writer = await _balance("Show me Rahul's leave balance", is_manager=False)

    assert text == las.OTHERS_BALANCE_REFUSAL
    assert "attendance" not in text
    bal.assert_not_called()
    assert writer.of_type("leave_balance") == []


async def test_a_manager_is_refused_the_named_persons_balance():
    # Product decision 2026-09-30: only HR sees another employee's balance.
    text, bal, _ = await _balance("Show me Rahul's leave balance", is_manager=True)

    assert text == las.OTHERS_BALANCE_REFUSAL
    bal.assert_not_called()


@pytest.mark.parametrize("is_manager", [False, True])
async def test_a_role_word_is_refused_for_everyone(is_manager):
    text, bal, _ = await _balance("my manager's leave balance", is_manager=is_manager)

    assert text == las.OTHERS_BALANCE_REFUSAL
    bal.assert_not_called()


async def test_naming_yourself_is_your_own_balance():
    text, bal, _ = await _balance("Show me Abcd Test's leave balance", is_manager=False)

    assert text == "Here's your current leave balance."
    assert bal.call_args.kwargs.get("employee_name") is None


# =============================================================================
# leave_action_node: "has my leave been approved?"
# =============================================================================

LEAVES = [
    {"id": 300 + i, "leave_type": t, "leave_type_slug": t.lower().replace(" ", "_"),
     "from_date": d, "to_date": d, "status_name": s, "total_days": 1}
    for i, (t, s, d) in enumerate([
        ("Casual Leave", "pending", "2026-09-21"), ("Earned Leave", "approved", "2026-09-16"),
        ("Short Leave", "rejected", "2026-09-18"), ("Sick Leave", "approved", "2026-09-25"),
        ("Sick Leave", "pending", "2026-10-10"), ("Casual Leave", "cancelled", "2026-11-10"),
        ("Earned Leave", "approved", "2026-09-05"),
    ])
]


async def _status(query):
    ctx = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "Abcd Test", "is_manager": False}}})
    applied = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "leaves": LEAVES}}})
    writer = _Writer()
    with patch.object(las.erp_client, "get_leave_context", ctx), \
            patch.object(las.erp_client, "get_applied_leaves", applied), \
            patch.object(las.leave_slot_service, "get_slots", lambda *a, **k: None), \
            patch.object(las.leave_disambiguation_state, "set_candidates", lambda *a, **k: None), \
            patch.object(las, "_today_in_app_timezone", lambda: date(2026, 9, 23)):
        out = await las.leave_action_node(
            {"query": query, "intent": "leave_status", "bearer_token": "t", "company_id": 1,
             "conversation_id": "s", "usage_events": [], "is_manager": False,
             "has_date_expression": False}, writer)
    return out["response_text"], writer


async def test_a_bare_approval_question_is_answered_not_asked_back():
    text, writer = await _status("Has my leave been approved?")

    assert text == "3 of your 7 leave requests are approved (2 pending, 1 rejected, 1 cancelled)."
    cards = writer.of_type("leave_status")
    assert [c["status_name"] for c in cards[0]["data"]["leaves"]] == ["approved"] * 3
    assert writer.of_type("leave_cancellation_selection") == []


@pytest.mark.parametrize("query,expected", [
    ("Has my manager approved my leave for 25th?", "is approved"),
    ("is my leave for 21st approved", "is pending"),
    # 27 characters between "is" and "approved" - fell to the LIST path,
    # which knew no bare day and answered with an approved leave in October.
    ("is my casual leave for 21st approved", "(2026-09-21 to 2026-09-21) (1 day(s)) is pending"),
])
async def test_a_bare_day_of_the_month_picks_that_leave(query, expected):
    text, _ = await _status(query)

    assert expected in text


@pytest.mark.parametrize("query,day", [
    ("Has my manager approved my leave for 25th?", 25), ("leave on the 3rd", 3),
    ("my leave for 25 days", None), ("leave for 3 months", None),
    ("approved leave on 25th september", None), ("leave at 10 am", None),
])
def test_bare_day_parsing(query, day):
    assert las._bare_day_of_month(query) == day


async def test_a_date_with_no_leave_says_so_and_offers_what_is_on_record():
    text, writer = await _status("is my leave for 12th approved")

    assert text.startswith("I couldn't find any leave request for 12 Sep 2026.")
    assert "is it one of these?" in text
    assert len(writer.of_type("leave_status")[0]["data"]["leaves"]) == len(LEAVES)


async def test_a_day_the_month_does_not_have_is_questioned():
    text, _ = await _status("is my leave for 31st approved")

    assert text == "September 2026 doesn't have a 31st — could you check the date?"


async def test_a_named_date_lists_every_leave_on_it_without_a_menu():
    text, _ = await _status("show my leaves for 21st")

    assert "Just to make sure" not in text
    assert "Casual Leave" in text and "2026-09-21" in text


# =============================================================================
# "withdraw it" with an application still being filled in
# =============================================================================

DRAFT = {"step": "collecting", "leave_type": None, "from_date": None, "to_date": None,
         "session_type_slug": None, "reason": None}


@pytest.mark.usefixtures("_quiet")
@pytest.mark.parametrize("query,intent", [
    ("I don't need the leave anymore, withdraw it", "apply_leave"),   # withdraw the DRAFT
    ("withdraw it", "apply_leave"),
    ("withdraw my leave LR-306", "cancel_leave"),                      # names a submitted one
])
async def test_withdrawal_with_a_draft_open_targets_the_draft(monkeypatch, query, intent):
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm_says("cancel_leave"))
    monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: dict(DRAFT))
    out = await classify_node.classify_node(_state(query, last_intent="apply_leave"), _Writer())

    assert out["intent"] == intent


async def test_the_draft_is_withdrawn_in_the_users_own_words():
    cleared = []
    ctx = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "Abcd Test", "is_manager": False}}})
    with patch.object(las.erp_client, "get_leave_context", ctx), \
            patch.object(las.leave_slot_service, "get_slots", lambda *a, **k: dict(DRAFT)), \
            patch.object(las.leave_slot_service, "clear_slots", lambda *a, **k: cleared.append(1)):
        out = await las.leave_action_node(
            {"query": "I don't need the leave anymore, withdraw it", "intent": "apply_leave",
             "bearer_token": "t", "company_id": 1, "conversation_id": "d", "usage_events": [],
             "is_manager": False}, _Writer())

    assert cleared
    assert out["response_text"] == (
        "No problem — I've withdrawn the current leave request. Nothing was submitted, and no "
        "existing leave was cancelled. Let me know if you'd like to start a new one.")


def test_withdraw_is_not_a_decline_at_the_cancel_confirmation_step():
    """The shared decline vocabulary must not learn "withdraw": at the
    cancel-leave confirmation it would mean "keep it", the opposite."""
    assert las._is_declining_or_cancelling("withdraw it") is False


# =============================================================================
# The apply-leave confirmation card: "change due to fever", then "no"
# =============================================================================

CONFIRMING = {"step": "awaiting_confirmation", "leave_type": "earned_leave",
              "from_date": "2026-09-29", "to_date": "2026-09-30", "session_type_slug": None,
              "reason": "Personal work", "reason_confirmed": True, "_leave_abbreviations": {}}


@pytest.mark.parametrize("reply,reason", [
    ("change due to fever", "Fever"), ("change the reason to fever", "Fever"),
    ("update reason as family function", "Family function"), ("reason: fever", "Fever"),
    ("the reason should be doctor appointment", "Doctor appointment"),
    ("change the date to 30th", None), ("change to sick leave", None), ("yes", None),
])
def test_a_reason_change_is_read_from_the_reply(reply, reason):
    assert las._reason_change_from_reply(reply) == reason


@pytest.mark.usefixtures("_quiet")
@pytest.mark.parametrize("reply", ["no", "no thanks", "nope", "change due to fever", "yes"])
async def test_a_card_reply_stays_with_the_apply_flow(monkeypatch, reply):
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm_says("small_talk"))
    monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: dict(CONFIRMING))
    out = await classify_node.classify_node(_state(reply, last_intent="apply_leave"), _Writer())

    assert out["intent"] == "apply_leave"


async def _at_the_card(reply, slots=None):
    ok = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "Abcd Test", "is_manager": False,
        "leave_quota": {"earned_leave": {"total": 20, "remaining": 11}},
        "leave_settings": {"leave_type": [{"slug": "earned_leave", "name": "Earned Leave",
                                           "session_type_required": False}]},
        "leaves": []}}})
    cleared, writer = [], _Writer()
    with 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(side_effect=RuntimeError("no LLM in tests"))), \
            patch.object(las.leave_slot_service, "get_slots",\
                         lambda *a, **k: dict(slots or CONFIRMING)), \
            patch.object(las.leave_slot_service, "set_slots", lambda *a, **k: None), \
            patch.object(las.leave_slot_service, "clear_slots", lambda *a, **k: cleared.append(1)), \
            patch.object(las, "_today", lambda: date(2026, 9, 23)), \
            patch.object(las, "_today_in_app_timezone", lambda: date(2026, 9, 23)):
        out = await las.leave_action_node(
            {"query": reply, "intent": "apply_leave", "bearer_token": "t", "company_id": 1,
             "conversation_id": "cf", "usage_events": [], "is_manager": False}, writer)
    return out["response_text"], writer, cleared


async def test_change_due_to_fever_updates_the_reason_on_the_card():
    text, writer, cleared = await _at_the_card("change due to fever")

    assert text.startswith('Updated the reason to "Fever". To confirm:')
    assert writer.of_type("leave_confirmation")[0]["data"]["reason"] == "Fever"
    assert not cleared


@pytest.mark.parametrize("reply", ["no", "No", "nope", "no thanks"])
async def test_no_at_the_card_discards_the_request(reply):
    """A whole-message no is unambiguous -- it is the answer to the card's own
    yes/no question, so it resolves it on sight. (A no carrying a CHANGE, like
    "no but make it 3 days", is a different thing and is asked about; see
    tests/test_confirmation_gate_is_load_bearing.py.)"""
    text, writer, cleared = await _at_the_card(reply)

    assert "discarded" in text.lower()
    assert cleared
    assert writer.of_type("leave_confirmation") == []