"""QA, one conversation:

    show my apply leaves     -> "Just to make sure I get you the right info..."
    show my apply leave      -> "What type of leave would you like to apply for?"  (a NEW application)
    show my apporved leaves  -> "Just to make sure..." again
    Show my cancel leave     -> "I've discarded the leave application we were filling in"

Each turn left state the next one tripped over: "apply" was read as the
apply-leave ACTION, the accidental draft it opened then swallowed "cancel" as
"discard this draft", and misspelt status words matched no list filter.

Plus a product rule: a question that says "eligible" is answered by the
leave_eligibility check, never by the policy documents.
"""

import pytest

import services.classify_node as classify_node
import services.hr_graph as hr_graph
import services.leave_action_service as leave_action_service
from services.nlp_service import fast_classify, is_leave_listing_request


# =============================================================================
# "show my <status> leaves" is a request to VIEW the list
# =============================================================================

LISTING_REQUESTS = [
    "show my apply leaves", "show my apply leave", "show me my appy leaves",
    "show my applied leaves", "show my aplied leaves",
    "show my apporved leaves", "show my approved leaves",
    "Show my cancel leave", "show my canel leaves", "show my canclled leaves",
    "show my cancelled leaves", "list my cancelled leave requests",
    "show my applied leaves for this month", "can you show my approved leaves?",
]

NOT_LISTING_REQUESTS = {
    "apply leave": "apply_leave",
    "apply casual leave tomorrow": "apply_leave",
    "i want to apply leave": "apply_leave",
    "cancel my leave": "cancel_leave",
    "show my leave balance": "leave_balance",
    "show my leaves left": "leave_balance",
    "show my team leaves": "HRMS_TEAM_LEAVE_QUERY",
    "show my team pending leaves": "HRMS_TEAM_LEAVE_QUERY",
}


@pytest.mark.parametrize("query", LISTING_REQUESTS)
def test_a_listing_request_is_leave_status(query):
    assert is_leave_listing_request(query) is True
    assert fast_classify(query)[0] == "leave_status"


@pytest.mark.parametrize("query,intent", NOT_LISTING_REQUESTS.items())
def test_actions_balance_and_team_queries_keep_their_intent(query, intent):
    assert is_leave_listing_request(query) is False
    assert fast_classify(query)[0] == intent


@pytest.mark.parametrize("query,status", [
    ("show my apporved leaves", "approved"),
    ("Show my cancel leave", "cancelled"),
    ("show my canel leaves", "cancelled"),
    ("show my canclled leaves", "cancelled"),
    ("show my pendng leaves", "pending"),
    ("show my rejcted leaves", "rejected"),
])
def test_a_misspelt_status_word_is_that_filter(query, status):
    assert leave_action_service._extract_status_filter(query) == status


@pytest.mark.parametrize("query", [
    "show my apply leaves", "show my appy leaves", "show my aplied leaves", "show my applied leaves",
])
def test_apply_and_its_typos_mean_all_applied_requests(query):
    assert leave_action_service._is_all_leaves_request(query) is True


@pytest.mark.parametrize("query", [
    "show my casual leaves", "show my earned leaves", "show my annual leaves",
    "show my sick leaves", "show my maternity leaves", "show my special leaves",
])
def test_a_leave_type_is_not_mistaken_for_a_status(query):
    """The fuzzy match must not turn a type name into a status filter."""
    assert leave_action_service._extract_status_filter(query) is None


@pytest.mark.parametrize("reply,resolved", [
    ("apporved", "approved"), ("canel", "cancelled"), ("cancel", "cancelled"),
    ("apply", "all"), ("appy ones", "all"),
])
def test_a_typo_reply_to_the_which_leaves_question_resolves(reply, resolved):
    assert leave_action_service._resolve_leave_history_clarification(reply) == resolved


# =============================================================================
# With state left behind by earlier turns
# =============================================================================

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

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


@pytest.fixture
def _no_llm(monkeypatch):
    async def _no_shift_verdict(query):
        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_verdict)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _no_classification)
    monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda *a, **k: None)


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


@pytest.mark.usefixtures("_no_llm")
class TestWithAnApplyDraftOpen:

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

    @pytest.fixture(autouse=True)
    def _draft(self, monkeypatch):
        monkeypatch.setattr(classify_node.leave_slot_service, "get_slots",
                            lambda *a, **k: self.DRAFT)

    @pytest.mark.parametrize("query", ["Show my cancel leave", "show my cancelled leaves",
                                       "show my apporved leaves"])
    async def test_a_listing_request_is_answered_not_treated_as_a_discard(self, query):
        out = await classify_node.classify_node(_state(query), _Writer())

        assert out["intent"] == "leave_status"

    async def test_a_real_discard_still_discards(self):
        out = await classify_node.classify_node(_state("cancel"), _Writer())

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


@pytest.mark.usefixtures("_no_llm")
class TestWithTheWhichLeavesQuestionPending:

    @pytest.fixture(autouse=True)
    def _pending(self, monkeypatch):
        monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: None)
        monkeypatch.setattr(classify_node.leave_history_clarify_state, "get_state",
                            lambda *a, **k: {"leave_type_slug": None, "date_from": None,
                                             "date_to": None})
        monkeypatch.setattr(classify_node.leave_history_clarify_state, "clear_state",
                            lambda *a, **k: None)

    async def test_show_my_apply_leave_does_not_start_an_application(self):
        out = await classify_node.classify_node(_state("show my apply leave"), _Writer())

        assert out["intent"] == "leave_status"


# =============================================================================
# "eligible" goes to the eligibility check, not the policy documents
# =============================================================================

def _route(intent, query):
    return hr_graph._route_after_classify({"intent": intent, "query": query,
                                           "is_hr": True, "error": None})


@pytest.mark.parametrize("intent,query", [
    ("leave_eligibility", "I am elgible for Casual Leave"),
    ("leave_eligibility", "am i eligible for sick leave if i joined last month"),
    ("policy", "what is the eligibility for earned leave"),
    ("leave_policy", "who is eligible for maternity leave"),
    ("policy", "am i elligible for earned leave"),
])
def test_an_eligibility_question_reaches_the_eligibility_check(intent, query):
    assert _route(intent, query) == "leave_eligibility_node"


def test_a_policy_question_without_eligibility_still_reaches_the_documents():
    assert _route("policy", "what is the sick leave policy") == "policy_rag_node"


def test_a_conditional_question_with_no_eligibility_word_still_goes_to_policy():
    """The existing reroute is kept for what it was built for."""
    assert _route("leave_eligibility", "can i take leave without approval") == "policy_rag_node"


# =============================================================================
# Policy questions that read like record lookups (QA screenshots, 2026-09-23)
# =============================================================================

POLICY_QUESTIONS = [
    "How many WFH days can I take in a month?",
    "How many WFH days can I take in a month?in my policy",
    "How many paid leaves do I get in a year?",
    "how many casual leaves can i take per month",
    "what is my notice period",
    "Total Company Leave",
    "company leave policy",
    "What is my leave policy?",
]


@pytest.mark.parametrize("query", POLICY_QUESTIONS)
def test_a_policy_question_is_labelled_policy(query):
    assert fast_classify(query)[0] == "policy"


@pytest.mark.parametrize("query,intent", [
    ("how many leaves do i have left", "leave_balance"),
    ("how many leaves have i taken this year", "leave_balance"),
    ("how many leaves did i apply in a month", "leave_balance"),
    ("how many casual leaves am i eligible for in a year", "leave_eligibility"),
    ("what is the notice period of the candidate", "recruitment"),
])
def test_record_and_eligibility_questions_keep_their_intent(query, intent):
    assert fast_classify(query)[0] == intent


@pytest.mark.parametrize("query", POLICY_QUESTIONS + ["Can I take leave without approval?"])
def test_every_policy_question_reaches_the_documents(query):
    assert _route("policy", query) == "policy_rag_node"


class TestTheOwnershipGuardOnlyJudgesAttendance:
    """ "Total Company Leave" was refused with "I can only share attendance
    details for your own account" - the guard ran on every query and its
    classifier labelled anything company-wide as "group"."""

    @pytest.fixture
    def guard(self, monkeypatch):
        import services.ownership_guard as og
        calls = []

        async def _group(prompt, labels, fallback_label="unknown"):
            calls.append(prompt)
            return "group", None, True

        monkeypatch.setattr(og, "classify_intent_structured", _group)
        monkeypatch.setattr(og.permission_service, "may_view_team", lambda *a, **k: False)
        return og, calls

    @pytest.mark.parametrize("query", ["Total Company Leave", "what is my leave policy",
                                       "how many holidays does the company have"])
    async def test_a_non_attendance_question_is_never_judged(self, guard, query):
        og, calls = guard
        out = await og.ownership_guard_node(
            {"query": query, "bearer_token": "a.e30.c", "is_manager": False}, lambda e: None)

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

    @pytest.mark.parametrize("query", ["what is John's attendance this month",
                                       "when did Ravi punch in yesterday",
                                       "show Priya check in time"])
    async def test_someone_elses_attendance_is_still_blocked(self, guard, query):
        og, _ = guard
        out = await og.ownership_guard_node(
            {"query": query, "bearer_token": "a.e30.c", "is_manager": False}, lambda e: None)

        assert out["blocked"] is True


# =============================================================================
# QA: "show my pendng leaves" got "Just to make sure I get you the right
# info..." - on a build without the typo-tolerant status words (589ef53).
# Pinned end to end: the typo is answered exactly like the correct spelling.
# =============================================================================

@pytest.mark.parametrize("query", ["show my pendng leaves", "show my pedning leaves",
                                   "show my pendig leave", "show my pending leaves"])
async def test_a_misspelt_pending_is_answered_not_asked_back(monkeypatch, query):
    from unittest.mock import AsyncMock
    leaves = [{"id": 16313, "leave_type": "Short Leave", "leave_type_slug": "short_leave",
               "from_date": "2026-09-17", "to_date": "2026-09-17", "status_name": "pending",
               "total_days": 1}]
    ok = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {
        "name": "T", "is_manager": False, "leaves": leaves}}})
    monkeypatch.setattr(leave_action_service.erp_client, "get_leave_context", ok)
    monkeypatch.setattr(leave_action_service.erp_client, "get_applied_leaves", ok)
    monkeypatch.setattr(leave_action_service.leave_slot_service, "get_slots", lambda *a, **k: None)
    events = []

    out = await leave_action_service.leave_action_node(
        {"query": query, "intent": "leave_status", "bearer_token": "t", "company_id": 1,
         "conversation_id": "p", "usage_events": [], "is_manager": False,
         "has_date_expression": False}, events.append)

    assert "Just to make sure" not in out["response_text"]
    assert "pending" in out["response_text"].lower()
    assert "Short Leave" in out["response_text"]
