"""Three reported conversations (2026-09-30).

1. Attendance follow-ups. "show my attenddacen for 24 sept" -> "show for 28
   sept" -> "Something went wrong". The misspelt message went to punch_details
   on every live run (spelt right: attendance on every run) — the LLM reads the
   raw typo; and "show for 28 sept" / "show attendcaen for 28 sept" left the
   attendance flow too: the first carries a verb, so it didn't count as a bare
   date follow-up, and "attendcaen" (two swapped pairs) wasn't folded at all.
2. Bare words -> employee search. A manager's "absent", "late", "present",
   "help", "resign" went to an employee lookup for someone called that.
3. Other people's / the team's leave balance. A manager's "show rahul leave
   balance" got the manager's OWN balance, "show me Rahul's leave balance"
   fetched Rahul's, and "team leave balance" got the team's pending requests.
   Now only HR may see anyone else's balance; everyone else is told so.
"""
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.permission_service as permission_service
from services import date_resolver
from services.nlp_service import (
    extract_other_balance_target, fold_attendance_typos, is_team_balance_request,
)


# -- 1. attendance follow-ups -------------------------------------------------------

class TestAttendanceTypos:
    @pytest.mark.parametrize("typo", ["attendcaen", "attenddacen", "attedance", "atendance", "attendence"])
    def test_folded(self, typo):
        assert fold_attendance_typos(f"show {typo} for 28 sept") == "show attendance for 28 sept"

    @pytest.mark.parametrize("word", ["attention", "attendant", "attended", "attenuated"])
    def test_real_words_are_left_alone(self, word):
        assert fold_attendance_typos(f"my {word}") == f"my {word}"


class TestDateOnlyFollowUp:
    @pytest.mark.parametrize("query", [
        "show for 28 sept", "what about 28 sept", "and for yesterday", "same for monday",
        "show me 29th", "check 28 sept", "how about last friday", "28 sept", "for 28 sept",
    ])
    def test_a_date_with_only_a_lead_in_is_a_follow_up(self, query):
        assert classify_node._is_bare_date_fragment(
            query, date_resolver.mentions_date_expression(query)) is True

    @pytest.mark.parametrize("query", [
        "show my payslip for august", "apply sick leave for tomorrow",
        "regularise my attendance for 19 september", "show my leave balance",
    ])
    def test_a_request_in_its_own_right_is_not(self, query):
        assert classify_node._is_bare_date_fragment(
            query, date_resolver.mentions_date_expression(query)) is False


@pytest.fixture
def llm_says(monkeypatch):
    """The classifier LLM answering `label` — punch_details, as it did live."""
    def set_label(label):
        async def _no_shift(q):
            return None, 0.0, None

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

        monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _classify)
    return set_label


async def _intent(query, last_intent=None, is_manager=False):
    out = await classify_node.classify_node(
        {"query": query, "company_id": 1, "conversation_id": "att-fu", "bearer_token": "t",
         "usage_events": [], "is_manager": is_manager, "last_intent": last_intent}, lambda e: None)
    return out["intent"]


class TestAttendanceRouting:
    async def test_a_misspelt_first_question_is_attendance(self, llm_says):
        llm_says("punch_details")
        assert await _intent("show my attenddacen for 24 sept") == "attendance"

    @pytest.mark.parametrize("query", ["show for 28 sept", "show attendcaen for 28 sept",
                                       "what about 29 sept"])
    async def test_follow_ups_stay_with_attendance(self, llm_says, query):
        llm_says("punch_details")
        assert await _intent(query, last_intent="attendance") == "attendance"

    async def test_a_follow_up_after_punch_details_stays_there(self, llm_says):
        llm_says("attendance")
        assert await _intent("show for 28 sept", last_intent="punch_details") == "punch_details"


# -- 2. bare words are not names ----------------------------------------------------

class TestBareWordsAreNotNames:
    @pytest.mark.parametrize("word", ["absent", "late", "present", "help", "resign", "half day",
                                      "details", "history"])
    def test_hr_words(self, word):
        assert classify_node._is_bare_person_fragment(word, False) is False

    @pytest.mark.parametrize("name", ["rahul", "abctest", "ayush jio", "rudraveer1111", "geo3"])
    def test_names_still_are(self, name):
        assert classify_node._is_bare_person_fragment(name, False) is True

    async def test_absent_after_attendance_is_not_an_employee_search(self, llm_says):
        llm_says("attendance")
        intent = await _intent("absent", last_intent="attendance", is_manager=True)
        assert intent != "manager_leave_request_lookup"


# -- 3. other people's and the team's leave balance ---------------------------------

class TestBalanceDetection:
    @pytest.mark.parametrize("query,name", [
        ("show rahul leave balance", "Rahul"),
        ("show me Rahul's leave balance", "Rahul"),
        ("leave balance of ayush jio", "Ayush Jio"),
        ("what is ayush jio leave balance", "Ayush Jio"),
        ("check rahul casual leave balance", "Rahul"),
    ])
    def test_another_person(self, query, name):
        assert extract_other_balance_target(query) == name
        assert is_team_balance_request(query) is False

    @pytest.mark.parametrize("query", [
        "team leave balance", "show my team leave balance", "what is my team's casual leave balance",
        "leave balance of my team", "all employees leave balance",
    ])
    def test_the_team(self, query):
        assert is_team_balance_request(query) is True
        assert extract_other_balance_target(query) is None

    @pytest.mark.parametrize("query", ["show my leave balance", "my casual leave balance",
                                       "leave balance", "what is my leave balance"])
    def test_ones_own(self, query):
        assert extract_other_balance_target(query) is None
        assert is_team_balance_request(query) is False


class TestOnlyHrMayViewOthersBalance:
    @pytest.mark.parametrize("state,context,allowed", [
        ({"is_hr_role": True}, None, True),
        ({}, {"is_hr": True}, True),
        ({"is_manager": True}, {"is_manager": True, "is_hr": False}, False),   # a manager: no
        ({"is_manager": False}, {"is_hr": False}, False),
        ({}, None, False),
    ])
    def test_permission(self, state, context, allowed):
        assert permission_service.may_view_others_leave_balance(state, context) is allowed


async def _balance_turn(query, *, is_manager=True, is_hr=False):
    context = {"http_status": 200, "body": {"success": True, "data": {
        "name": "Deepak Singh", "is_manager": is_manager, "is_hr": is_hr}}}
    balance_calls = []

    async def balance(token, company_id=None, conversation_id=None, employee_name=None, **kw):
        balance_calls.append(employee_name)
        return {"http_status": 200, "body": {"success": True, "data": {
            "leave_quota": {"casual_leave": {"total": 12, "remaining": 8}}}}}

    events = []
    with patch.object(las.erp_client, "get_leave_context", AsyncMock(return_value=context)), \
            patch.object(las.erp_client, "get_leave_balance", balance), \
            patch.object(las.leave_slot_service, "get_slots", lambda *a, **k: None), \
            patch.object(las.leave_slot_service, "set_slots", lambda *a, **k: True), \
            patch.object(las.leave_slot_service, "clear_slots", lambda *a, **k: True):
        out = await las.leave_action_node(
            {"query": query, "intent": "leave_balance", "bearer_token": "t", "company_id": 1,
             "conversation_id": "bal", "usage_events": [], "is_manager": is_manager,
             "is_hr_role": is_hr}, events.append)
    done = [e for e in events if e.get("type") == "done"][-1]
    return out["response_text"], done, balance_calls


class TestBalanceAnswers:
    @pytest.mark.parametrize("query", [
        "show rahul leave balance", "show me Rahul's leave balance", "leave balance of ayush jio",
        "team leave balance", "what is my team's casual leave balance",
    ])
    async def test_a_manager_is_told_to_contact_hr(self, query):
        text, done, calls = await _balance_turn(query, is_manager=True)

        assert text == las.OTHERS_BALANCE_REFUSAL
        assert "contact HR" in text
        assert done["intent"] == "team_attendance_restricted"
        assert calls == [], "no balance may be fetched for a refused request"

    async def test_hr_still_sees_a_named_employees_balance(self):
        text, done, calls = await _balance_turn("show me Rahul's leave balance",
                                                is_manager=False, is_hr=True)
        assert calls == ["Rahul"]
        assert text == "Here's Rahul's current leave balance."

    async def test_hr_is_refused_a_team_balance_too(self):
        text, _, calls = await _balance_turn("team leave balance", is_manager=False, is_hr=True)
        assert text == las.OTHERS_BALANCE_REFUSAL
        assert calls == []

    async def test_ones_own_balance_is_unchanged(self):
        text, done, calls = await _balance_turn("show my leave balance", is_manager=True)
        assert calls == [None]
        assert done["intent"] == "leave_balance"

    async def test_routing_sends_a_team_balance_to_the_balance_branch(self, llm_says):
        llm_says("HRMS_TEAM_LEAVE_QUERY")                  # what the LLM said live
        assert await _intent("team leave balance", is_manager=True) == "leave_balance"
