"""A normal user (is_manager = false, is_hr = false) asking for anything they
do for THEMSELVES - attendance, punches, shift, leave balance / requests,
applying or cancelling leave, regularisation, eligibility, their details -
about ANOTHER person is refused one way: the "Access restricted" card and the
single deny intent the frontend already renders the restricted UI for
(team_attendance_restricted). QA: "show adarsh leaves" came back as plain
text, "Show Adarsh attendance details?" as a bare "blocked".

The detector must never refuse a request about the caller's OWN records, so
the no-match list below matters as much as the match list.
"""

import pytest

import services.access_notice as access_notice
import services.classify_node as classify_node
import services.hr_graph as hr_graph
from services.nlp_service import extract_other_person_request

MATCH = [
    ("Show Adarsh attendance details?", "attendance", "Adarsh"),
    ("Adarsh's attendance", "attendance", "Adarsh"),
    ("priya menon's punch details", "punch_details", "Priya Menon"),
    ("what is Rohan's shift tomorrow", "shift", "Rohan"),
    ("attendance of Adarsh", "attendance", "Adarsh"),
    ("punch details of priya", "punch_details", "Priya"),
    ("leave balance of Ravi Kumar", "leave_balance", "Ravi Kumar"),
    ("Show me Rahul's leave balance", "leave_balance", "Rahul"),
    ("check rahul punch in time", "punch_details", "Rahul"),
    ("cancel Rahul's leave", "cancel_leave", "Rahul"),
    ("cancel the leave of Priya", "cancel_leave", "Priya"),
    ("apply leave on behalf of Priya", "apply_leave", "Priya"),
    ("apply Rahul's sick leave", "apply_leave", "Rahul"),
    ("show adarsh leaves", "leave_status", "Adarsh"),
    ("show Priya's leave status", "leave_status", "Priya"),
    ("what is anil's leave eligibility", "leave_eligibility", "Anil"),
    ("show rohan's regularization", "regularisation", "Rohan"),
    ("Is Rohan Mehta currently an employee here?", "employee_details", "Rohan Mehta"),
    # No possessive: each got the caller's OWN balance card (negative run, 28 Oct, #52).
    ("how many leaves does Priya have left?", "leave_balance", "Priya"),
    ("how many sick leaves has rahul got", "leave_balance", "Rahul"),
    ("how many leaves does Priya Sharma have", "leave_balance", "Priya Sharma"),
    ("does priya have any sick leave left", "leave_balance", "Priya"),
]

NO_MATCH = [
    "apply leave for tomorrow", "apply leave for personal work", "leave for my sister wedding",
    "today's attendance", "yesterday's punch details", "show my attendance", "show my leave balance",
    "my sister's wedding", "show team attendance", "my team's attendance", "what is the attendance policy",
    "show last week attendance", "show casual leave balance", "cancel my leave", "apply leave",
    "shift timing", "show attendance of this month", "punch details of today", "show sick leaves",
    "is my leave approved", "check in time today", "this week's shift", "show me attendance",
    "show me my punch details", "check leave balance", "show attendance details", "show leave status",
    "how many leaves do I have left", "how many leaves does a new joiner get", "how many leaves does one have",
    "how many leaves does an employee get", "how many leaves does my team have", "do i have any sick leave left",
    "remaining leave balance", "total leave balance", "leave balance", "what is my casual leave balance",
    "meri leave balance batao", "mera leave balance hindi me batao", "explain leave balance in japanese",
]


@pytest.mark.parametrize("query,capability,person", MATCH)
def test_someone_elses_request_is_recognised(query, capability, person):
    assert extract_other_person_request(query) == (capability, person)


@pytest.mark.parametrize("query", NO_MATCH)
def test_a_request_about_the_caller_is_never_mistaken_for_someone_elses(query):
    assert extract_other_person_request(query) is None


# =============================================================================
# The gate in classify_node
# =============================================================================

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

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

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


@pytest.fixture
def quiet(monkeypatch):
    async def _no_shift(q):
        return None, 0.0, None

    async def _llm(prompt, labels, fallback_label="unknown"):
        return "general_hr", None, False

    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm)
    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)


async def _classify(query, **role):
    writer = _Writer()
    state = {"query": query, "company_id": 1, "conversation_id": "g", "bearer_token": "t",
             "usage_events": [], **role}
    out = await classify_node.classify_node(state, writer)
    return out, writer, state


@pytest.mark.usefixtures("quiet")
@pytest.mark.parametrize("query,capability,_person", MATCH)
async def test_a_normal_user_gets_the_restricted_card_and_the_single_intent(query, capability, _person):
    out, writer, state = await _classify(query, is_manager=False, is_hr_role=False)

    assert out["intent"] == access_notice.RESTRICTED_INTENT == "team_attendance_restricted"
    notice = writer.of_type("access_notice")[0]["data"]
    assert notice["title"] == "Access restricted"
    assert notice["capability"] == capability
    assert notice["reason"] == access_notice.REASON_OTHER_EMPLOYEE
    done = writer.of_type("done")[0]
    assert done["intent"] == access_notice.RESTRICTED_INTENT
    assert done["data"]["access_notice"] == notice          # history renders the same card
    assert _person.lower() not in done["message"].lower()   # never confirms the person exists
    assert hr_graph._route_after_classify({**state, **out}) == "__end__"


@pytest.mark.usefixtures("quiet")
@pytest.mark.parametrize("role", [{"is_manager": True}, {"is_hr_role": True},
                                  {"is_manager": "unknown", "is_hr_role": "unknown"}],
                         ids=["manager", "hr", "role unknown"])
async def test_the_gate_stands_aside_unless_the_answer_is_a_definite_no(role):
    """A manager / HR user gets the feature; an unresolved role is left to the
    feature's own node and erp-api rather than refused on a guess."""
    out, writer, _ = await _classify("Show Adarsh attendance details?", **role)

    assert out["intent"] != access_notice.RESTRICTED_INTENT
    assert writer.of_type("access_notice") == []


@pytest.mark.usefixtures("quiet")
async def test_a_normal_users_own_request_is_not_touched():
    out, writer, _ = await _classify("show my attendance", is_manager=False, is_hr_role=False)

    assert out["intent"] != access_notice.RESTRICTED_INTENT
    assert writer.of_type("access_notice") == []
