"""QA: "Is Rohan Mehta currently an employee here?" -> "Something went wrong".

It was labelled "unclear" and the turn ended with an error; a close variant
("does priya work here") became a LEAVE lookup for managers. Product rule:

    * an employee is told other employees' details are not shared - with no
      erp-api call about the named person at all;
    * a manager / HR / admin gets the name checked against their own team:
      found -> confirmed; several -> "which one?"; none -> "not found" plus
      the team's members, so they can see who IS on it.
"""

from unittest.mock import AsyncMock, patch

import pytest

import services.classify_node as classify_node
import services.hr_graph as hr_graph
from services.nlp_service import extract_employee_lookup_target


@pytest.mark.parametrize("query,name", [
    ("Is Rohan Mehta currently an employee here?", "Rohan Mehta"),
    ("is rohan still an employee", "Rohan"),
    ("does priya work here", "Priya"),
    ("does Priya Sharma still work with us?", "Priya Sharma"),
    ("is Rahul in my team", "Rahul"),
    ("is Ravi part of the team", "Ravi"),
    ("do we have an employee named Rohan Mehta?", "Rohan Mehta"),
    ("is there someone called Anil in my team", "Anil"),
    ("is Rohan my team member", "Rohan"),
])
def test_the_named_person_is_found(query, name):
    assert extract_employee_lookup_target(query) == name


@pytest.mark.parametrize("query", [
    "is my leave approved", "is it a holiday tomorrow", "is he an employee",
    "am i an employee here", "show my team", "is there a holiday on friday",
    "do i work here", "is today a working day",
])
def test_other_questions_name_no_one(query):
    assert extract_employee_lookup_target(query) is None


@pytest.mark.parametrize("is_manager", [False, True])
@pytest.mark.parametrize("query", [
    "Is Rohan Mehta currently an employee here?", "does priya work here", "is Rahul in my team",
])
async def test_it_routes_to_the_team_members_node_for_every_role(monkeypatch, query, is_manager):
    async def _no_shift(q):
        return None, 0.0, None

    async def _llm_unclear(prompt, labels, fallback_label="unknown"):
        return "unknown", None, True   # what happened live

    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm_unclear)
    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)
    state = {"query": query, "company_id": 1, "conversation_id": "c", "bearer_token": "t",
             "usage_events": [], "is_manager": is_manager}

    out = await classify_node.classify_node(state, lambda e: None)

    assert out.get("error") is None
    if not is_manager:
        # A normal user is refused up front by classify_node's access gate:
        # the single deny intent, the card, and the turn ends there.
        assert out["intent"] == "team_attendance_restricted"
        assert hr_graph._route_after_classify({**state, **out}) == "__end__"
        return
    assert out["intent"] == "HRMS_TEAM_MEMBERS_QUERY"
    assert hr_graph._route_after_classify({**state, **out}) == "team_members_node"


# =============================================================================
# team_members_node
# =============================================================================
# The named lookup asks /leave/pending/teams?employee_name=X - the roster
# endpoint (/leave/team/members) answers 404 on the deployed erp-api, which is
# what turned the live reply into "I'm unable to reach the HR system".

ROSTER = [
    {"employee_id": 1, "employee_name": "Rohan Mehta", "employee_number": "EMP101"},
    {"employee_id": 2, "employee_name": "Priya Sharma", "employee_number": "EMP102"},
    {"employee_id": 3, "employee_name": "Rohan Das", "employee_number": "EMP103"},
]


def _search(term):
    """erp-api's documented /leave/pending/teams?employee_name= shapes."""
    words = term.lower().split()
    hits = [r for r in ROSTER if all(w in r["employee_name"].lower().split() for w in words)]
    if hits:
        data = {"action_required": "select_employee", "search_matched": True, "employees": hits}
    else:
        data = {"action_required": "select_employee", "search_matched": False, "employees": ROSTER}
    return {"http_status": 200, "body": {"success": True, "data": data}}


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]


async def _ask(query, is_manager, response=None):
    async def _pending(token, employee_name=None, **kwargs):
        return response if response is not None else _search(employee_name)
    search = AsyncMock(side_effect=_pending)
    roster = AsyncMock(side_effect=AssertionError("the 404ing roster endpoint must not be called"))
    writer = _Writer()
    with patch.object(hr_graph.erp_client, "get_team_pending_leaves", search),             patch.object(hr_graph.erp_client, "get_team_members", roster):
        out = await hr_graph.team_members_node(
            {"query": query, "company_id": 1, "conversation_id": "t", "bearer_token": "a.e30.c",
             "usage_events": [], "is_manager": is_manager}, writer)
    return out["response_text"], search, writer


async def test_an_employee_is_refused_without_looking_anyone_up():
    text, search, writer = await _ask("Is Rohan Mehta currently an employee here?", is_manager=False)

    assert text.startswith("Sorry, I can't share information about other employees.")
    search.assert_not_called()
    assert writer.of_type("team_members") == []


async def test_a_manager_is_told_the_person_is_on_their_team():
    text, search, writer = await _ask("Is Rohan Mehta currently an employee here?", is_manager=True)

    assert text == "Yes — Rohan Mehta (EMP101) is a member of your team."
    assert search.call_args.kwargs["employee_name"] == "Rohan Mehta"
    assert [m["employee_name"] for m in writer.of_type("team_members")[0]["data"]["members"]] == ["Rohan Mehta"]


async def test_a_first_name_shared_by_two_members_asks_which_one():
    text, _, _ = await _ask("is Rohan in my team", is_manager=True)

    assert text.startswith('I found 2 people matching "Rohan" in your team:')
    assert "Rohan Mehta" in text and "Rohan Das" in text
    assert text.endswith("Which one did you mean?")


async def test_a_name_not_on_the_team_says_so_and_lists_the_team():
    text, _, writer = await _ask("does Anil work here", is_manager=True)

    assert text.startswith("I couldn't find Anil in your team.")
    for name in ("Rohan Mehta", "Priya Sharma", "Rohan Das"):
        assert name in text
    assert len(writer.of_type("team_members")[0]["data"]["members"]) == 3


async def test_an_employee_code_is_found_in_the_returned_roster():
    """erp-api searches names only, so a code comes back unmatched with the roster."""
    text, _, _ = await _ask("is EMP102 in my team", is_manager=True)

    assert text == "Yes — Priya Sharma (EMP102) is a member of your team."


async def test_erp_apis_403_still_refuses_with_the_employee_wording():
    """Role not resolved locally: erp-api's own gate decides."""
    with patch.object(hr_graph.permission_service, "may_view_team", lambda *a, **k: object()):
        text, search, _ = await _ask("Is Rohan Mehta currently an employee here?", is_manager=None,
                                     response={"http_status": 403, "body": {"success": False}})

    search.assert_called_once()
    assert text.startswith("Sorry, I can't share information about other employees.")


async def test_the_plain_roster_still_uses_the_roster_endpoint():
    ok = AsyncMock(return_value={"http_status": 200, "body": {"success": True, "data": {"members": [
        {"employee_name": "Rohan Mehta", "employee_number": "EMP101", "employee_designation": "Developer"}]}}})
    with patch.object(hr_graph.erp_client, "get_team_members", ok):
        out = await hr_graph.team_members_node(
            {"query": "show my team", "company_id": 1, "conversation_id": "t", "bearer_token": "a.e30.c",
             "usage_events": [], "is_manager": True}, lambda e: None)

    assert out["response_text"].startswith("Your team has 1 member:")


async def test_show_my_team_falls_back_when_the_roster_route_is_not_deployed():
    """/leave/team/members answers 404 on the deployed erp-api: the roster is
    read from the pending-teams search instead of reporting an outage."""
    missing = AsyncMock(side_effect=hr_graph.erp_client.ErpApiUnavailable("not found", status_code=404))

    async def _pending(token, employee_name=None, **kwargs):
        return _search(employee_name)

    with patch.object(hr_graph.erp_client, "get_team_members", missing), \
            patch.object(hr_graph.erp_client, "get_team_pending_leaves", AsyncMock(side_effect=_pending)):
        out = await hr_graph.team_members_node(
            {"query": "show my team", "company_id": 1, "conversation_id": "t", "bearer_token": "a.e30.c",
             "usage_events": [], "is_manager": True}, lambda e: None)

    assert out["response_text"].startswith("Your team has 3 members:")
    assert "unable to reach" not in out["response_text"]


async def test_a_real_outage_is_still_reported_as_one():
    down = AsyncMock(side_effect=hr_graph.erp_client.ErpApiUnavailable("connection error"))
    with patch.object(hr_graph.erp_client, "get_team_members", down):
        out = await hr_graph.team_members_node(
            {"query": "show my team", "company_id": 1, "conversation_id": "t", "bearer_token": "a.e30.c",
             "usage_events": [], "is_manager": True}, lambda e: None)

    assert "unable to reach" in out["response_text"]


# =============================================================================
# QA, round 2: typos, the card on the first reply, and the not-found headline
# =============================================================================

@pytest.mark.parametrize("query", [
    "is rohan mehta current eployee here ?",
    "Is Rohan Mehta currntly an emplyee here",
    "is rohan mehta currently an employee here",
    "is rohan mehta still employed here",
])
def test_typos_resolve_the_same_person_every_time(query):
    """Each typo used to miss, fall to the LLM, and get a different answer."""
    assert extract_employee_lookup_target(query) == "Rohan Mehta"


async def test_the_employee_refusal_streams_the_not_available_card():
    """Live it rendered as a plain bubble; the amber card appeared only after
    switching chats, rebuilt from the saved intent."""
    text, _, writer = await _ask("Is Rohan Mehta currently an employee here?", is_manager=False)

    notices = writer.of_type("access_notice")
    assert len(notices) == 1
    assert notices[0]["data"]["message"] == text


async def test_the_not_found_headline_travels_inside_the_team_card():
    """The UI shows the team card, not the reply text beside it."""
    _, _, writer = await _ask("does Anil work here", is_manager=True)

    card = writer.of_type("team_members")[0]["data"]
    assert card["matched"] is False
    assert card["search_term"] == "Anil"
    assert card["message"].startswith("I couldn't find Anil in your team.")
    assert card["total_members"] == 3


async def test_a_found_member_card_says_so_too():
    _, _, writer = await _ask("Is Rohan Mehta currently an employee here?", is_manager=True)

    card = writer.of_type("team_members")[0]["data"]
    assert card["matched"] is True
    assert card["message"] == "Yes — Rohan Mehta (EMP101) is a member of your team."


def test_team_member_answers_are_never_served_from_the_query_cache():
    """Cached, a repeat was replayed as text only - no card - from an old roster."""
    import main
    assert "HRMS_TEAM_MEMBERS_QUERY" in main._STATEFUL_QUERY_INTENTS
    assert "team_attendance_restricted" in main._STATEFUL_QUERY_INTENTS
