"""QA observation (2026-10-06): these regularization questions were not
understood.

    My rejected regularization / my approved regularization / my cancelled
    regularization                                -> went to general chat
    i want to cancel my regularizatin             -> must reach the cancel flow
    what is status of my regularization (a date / a reference / a status)
                                                  -> the date and the reference
                                                     were ignored; everything listed

Routing is deterministic (classify_node._my_regularisation_view_intent), and
my_regularisation_view_node now narrows by REG reference and by date or span
as well as by status, answering a single request directly.
"""
from datetime import date

import pytest

import services.classify_node as classify_node
import services.erp_client as erp_client
import services.my_regularisation_view as view
import services.regularisation_cancel as rc


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

    async def _classify(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", _classify)


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


class TestRouting:
    @pytest.mark.parametrize("query", [
        "My rejected regularization", "my approved regularization", "my cancelled regularization",
        "my rejected regularizations", "my pending regularization",
        "what is status of my regularization", "what is the status of my regularization for 29 sept",
        "status of my regularization on 29 sept", "is my regularization for 29 sept approved",
        "what is the status of REG-131", "status of REG-131", "show REG-131", "REG-131 status",
        "regularization status", "show my rejected regularization for september",
    ])
    async def test_reaches_my_regularization_view(self, llm_says_general, query):
        assert await _route(query) == view.VIEW_INTENT

    @pytest.mark.parametrize("query", ["i want to cancel my regularizatin",
                                       "i want to cancel my regularization", "cancel REG-131"])
    async def test_cancel_reaches_the_cancel_flow(self, llm_says_general, query):
        assert await _route(query) == rc.CANCEL_INTENT

    @pytest.mark.parametrize("query", ["approve REG-142", "reject REG-142 because wrong punch"])
    async def test_a_managers_action_is_not_a_view(self, llm_says_general, query):
        assert await _route(query, is_manager=True) == "manager_regularisation_approval"


def _row(rid, day, status, **extra):
    return {"regularization_id": rid, "apply_date": day, "from_time": "09:30:00",
            "to_time": "18:30:00", "reason": "Forgot to punch out", "status_name": status,
            "employee_name": "B Geo", "employee_number": "geo3",
            "created_at": "2026-09-30 10:00:00", **extra}


ROWS = [_row(131, "2026-09-29", "pending"),
        _row(130, "2026-09-26", "rejected", rejection_reason="Biometric shows you were present"),
        _row(129, "2026-09-12", "approved"), _row(128, "2026-08-20", "cancelled")]


class Writer(list):
    def __call__(self, e):
        self.append(e)

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


@pytest.fixture
def mine(monkeypatch):
    monkeypatch.setattr(view, "_today", lambda: date(2026, 10, 6))

    async def get_my(token, status=None, **kw):
        rows = [dict(r) for r in ROWS]
        if status and status != "all":
            rows = [r for r in rows if r["status_name"] == status]
        return {"http_status": 200, "body": {"success": True, "data": {"regularizations": rows}}}

    monkeypatch.setattr(erp_client, "get_my_regularizations", get_my)


async def _ask(query, **state):
    w = Writer()
    await view.my_regularisation_view_node(
        {"query": query, "company_id": 1, "conversation_id": "c", "bearer_token": "t",
         "usage_events": [], **state}, w)
    return w.done()["data"]


class TestAnswers:
    async def test_by_reference(self, mine):
        data = await _ask("what is the status of REG-131")
        assert data["answer"] == ("Your regularization request REG-131 for 29-Sep-2026 "
                                  "(Missed punch-out, 9:30 AM to 6:30 PM) is Pending approval.")
        assert data["reference_filter"] == "REG-131" and data["total_count"] == 1

    async def test_by_reference_with_the_rejection_reason(self, mine):
        data = await _ask("status of REG-130")
        assert data["answer"].endswith("is Rejected. Rejection reason: Biometric shows you were present.")

    async def test_unknown_reference(self, mine):
        data = await _ask("status of REG-999")
        assert data["answer"] == "I couldn't find REG-999 among your regularization requests."
        assert data["found"] is False

    async def test_by_date(self, mine):
        data = await _ask("what is the status of my regularization for 29 sept")
        assert data["answer"].startswith("Your regularization request REG-131 for 29-Sep-2026")
        assert data["date_filter"] == {"from": "2026-09-29", "to": "2026-09-29"}

    async def test_yes_no_question_for_a_date(self, mine):
        data = await _ask("is my regularization for 26 sept approved")
        assert "REG-130" in data["answer"] and "is Rejected" in data["answer"]

    async def test_status_and_month_together(self, mine):
        data = await _ask("show my rejected regularization for september")
        assert [r["regularization_id"] for r in data["regularizations"]] == [130]
        assert data["status_filter"] == "rejected"

    async def test_a_month_lists_its_requests(self, mine):
        data = await _ask("my regularization requests from september")
        assert data["answer"].startswith("Here are your 3 regularization requests from "
                                         "01-Sep-2026 to 30-Sep-2026:")
        assert data["total_count"] == 3

    async def test_nothing_on_that_date(self, mine):
        data = await _ask("show my regularization for 1 oct")
        assert data["answer"] == "You don't have any regularization requests for 01-Oct-2026."

    @pytest.mark.parametrize("query,status,ids", [
        ("My rejected regularization", "rejected", [130]),
        ("my approved regularization", "approved", [129]),
        ("my cancelled regularization", "cancelled", [128]),
    ])
    async def test_each_status(self, mine, query, status, ids):
        data = await _ask(query)
        assert data["status_filter"] == status
        assert [r["regularization_id"] for r in data["regularizations"]] == ids

    async def test_a_managers_team_request_by_reference(self, mine, monkeypatch):
        async def team(token, **kw):
            return {"http_status": 200, "body": {"success": True, "data": {"regularizations": [
                _row(142, "2026-10-02", "pending", employee_name="Ayush Jio")]}}}

        monkeypatch.setattr(erp_client, "get_pending_regularizations", team)
        data = await _ask("status of REG-142", is_manager=True, is_manager_jwt=True)
        assert data["answer"].startswith("Ayush Jio's regularization request REG-142 for 02-Oct-2026")
        assert data["team_request"] is True


class TestAlreadyApplied:
    """QA bug: "What regularization requests have I applied for?" opened the
    APPLY flow ("which date(s) would you like to regularize?"). "applied",
    "submitted", "did I apply" contain the apply markers, which exclude a
    message from the view - questions about requests already made are now
    recognised before that."""

    @pytest.fixture
    def llm_says_apply(self, monkeypatch):
        # What the live classifier answered for the reported question.
        async def _no_shift(q):
            return None, 0.0, None

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

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

    @pytest.mark.parametrize("query", [
        "What regularization requests have I applied for?", "what regularizations have i applied",
        "which regularization requests did I apply for", "regularizations I have applied",
        "show the regularizations I applied", "list regularization requests i raised",
        "how many regularization requests have I submitted?", "regularization requests applied by me",
        "my applied regularizations", "did I apply for regularization on 29 sept?",
        "have I applied regularization for 29 sept",
    ])
    @pytest.mark.parametrize("is_manager", [False, True])
    async def test_is_a_view(self, llm_says_apply, query, is_manager):
        assert await _route(query, is_manager=is_manager) == view.VIEW_INTENT

    @pytest.mark.parametrize("query", [
        "I want to apply regularization", "I need to apply regularization",
        "apply regularization for 29 sept",
        "I have applied for leave, now apply regularization for 29 sept",
    ])
    async def test_a_new_request_still_applies(self, llm_says_apply, query):
        assert await _route(query) == "regularisation"

    async def test_bare_list_is_own_for_an_employee_and_team_for_a_manager(self, llm_says_apply):
        assert await _route("show regularization requests") == view.VIEW_INTENT
        assert await _route("show regularization requests", is_manager=True) == \
            "manager_regularisation_view"

    async def test_the_answer_lists_them(self, mine):
        data = await _ask("What regularization requests have I applied for?")
        assert data["answer"].startswith("Here are your 4 regularization requests:")
        assert data["total_count"] == 4


class TestWithdrawn:
    """QA bug: "Show my withdrawn regularizations" listed EVERY request.
    Withdrawn = the employee's own cancel, so it is the cancelled filter."""

    @pytest.mark.parametrize("query", [
        "Show my withdrawn regularizations", "show my withdrawn regularisation requests",
        "regularizations i withdrew", "my retracted regularizations", "my withdrawn regularization",
    ])
    async def test_routes_and_filters_to_cancelled(self, llm_says_general, query):
        assert await _route(query) == view.VIEW_INTENT
        assert view._requested_status_filter(query) == "cancelled"

    async def test_only_cancelled_rows_are_listed(self, mine):
        data = await _ask("Show my withdrawn regularizations")
        assert data["status_filter"] == "cancelled"
        assert [r["regularization_id"] for r in data["regularizations"]] == [128]
        assert data["total_count"] == 1

    async def test_a_row_erp_api_labels_withdrawn_is_included(self, monkeypatch):
        monkeypatch.setattr(view, "_today", lambda: date(2026, 10, 6))

        async def get_my(token, status=None, **kw):
            return {"http_status": 200, "body": {"success": True, "data": {"regularizations": [
                _row(1, "2026-09-01", "withdrawn"), _row(2, "2026-09-02", "cancelled"),
                _row(3, "2026-09-03", "pending")]}}}

        monkeypatch.setattr(erp_client, "get_my_regularizations", get_my)
        data = await _ask("show my withdrawn regularizations")
        assert sorted(r["regularization_id"] for r in data["regularizations"]) == [1, 2]


class TestShowAllMyRegularizationDetails:
    """QA: "Show my all regularization details" must list every request. The
    close variants "give me all my regularization details" and "show all
    regularization details" opened the APPLY flow ("which date(s) would you
    like to regularize?") - "give" was not a viewing verb and "details" not a
    list noun."""

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

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

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

    @pytest.mark.parametrize("query", [
        "Show my all regularization details", "give me all my regularization details",
        "my regularization details", "tell me all my regularization records",
        "show all of my regularizations", "my all regularization", "my regularization history",
    ])
    @pytest.mark.parametrize("is_manager", [False, True])
    async def test_is_a_view(self, llm_says_apply, query, is_manager):
        assert await _route(query, is_manager=is_manager) == view.VIEW_INTENT

    async def test_without_my_from_an_employee(self, llm_says_apply):
        assert await _route("show all regularization details") == view.VIEW_INTENT

    async def test_all_statuses_are_listed(self, mine):
        data = await _ask("Show my all regularization details")
        assert data.get("status_filter") in (None, "all")
        assert data["total_count"] == len(ROWS) == len(data["regularizations"])

    @pytest.mark.parametrize("query", ["I want to apply regularization for 29 sept",
                                       "regularize my attendance"])
    async def test_apply_still_applies(self, llm_says_apply, query):
        assert await _route(query) != view.VIEW_INTENT


class TestMisspelledCancel:
    """QA: "canel my regularization" opened the APPLY flow ("which date(s)
    would you like to regularize?") - "canel" was not a cancel verb."""

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

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

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

    @pytest.mark.parametrize("query", [
        "canel my regularization", "cancle my regularisation", "i want to canel my regularizatin",
        "canel REG-140", "cansel my regularization request", "cancl my regularization",
    ])
    async def test_reaches_the_cancel_flow(self, llm_says_apply, query):
        assert await _route(query) == rc.CANCEL_INTENT

    @pytest.mark.parametrize("word", ["canal", "panel", "camel", "candle", "channel"])
    def test_real_words_are_left_alone(self, word):
        from services.nlp_service import fold_cancel_typos
        assert fold_cancel_typos(f"the {word} regularization") == f"the {word} regularization"
