"""A manager reviewing the TEAM's regularization requests, as tested live
(Oct 13, screenshots):

  * "I want to view to apply regularization for my team" / "I want to view who
    apply regularization for my team" / "Show me who has apply for
    regulization" - opened the APPLY flow or the team-attendance card; they
    ask for the team's pending list.
  * "i want to accept regularization" - opened the APPLY flow; "accept" is the
    row button's own label and means approve.
  * With the list on screen: "Accept for 7 OCT" and "acceprt for 7" went to
    the LEAVE approval flow, "REG-20645" to the employee-name picker, and
    "Approve for 7 reject for 3" re-showed the list. All of them act on the
    list that is showing.
"""
import pytest

import services.classify_node as classify_node
import services.erp_client as erp_client
import services.leave_slot_service as leave_slot_service
import services.regularisation_approval as ra

# The two rows in the screenshots: Dileep Anumula, missed punch-out, 3 and 7 Oct.
REG_20644 = {
    "regularization_id": 20644, "employee_id": 7956, "employee_number": "TUS2",
    "employee_name": "Dileep Anumula", "apply_date": "2026-10-03",
    "from_time": "09:30:00", "to_time": "18:30:00", "reason": "Missed punch-out",
    "status": 0, "status_name": "pending",
}
REG_20645 = {**REG_20644, "regularization_id": 20645, "apply_date": "2026-10-07"}


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

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

    def done(self):
        return [e for e in self.events if e.get("type") == "done"][-1]


# -- Routing -----------------------------------------------------------------

class TestRouting:
    @pytest.fixture(autouse=True)
    def _no_llm_no_state(self, monkeypatch):
        async def _no_shift(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)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _no_classification)
        monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda ns, c, v: None)
        monkeypatch.setattr(leave_slot_service, "get_manager_action", lambda c, v: None)
        monkeypatch.setattr(leave_slot_service, "get_report_state", lambda c, v: None)

    async def _intent(self, query, last_intent=None, is_manager=True):
        state = {"query": query, "company_id": 1, "conversation_id": "conv-team-review",
                 "bearer_token": "t", "usage_events": [], "is_manager": is_manager,
                 "is_manager_jwt": True, "is_hr_role": False, "last_intent": last_intent}
        return (await classify_node.classify_node(state, Writer()))["intent"]

    @pytest.mark.parametrize("query", [
        "I want to view to apply regularization for my team",
        "I want to view who apply regularization for my team",
        "Show me who has apply for regulization",
        "who applied regularization in my team",
        "show regukarization for my team",
    ])
    async def test_seeing_who_applied_is_the_team_list(self, query):
        assert await self._intent(query) == "manager_regularisation_view"

    @pytest.mark.parametrize("query", [
        "i want to accept regularization",
        "i want to approve regulization for my team",
        "accept regularization for my team",
        "reject regularization for 3 oct",
    ])
    async def test_accept_and_approve_are_the_approval_flow(self, query):
        assert await self._intent(query) == "manager_regularisation_approval"

    @pytest.mark.parametrize("query", [
        "apply regularization for 3 oct",
        "I want to apply regularization",
    ])
    async def test_applying_is_still_the_apply_flow(self, query):
        assert await self._intent(query) == "regularisation"

    @pytest.mark.parametrize("last_intent", [
        "manager_regularisation_view", "regularisation_approval_choice",
        "regularisation_approval_failed",
    ])
    @pytest.mark.parametrize("query", [
        "Accept for 7 OCT", "acceprt for 7", "Approve for 7 reject for 3", "REG-20645",
        "reject the 3rd",
    ])
    async def test_acting_on_the_list_on_screen(self, query, last_intent):
        assert await self._intent(query, last_intent) == "manager_regularisation_approval"

    @pytest.mark.parametrize("query", ["7 oct", "Dileep Anumula", "the second one"])
    async def test_answering_which_one(self, query):
        assert await self._intent(query, "regularisation_approval_choice") == \
            "manager_regularisation_approval"

    @pytest.mark.parametrize("query,last_intent", [
        # Another topic, even with the list on screen.
        ("approve leave for Dileep", "manager_regularisation_view"),
        ("thanks", "regularisation_approval_choice"),
        # A bare date after the plain list may as well be an attendance question.
        ("7 oct", "manager_regularisation_view"),
        # No regularization review before it.
        ("REG-20645", "manager_leave_approval"),
    ])
    async def test_not_a_followup(self, query, last_intent):
        assert await self._intent(query, last_intent) != "manager_regularisation_approval"

    @pytest.mark.parametrize("last_intent", [
        "manager_regularisation_view", "regularisation_approval_choice",
        "regularisation_approval_success", "regularisation_rejection_confirmation",
    ])
    @pytest.mark.parametrize("query", [
        "can you refresh the list", "refresh", "reload the list please", "show it again",
        "any updates?", "update the list", "show the list again", "Refresh the requests",
        "could you refresh it", "pls reload",
    ])
    async def test_refresh_fetches_the_team_list_again(self, query, last_intent):
        assert await self._intent(query, last_intent) == "manager_regularisation_view"

    @pytest.mark.parametrize("query,last_intent", [
        # Not after the regularization review.
        ("can you refresh the list", "manager_leave_approval"),
        ("refresh", None),
        # Not a refresh at all.
        ("update my phone number", "manager_regularisation_view"),
    ])
    def test_refresh_needs_the_review_and_the_wording(self, query, last_intent):
        assert not classify_node._is_regularisation_list_refresh(query, last_intent)

    @pytest.mark.parametrize("last_intent", [None, "manager_regularisation_view"])
    @pytest.mark.parametrize("query", [
        "accept REG-20645", "approve REG-20645", "reject REG-20645", "REG-20645 accept",
        "accept reg 20645", "approve regularization REG-20645",
        "reject regularisation reg-20644", "accept regularization 20645",
    ])
    async def test_a_reference_with_a_verb(self, query, last_intent):
        assert await self._intent(query, last_intent) == "manager_regularisation_approval"

    @pytest.mark.parametrize("last_intent", [
        "manager_regularisation_view", "regularisation_approval_choice",
        "regularisation_approval_success",
    ])
    @pytest.mark.parametrize("query", ["Dileep Anumula", "dileep", "TUS2", "reject ref-20644"])
    async def test_a_name_or_reference_under_the_list(self, query, last_intent):
        """Live: "Dileep Anumula" under the list went to the employee search,
        then to that person's LEAVE requests."""
        assert await self._intent(query, last_intent) == "manager_regularisation_approval"

    @pytest.mark.parametrize("query", ["ok thanks", "thank you", "got it", "no", "cool"])
    async def test_chat_under_the_list_is_not_a_name(self, query):
        assert not classify_node._is_regularisation_approval_followup(
            query, "manager_regularisation_view", False)

    @pytest.mark.parametrize("draft", [{"entries": []}, {"entries": [{"date": "2026-10-01"}]}])
    @pytest.mark.parametrize("query", [
        "dileep anumula 3rd oct approve", "approve dileep anumula 3rd oct",
        "dileep 3rd oct reject", "approve 3rd oct", "REG-20644", "Dileep Anumula",
        "can you refresh the list",
    ])
    async def test_an_open_apply_draft_does_not_take_a_reply_to_the_list(
            self, monkeypatch, query, draft):
        """Live: with a stale "which date(s)?" draft of the manager's own still
        stored, "dileep anumula 3rd oct approve" under the team list opened
        THEIR OWN regularization for 3 Oct."""
        monkeypatch.setattr(classify_node.slot_store, "get_slots",
                            lambda ns, c, v: draft if ns == "regularization" else None)
        assert (await self._intent(query, "manager_regularisation_view")).startswith(
            "manager_regularisation_")

    async def test_the_draft_still_gets_its_own_date_when_no_list_is_showing(self, monkeypatch):
        monkeypatch.setattr(classify_node.slot_store, "get_slots",
                            lambda ns, c, v: {"entries": []} if ns == "regularization" else None)
        assert await self._intent("3rd oct", "regularization_incomplete") == "regularisation"

    async def test_a_non_manager_is_not_routed_by_the_followup(self):
        assert not classify_node._is_regularisation_approval_followup(
            "hello", "manager_regularisation_view", False)
        assert await self._intent("REG-20645", "manager_regularisation_view",
                                  is_manager=False) != "manager_regularisation_approval"


# -- The node ----------------------------------------------------------------

@pytest.fixture
def store(monkeypatch):
    actions = {}
    monkeypatch.setattr(leave_slot_service, "get_manager_action",
                        lambda c, v: actions.get((str(c), v)))
    monkeypatch.setattr(leave_slot_service, "set_manager_action",
                        lambda c, v, a: actions.__setitem__((str(c), v), a) or True)
    monkeypatch.setattr(leave_slot_service, "clear_manager_action",
                        lambda c, v: actions.pop((str(c), v), None) or True)
    return actions


@pytest.fixture
def erp(monkeypatch):
    async def _pending(token, employee_id=None, company_id=None, conversation_id=None):
        return {"http_status": 200, "body": {"success": True, "data": {
            "total_pending_regularizations": 2, "regularizations": [REG_20644, REG_20645]}}}

    async def _members(token, company_id=None, conversation_id=None):
        return {"http_status": 404, "body": {}}

    monkeypatch.setattr(erp_client, "get_pending_regularizations", _pending)
    monkeypatch.setattr(erp_client, "get_team_members", _members)


async def _run(query, last_intent="manager_regularisation_view"):
    writer = Writer()
    await ra.regularisation_approval_node({
        "query": query, "intent": ra.APPROVAL_INTENT, "usage_events": [],
        "bearer_token": "t", "company_id": 26, "conversation_id": "c",
        "is_manager_jwt": True, "is_manager": True, "last_intent": last_intent}, writer)
    return writer.done()


def _armed(store):
    return store.get(("26", "c")) or {}


class TestNode:
    @pytest.mark.parametrize("query", ["Accept for 7 OCT", "acceprt for 7", "accept the 7th"])
    async def test_a_day_picks_that_days_request(self, erp, store, query):
        done = await _run(query)
        assert done["intent"] == "regularisation_approval_confirmation"
        assert _armed(store)["regularization_id"] == 20645
        assert _armed(store)["action"] == ra.ACTION_APPROVE

    async def test_a_day_with_no_request_says_which_days_have_one(self, erp, store):
        done = await _run("accept for 9")
        assert "2026-10-03, 2026-10-07" in done["data"]["answer"]
        assert _armed(store) == {}

    async def test_approve_one_reject_another_does_the_first_and_hands_back_the_rest(
            self, erp, store):
        done = await _run("Approve for 7 reject for 3")
        assert _armed(store)["regularization_id"] == 20645
        assert _armed(store)["action"] == ra.ACTION_APPROVE
        assert 'send "reject for 3"' in done["data"]["answer"]

    async def test_reject_then_approve_rejects_first(self, erp, store):
        done = await _run("reject for 3 and approve for 7")
        assert _armed(store)["regularization_id"] == 20644
        assert _armed(store)["action"] == ra.ACTION_REJECT
        assert 'send "approve for 7"' in done["data"]["answer"]

    async def test_no_target_asks_by_date_reference_or_name(self, erp, store):
        done = await _run("i want to accept regularization")
        answer = done["data"]["answer"]
        assert done["intent"] == "regularisation_approval_choice"
        assert "date" in answer and "REG-20644" in answer and "name" in answer
        assert _armed(store) == {}

    async def test_reference_answers_the_choice(self, erp, store):
        await _run("REG-20645", last_intent="regularisation_approval_choice")
        assert _armed(store)["regularization_id"] == 20645

    async def test_a_reject_choice_keeps_rejecting(self, erp, store):
        done = await _run("reject regularization")
        assert done["intent"] == "regularisation_rejection_choice"
        await _run("7 oct", last_intent="regularisation_rejection_choice")
        assert _armed(store)["regularization_id"] == 20645
        assert _armed(store)["action"] == ra.ACTION_REJECT

    @pytest.mark.parametrize("last_intent", ["regularisation_approval_choice",
                                             "manager_regularisation_view"])
    async def test_a_name_with_two_requests_is_asked_again(self, erp, store, last_intent):
        done = await _run("Dileep Anumula", last_intent=last_intent)
        assert done["intent"] == "regularisation_approval_choice"
        assert "REG-20644" in done["data"]["answer"] and "REG-20645" in done["data"]["answer"]
        assert _armed(store) == {}

    async def test_the_question_lists_only_that_members_requests(self, erp, store, monkeypatch):
        """Under a list with another report's request too, "Dileep Anumula"
        asks about Dileep's two - not the other person's, and not leave."""
        other = {**REG_20644, "regularization_id": 30001, "employee_id": 8001,
                 "employee_number": "TUS9", "employee_name": "Asha Rao",
                 "apply_date": "2026-10-05"}

        async def _three(token, employee_id=None, company_id=None, conversation_id=None):
            return {"http_status": 200, "body": {"success": True, "data": {
                "total_pending_regularizations": 3,
                "regularizations": [REG_20644, other, REG_20645]}}}
        monkeypatch.setattr(erp_client, "get_pending_regularizations", _three)

        done = await _run("Dileep Anumula")
        answer = done["data"]["answer"]
        assert done["intent"] == "regularisation_approval_choice"
        assert "REG-20644" in answer and "REG-20645" in answer
        assert "REG-30001" not in answer and "Asha" not in answer
        assert [r["regularization_id"] for r in done["data"]["regularizations"]] == [20644, 20645]

        # ...and the next reply picks one of THOSE.
        await _run("7 oct", last_intent="regularisation_approval_choice")
        assert _armed(store)["regularization_id"] == 20645

    async def test_a_name_with_one_request_gets_its_card(self, erp, store, monkeypatch):
        async def _one(token, employee_id=None, company_id=None, conversation_id=None):
            return {"http_status": 200, "body": {"success": True, "data": {
                "total_pending_regularizations": 1, "regularizations": [REG_20644]}}}
        monkeypatch.setattr(erp_client, "get_pending_regularizations", _one)
        done = await _run("Dileep Anumula")
        assert done["intent"] == "regularisation_approval_confirmation"
        assert _armed(store)["regularization_id"] == 20644

    @pytest.mark.parametrize("query", ["dileep anumula 3rd oct approve",
                                       "approve dileep anumula 3rd oct",
                                       "Dileep Anumula 3 oct approve"])
    async def test_name_date_and_verb_pick_that_request(self, erp, store, query):
        done = await _run(query)
        assert done["intent"] == "regularisation_approval_confirmation"
        assert _armed(store)["regularization_id"] == 20644
        assert _armed(store)["action"] == ra.ACTION_APPROVE

    async def test_a_name_not_in_the_queue_is_said_so(self, erp, store):
        done = await _run("Ravi Kumar")
        assert done["data"]["answer"] == ra.NOT_IN_YOUR_TEAM_MESSAGE
        assert _armed(store) == {}

    @pytest.mark.parametrize("query,reg_id,action", [
        ("accept REG-20645", 20645, ra.ACTION_APPROVE),
        ("approve reg 20645", 20645, ra.ACTION_APPROVE),
        ("REG-20644 accept", 20644, ra.ACTION_APPROVE),
        ("reject REG-20644", 20644, ra.ACTION_REJECT),
        ("reject ref-20644", 20644, ra.ACTION_REJECT),
        ("approve regularization REG-20645", 20645, ra.ACTION_APPROVE),
        ("REG-20645", 20645, ra.ACTION_APPROVE),
    ])
    async def test_a_reference_picks_that_request(self, erp, store, query, reg_id, action):
        await _run(query)
        assert _armed(store)["regularization_id"] == reg_id
        assert _armed(store)["action"] == action

    async def test_a_reference_not_in_the_queue_changes_nothing(self, erp, store):
        done = await _run("approve REG-99999")
        assert ra.NOT_IN_YOUR_TEAM_MESSAGE in done["data"]["answer"]
        assert _armed(store) == {}

    @pytest.mark.parametrize("query", ["the second one", "approve", "accept it"])
    async def test_position_and_verbs_are_not_names(self, erp, store, query):
        done = await _run(query)
        assert done["data"]["answer"] != ra.NOT_IN_YOUR_TEAM_MESSAGE


class TestTeamListIsShown:
    """Live, once routing was fixed: "I want to view to apply regularization
    for my team" reached the node, which read "to apply" as an employee's name
    and answered "Pending regularization request was not found in your team."
    """

    @pytest.mark.parametrize("query", [
        "I want to view to apply regularization for my team",
        "I want to view who apply regularization for my team",
        "Show me who has apply for regulization",
        "show who has applied for regularisation",
        "show regukarization for my team",
    ])
    async def test_the_whole_team_list(self, erp, store, query):
        writer = Writer()
        await ra.regularisation_approval_node({
            "query": query, "intent": ra.VIEW_INTENT, "usage_events": [],
            "bearer_token": "t", "company_id": 26, "conversation_id": "c",
            "is_manager_jwt": True, "is_manager": True}, writer)
        done = writer.done()
        assert done["intent"] == ra.VIEW_INTENT, done["data"]["answer"]
        table = [e for e in writer.events if e.get("type") == "team_pending_regularization"]
        assert len(table[0]["data"]["regularizations"]) == 2

    async def test_refresh_at_the_reason_prompt_is_not_the_reason(self, erp, store):
        store[("26", "c")] = {"kind": ra.CARD_KIND, "step": "awaiting_rejection_reason",
                              "action": ra.ACTION_REJECT, "regularization_id": 20644,
                              "card": {"employee_name": "Dileep Anumula"}}
        writer = Writer()
        await ra.regularisation_approval_node({
            "query": "can you refresh the list", "intent": ra.VIEW_INTENT, "usage_events": [],
            "bearer_token": "t", "company_id": 26, "conversation_id": "c",
            "is_manager_jwt": True, "is_manager": True}, writer)
        assert writer.done()["intent"] == ra.VIEW_INTENT
        assert _armed(store) == {}

    @pytest.mark.parametrize("query,name", [
        ("show geo6 regularization requests", "geo6"),
        ("approve regularization of Dileep Anumula", "Dileep Anumula"),
        ("reject regularization for Rajesh Kumar", "Rajesh Kumar"),
    ])
    def test_real_names_are_still_read(self, query, name):
        assert ra._extract_employee_name(query) == name


class TestLongInstructions:
    """A whole instruction in one message - who, which day, the times, and
    for a rejection the reason - goes straight to its confirmation card,
    with nothing asked again."""

    @pytest.mark.parametrize("query,reg_id", [
        ("approve REG-20645 for Dileep Anumula on 7 Oct 2026 from 9:30 am to 6:30 pm, "
         "missed punch-out", 20645),
        ("please accept the regularization request of Dileep Anumula dated 07-10-2026, "
         "missed punch out from 09:30 to 18:30", 20645),
        ("I want to approve dileep anumula's regularization for 3rd october from 09:30 to "
         "18:30 as he forgot to punch out", 20644),
        ("accept regularization of Dileep Anumula for 2026-10-03 9:30 to 18:30 "
         "reason missed punch-out", 20644),
    ])
    async def test_approve(self, erp, store, query, reg_id):
        done = await _run(query, last_intent=None)
        assert done["intent"] == "regularisation_approval_confirmation", done["data"]["answer"]
        assert _armed(store)["regularization_id"] == reg_id
        assert _armed(store)["action"] == ra.ACTION_APPROVE
        assert _armed(store)["step"] == "awaiting_confirmation"

    @pytest.mark.parametrize("query,reg_id,reason", [
        ("reject Dileep Anumula's regularization for 3 oct, 09:30 to 18:30, reason: the "
         "punch record already exists for that day", 20644,
         "the punch record already exists for that day"),
        ("reject regularization REG-20644 because the employee was on leave that day", 20644,
         "the employee was on leave that day"),
        ("I want to reject dileep anumula regularization for 3rd oct from 9:30 am to 6:30 pm "
         "because he was absent the whole day", 20644, "he was absent the whole day"),
        ("please reject the regularization request of Dileep Anumula dated 07-Oct-2026 "
         "(09:30 - 18:30) since the biometric shows a punch out at 18:32", 20645,
         "the biometric shows a punch out at 18:32"),
        ("reject for 7 oct reason: punch out is already recorded", 20645,
         "punch out is already recorded"),
    ])
    async def test_reject_with_reason_goes_to_the_confirm_rejection_card(
            self, erp, store, query, reg_id, reason):
        done = await _run(query, last_intent=None)
        assert done["intent"] == "regularisation_rejection_confirmation", done["data"]["answer"]
        armed = _armed(store)
        assert armed["regularization_id"] == reg_id
        assert armed["action"] == ra.ACTION_REJECT
        assert armed["step"] == "awaiting_confirmation"
        assert armed["card"]["rejection_reason"] == reason

    @pytest.mark.parametrize("query", [
        "approve REG-20645 for Dileep Anumula on 7 Oct 2026 from 9:30 am to 6:30 pm, "
        "missed punch-out",
        "please accept the regularization request of Dileep Anumula dated 07-10-2026, "
        "missed punch out from 09:30 to 18:30",
        "reject Dileep Anumula's regularization for 3 oct, 09:30 to 18:30, reason: the "
        "punch record already exists for that day",
        "I want to reject dileep anumula regularization for 3rd oct from 9:30 am to 6:30 pm "
        "because he was absent the whole day",
    ])
    @pytest.mark.parametrize("last_intent", [None, "manager_regularisation_view"])
    async def test_routing(self, monkeypatch, query, last_intent):
        async def _no_shift(q):
            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)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _no_classification)
        monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda ns, c, v: None)
        monkeypatch.setattr(leave_slot_service, "get_manager_action", lambda c, v: None)
        monkeypatch.setattr(leave_slot_service, "get_report_state", lambda c, v: None)
        out = await classify_node.classify_node(
            {"query": query, "company_id": 1, "conversation_id": "c", "bearer_token": "t",
             "usage_events": [], "is_manager": True, "is_manager_jwt": True,
             "is_hr_role": False, "last_intent": last_intent}, Writer())
        assert out["intent"] == "manager_regularisation_approval"


@pytest.mark.parametrize("query,expected", [
    ("Approve for 7 reject for 3", ("Approve for 7", "reject for 3")),
    ("approve REG-1, reject REG-2", ("approve REG-1", "reject REG-2")),
    ("approve REG-1", ("approve REG-1", None)),
    ("reject it, do not approve", ("reject it, do not approve", None)),
])
def test_split_mixed_instruction(query, expected):
    assert ra._split_mixed_instruction(query) == expected


@pytest.mark.parametrize("query,day", [
    ("accept for 7", 7), ("reject the 3rd", 3), ("approve on 21st", 21),
    ("approve 2", None), ("approve for 2 days", None), ("approve the 2nd one", None),
])
def test_day_of_month(query, day):
    assert ra._extract_day_of_month(query) == day
