"""Nobody applies a regularization for someone else's attendance - not a
manager, not HR. Live: "i want to apply regyalrization for my team" opened the
caller's OWN apply form ("Sure - which date(s) would you like to regularize?").

Refused in two places:
  * classify_node, deterministically, for team / possessive / on-behalf wording;
  * the apply flow, when its extraction names another employee ("apply
    regularization for Dileep Anumula") - a word list cannot tell a name from
    "for missing punch".
"""
import json
from unittest.mock import AsyncMock, patch

import pytest

import services.classify_node as classify_node
import services.leave_slot_service as leave_slot_service
import services.ownership_guard as ownership_guard
import services.regularisation_node as reg
import services.slot_store as slot_store
from services.regularisation_guards import (
    APPLY_FOR_OTHERS_INTENT,
    APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE,
)


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]


@pytest.fixture
def no_llm(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 _classify(query, is_manager=True):
    writer = Writer()
    out = await classify_node.classify_node(
        {"query": query, "company_id": 1, "conversation_id": "conv-apply-others",
         "bearer_token": "t", "usage_events": [], "is_manager": is_manager,
         "is_manager_jwt": True, "is_hr_role": False}, writer)
    return out, writer


class TestClassify:
    @pytest.mark.parametrize("is_manager", [True, False])
    @pytest.mark.parametrize("query", [
        "i want to apply regyalrization for my team",
        "apply regularization for my team",
        "I want to apply regularization for my team members",
        "raise regularization for my reportees",
        "apply regularization on behalf of Dileep",
        "apply Dileep's regularization",
        "submit regularisation for my team for 3 oct",
    ])
    async def test_refused_with_the_apply_for_yourself_message(self, no_llm, query, is_manager):
        out, writer = await _classify(query, is_manager)
        # A non-manager naming a person meets the earlier "someone else's
        # records" gate first - its card and intent, the same sentence.
        assert out["intent"] in (APPLY_FOR_OTHERS_INTENT,
                                 classify_node.access_notice.RESTRICTED_INTENT)
        if is_manager:
            assert out["intent"] == APPLY_FOR_OTHERS_INTENT
        assert writer.done()["data"]["answer"] == APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE
        assert "for yourself" in APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE

    @pytest.mark.parametrize("query", [
        "apply regularization for 3 oct",
        "apply regularization for missing punch",
        "apply regularization for me",
        "apply regularization for yesterday's missed punch",
        "I want to apply regularization",
    ])
    async def test_applying_for_yourself_is_untouched(self, no_llm, query):
        out, _ = await _classify(query)
        assert out["intent"] == "regularisation"

    @pytest.mark.parametrize("query,intent", [
        ("I want to view to apply regularization for my team", "manager_regularisation_view"),
        ("show me who applied regularization in my team", "manager_regularisation_view"),
        ("approve regularization for my team", "manager_regularisation_approval"),
    ])
    async def test_seeing_or_approving_the_team_is_not_applying(self, no_llm, query, intent):
        out, _ = await _classify(query)
        assert out["intent"] == intent

    def test_the_graph_stops_after_the_refusal(self):
        import services.hr_graph as hr_graph
        assert hr_graph._route_after_classify(
            {"intent": APPLY_FOR_OTHERS_INTENT, "response_text": "x"}) == hr_graph.END


# -- The apply flow: a named other employee -----------------------------------

def _llm(employee_name, entries=None):
    return {"choices": [{"message": {"content": json.dumps(
        {"action": "provide_info", "entries": entries or [], "employee_name": employee_name})}}]}


async def _apply_turn(query, employee_name, entries=None, conversation_id="conv-apply-other"):
    writer = Writer()
    with patch("services.slot_flow._call_llm",
               new=AsyncMock(return_value=_llm(employee_name, entries))):
        await reg.regularisation_node(
            {"query": query, "company_id": "apply-other-co", "conversation_id": conversation_id,
             "bearer_token": "t", "usage_events": []}, writer)
    return writer.done()


class TestApplyFlow:
    @pytest.fixture(autouse=True)
    def _no_erp(self, monkeypatch):
        """Nothing here may reach erp-api - it is the extraction's result
        that decides these cases."""
        monkeypatch.setattr(reg, "_get_shift_details", AsyncMock(return_value=None))
        monkeypatch.setattr(reg, "_get_attendance_prefill",
                            AsyncMock(return_value={"slot_prefill": {}, "preview": {}}))
        if hasattr(reg, "_check_duplicate_date"):
            monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
                "outcome": "none", "message": None, "existing_request": None, "rows": []}))
        monkeypatch.setattr(reg, "_get_regularization_settings", AsyncMock(return_value={
            "available": True, "window_days": None, "limit": None, "cycle": None}))
        posts = AsyncMock(side_effect=AssertionError("nothing may be submitted"))
        monkeypatch.setattr(reg.attendance_client, "post_regularization", posts)
        monkeypatch.setattr(reg.attendance_client, "get_my_regularizations",
                            AsyncMock(return_value={"http_status": 200, "body": {"data": []}}))

    async def test_a_named_other_employee_is_refused_and_no_draft_is_kept(self):
        done = await _apply_turn("apply regularization for Dileep Anumula", "Dileep Anumula")
        assert done["data"]["answer"] == APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE
        assert done["intent"] == "regularization_other_employee"
        assert not slot_store.get_slots("regularization", "apply-other-co", "conv-apply-other")

    async def test_with_a_date_too(self):
        done = await _apply_turn("apply regularization for Dileep for 3 oct", "Dileep",
                                 entries=[{"date": "2026-10-03"}], conversation_id="conv-2")
        assert done["data"]["answer"] == APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE

    async def test_the_callers_own_request_still_asks_for_the_date(self):
        done = await _apply_turn("apply regularization", None, conversation_id="conv-3")
        assert "which date" in done["data"]["answer"].lower()


class TestNonManagerGuardWording:
    async def test_a_non_manager_naming_someone_gets_the_apply_wording(self, monkeypatch):
        async def _other(prompt, labels, fallback_label="unknown"):
            return "other", None, True
        monkeypatch.setattr(ownership_guard, "classify_intent_structured", _other)
        monkeypatch.setattr(ownership_guard.permission_service, "may_view_team",
                            lambda state, **kw: False)
        writer = Writer()
        out = await ownership_guard.ownership_guard_node(
            {"query": "apply regularization for Ayush Jio", "bearer_token": None}, writer)
        assert out["blocked"] is True
        event = [e for e in writer.events if e.get("type") == "guardrail"][0]
        assert event["message"] == APPLY_FOR_OTHERS_NOT_ALLOWED_MESSAGE
