"""HA-697 — "am I eligible for regularization?" and the regularization policy
entry /api/v1/ai/leave/balance now carries in leave_settings.leave_type[]:

    {"name": "Regularization", "slug": "regularization",
     "max_apply_in_month": 10, "benefit_start": "joining",
     "regularization_allowed_days": 20}

Reported live: {"query": "show me reqgulariztion eligibility"} came back as
team_attendance_restricted ("I can only check your own leave eligibility") —
the typo was read as a PERSON'S NAME. Spelled correctly, the same question
opened the APPLY flow ("which date(s)?"). Both now reach leave_eligibility_node,
which answers with the eligibility card plus the quota.
"""
import copy

import pytest

import services.classify_node as classify_node
import services.erp_client as erp_client
import services.leave_action_service as leave_action_service
import services.leave_eligibility_service as les
import services.regularisation_node as regularisation_node
from services.nlp_service import (
    extract_other_person_request, fold_regularization_typos, is_regularisation_eligibility_query,
)

REGULARIZATION_ENTRY = {
    "name": "Regularization", "slug": "regularization", "max_apply_in_month": 10,
    "benefit_start": "joining", "regularization_allowed_days": 20,
}
CASUAL = {"name": "Casual Leave", "slug": "casual_leave", "quota": 100, "max_apply_in_month": 2,
          "benefit_start": "confirmation", "oneTypeMax": "2"}
LEAVE_SETTINGS = {
    "leave_type": [CASUAL, REGULARIZATION_ENTRY],
    "regularization_limit": "10",
    "regularization_allowed_days": 20,
}
EMPLOYEE = {"name": "Akash Jio", "doj": "2025-06-14", "emp_no": "geo2", "is_confirmed": True}


SEP_CYCLE = {"type": "monthly", "start_date": "2026-09-01", "end_date": "2026-09-30"}


def _balance_response(leave_settings=None, leave_quota=None, payroll_cycle=None):
    data = {
        "leave_quota": leave_quota if leave_quota is not None else {"casual_leave": {"total": 12, "remaining": 8}},
        "leave_settings": copy.deepcopy(leave_settings if leave_settings is not None else LEAVE_SETTINGS),
    }
    if payroll_cycle is not None:
        data["payroll_cycle"] = payroll_cycle
    return {"http_status": 200, "body": {"success": True, "data": data}}


def _reg_row(reg_id, apply_date, status_name):
    return {"regularization_id": reg_id, "apply_date": apply_date, "status_name": status_name,
            "reason": "forgot to punch out", "employee_name": "Akash Jio", "employee_number": "geo2"}


@pytest.fixture
def raw_balance(monkeypatch):
    """What erp-api answers, BEFORE the client's own processing — so every
    test here goes through the real erp_client functions. state["response"]
    is /leave/balance; state["regularizations"] the caller's own requests."""
    state = {"response": _balance_response(), "regularizations": [], "calls": []}

    async def fake_request(method, path, token, **kwargs):
        state["calls"].append(path)
        if path == "/api/v1/ai/leave/balance":
            return copy.deepcopy(state["response"])
        if path == "/api/v1/ai/regularizations":
            if state["regularizations"] is None:
                raise erp_client.ErpApiUnavailable("down")
            return {"http_status": 200, "body": {"success": True, "data": {
                "regularizations": copy.deepcopy(state["regularizations"])}}}
        raise AssertionError(f"unexpected erp-api call {path}")

    monkeypatch.setattr(erp_client, "_request", fake_request)
    return state


# -- typo folding and the other-person gate ------------------------------------

class TestRegularizationTypos:
    @pytest.mark.parametrize("typo", [
        "reqgulariztion", "regulrization", "reglarization", "regulariztion",
        "regularisaton", "reqularization", "rehularization", "regulaization",
    ])
    def test_misspellings_fold_to_the_real_word(self, typo):
        assert fold_regularization_typos(f"show me {typo} eligibility").split()[2].startswith("regulari")

    @pytest.mark.parametrize("word", [
        "regular", "regularly", "regulation", "regulations", "registration",
        "realization", "reorganization", "rehana", "reshma",
    ])
    def test_real_words_and_names_are_untouched(self, word):
        assert fold_regularization_typos(f"show {word} details") == f"show {word} details"


class TestOtherPersonGate:
    def test_the_reported_typo_is_not_read_as_a_person(self):
        assert extract_other_person_request("show me reqgulariztion eligibility") is None

    def test_a_real_name_with_a_typod_capability_is_still_caught(self):
        assert extract_other_person_request("show Ayush regulrization") == ("regularisation", "Ayush")


# -- routing ---------------------------------------------------------------------

class TestDetector:
    @pytest.mark.parametrize("query", [
        "show me reqgulariztion eligibility",
        "am I eligible for regularization",
        "regularisation eligibility",
        "what is my regularization quota",
        "what's my regularization limit",
        "am I elgible for regularization",
    ])
    def test_eligibility_and_quota_questions(self, query):
        assert is_regularisation_eligibility_query(query) is True

    @pytest.mark.parametrize("query", [
        "apply regularization", "show my regularization requests",
        "am I eligible for sick leave", "regularization policy",
    ])
    def test_everything_else(self, query):
        assert is_regularisation_eligibility_query(query) is False


class TestClassifyRouting:
    @pytest.fixture(autouse=True)
    def _no_llm(self, monkeypatch):
        async def _no_shift_verdict(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_verdict)
        monkeypatch.setattr(classify_node, "classify_intent_structured", _no_classification)
        monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda ns, c, v: None)

    async def _intent(self, query):
        out = await classify_node.classify_node(
            {"query": query, "company_id": 1, "conversation_id": "conv-reg-elig",
             "bearer_token": "t", "usage_events": [], "is_manager": False, "is_hr_role": False},
            lambda event: None)
        return out["intent"]

    @pytest.mark.parametrize("query", [
        "show me reqgulariztion eligibility",   # the reported message
        "am I eligible for regularization",
        "what is my regularization quota",
    ])
    async def test_goes_to_the_eligibility_card(self, query):
        assert await self._intent(query) == "leave_eligibility"

    @pytest.mark.parametrize("query", [
        "show my reqgulariztion",               # reported live: opened the APPLY flow
        "show my regulrization requests",
        "my pending regularisaton requests",
    ])
    async def test_a_typod_view_shows_the_callers_own_requests(self, query):
        assert await self._intent(query) == "my_regularisation_view"

    async def test_a_typod_team_view_from_a_non_manager_reaches_the_refusal(self):
        assert await self._intent("show my team reqgulariztion requests") == "manager_regularisation_view"

    @pytest.mark.parametrize("query", ["approve REG-22", "approve reg 22"])
    async def test_the_card_reference_routes_to_regularization_approval_not_leave(self, query):
        """The cards show "REG-22"; with no "regulariz" in the message it used to
        reach the LEAVE-approval hook and look up leave request 22."""
        out = await classify_node.classify_node(
            {"query": query, "company_id": 1, "conversation_id": "conv-reg-ref",
             "bearer_token": "t", "usage_events": [], "is_manager": True, "is_hr_role": False},
            lambda event: None)
        assert out["intent"] == "manager_regularisation_approval"

    async def test_a_dated_question_stays_with_the_apply_flow(self):
        assert await self._intent("am I eligible to regularize 5 sept") == "regularisation"

    async def test_apply_is_unchanged(self):
        assert await self._intent("apply regularization") == "regularisation"


# -- erp_client.get_leave_balance ------------------------------------------------

class TestPolicySplit:
    async def test_the_entry_moves_out_of_leave_type(self, raw_balance):
        result = await erp_client.get_leave_balance("tok")
        settings = result["body"]["data"]["leave_settings"]

        assert [t["slug"] for t in settings["leave_type"]] == ["casual_leave"]
        assert settings["regularization_policy"] == REGULARIZATION_ENTRY
        # Everything else in leave_settings is left as erp-api sent it.
        assert settings["regularization_allowed_days"] == 20
        assert settings["regularization_limit"] == "10"

    async def test_a_response_without_the_entry_is_untouched(self, raw_balance):
        raw_balance["response"] = _balance_response({"leave_type": [CASUAL]})
        result = await erp_client.get_leave_balance("tok")
        settings = result["body"]["data"]["leave_settings"]

        assert [t["slug"] for t in settings["leave_type"]] == ["casual_leave"]
        assert "regularization_policy" not in settings

    @pytest.mark.parametrize("body", [None, {}, {"data": None}, {"data": {"leave_settings": None}},
                                      {"data": {"leave_settings": {"leave_type": None}}}])
    async def test_odd_shapes_never_raise(self, monkeypatch, body):
        async def fake_request(*args, **kwargs):
            return {"http_status": 200, "body": body}

        monkeypatch.setattr(erp_client, "_request", fake_request)
        await erp_client.get_leave_balance("tok")

    async def test_apply_leave_no_longer_offers_regularization_as_a_leave(self, raw_balance):
        known = await leave_action_service._fetch_known_leave_types(erp_client, "tok", 1, "c")
        assert "regularization" not in [t["slug"] for t in known]


# -- leave_eligibility_node -------------------------------------------------------

async def _ask(monkeypatch, query, employee=EMPLOYEE):
    async def fake_context(*args, **kwargs):
        return {"http_status": 200, "body": {"success": True, "data": dict(employee)}}

    monkeypatch.setattr(les.erp_client, "get_leave_context", fake_context)
    monkeypatch.setattr(les.leave_eligibility_clarify_state, "clear_state", lambda *a: None)
    monkeypatch.setattr(les.leave_eligibility_clarify_state, "set_state", lambda *a: None)
    events = []
    await les.leave_eligibility_node({"query": query, "usage_events": []}, events.append)
    done = [e for e in events if e["type"] == "done"][-1]
    cards = [e["data"] for e in events if e["type"] == "leave_eligibility"]
    return done, cards


class TestRegularizationEligibilityCard:
    async def test_eligible_from_joining_with_the_quota(self, monkeypatch, raw_balance):
        done, cards = await _ask(monkeypatch, "show me reqgulariztion eligibility")

        assert done["intent"] == "leave_eligibility"
        answer = done["data"]["answer"]
        assert answer.startswith("Eligible — Regularization is available from your date of joining")
        assert "up to 10 regularizations a month" in answer
        assert "for dates up to 20 days back" in answer
        assert "Pending and approved requests count toward this limit." in answer
        assert done["data"]["title"] == "You're eligible for Regularization"

        (card,) = cards
        (result,) = card["results"]
        assert result["leave_type"]["slug"] == "regularization"
        assert result["leave_type"]["leave_code"] == "REG"
        assert result["eligible"] is True
        assert result["reason_code"] == "AVAILABLE_FROM_JOINING"
        assert result["policy"]["max_apply_in_month"] == 10
        assert result["policy"]["regularization_allowed_days"] == 20
        # No payroll_cycle in this response: the limit alone, no guessed usage.
        assert result["quota"] == {
            "limit": 10, "period": "month", "cycle": None, "used": None, "remaining": None,
            "counted_statuses": ["pending", "approved"], "usage_available": False,
        }
        # Same done-data shape as the leave-type card.
        assert done["data"]["results"] == card["results"]
        assert done["data"]["employee"]["emp_code"] == "geo2"

    async def test_usage_is_shown_once_the_backend_sends_it(self, monkeypatch, raw_balance):
        raw_balance["response"] = _balance_response(
            leave_quota={"casual_leave": {"total": 12, "remaining": 8},
                         "regularization": {"total": 10, "remaining": 7}})
        done, cards = await _ask(monkeypatch, "what is my regularization quota")

        assert "You've used 3 of 10 so far this cycle (7 left)." in done["data"]["answer"]
        quota = cards[0]["results"][0]["quota"]
        assert (quota["used"], quota["remaining"], quota["usage_available"]) == (3, 7, True)

    async def test_usage_is_counted_inside_the_payroll_cycle(self, monkeypatch, raw_balance):
        raw_balance["response"] = _balance_response(payroll_cycle=SEP_CYCLE)
        raw_balance["regularizations"] = [
            _reg_row(1, "2026-09-14", "pending"),     # counts
            _reg_row(2, "2026-09-03", "approved"),    # counts
            _reg_row(3, "2026-09-10", "cancelled"),   # never counts
            _reg_row(4, "2026-09-11", "rejected"),    # never counts
            _reg_row(5, "2026-08-31", "approved"),    # previous cycle
        ]
        done, cards = await _ask(monkeypatch, "what is my regularization quota")

        assert "You've used 2 of 10 for Sep 2026 (8 left)." in done["data"]["answer"]
        quota = cards[0]["results"][0]["quota"]
        assert (quota["used"], quota["remaining"], quota["usage_available"]) == (2, 8, True)
        assert quota["cycle"]["start_date"] == "2026-09-01"
        assert quota["cycle"]["end_date"] == "2026-09-30"

    async def test_a_21st_to_20th_cycle(self, monkeypatch, raw_balance):
        raw_balance["response"] = _balance_response(payroll_cycle={
            "type": "monthly", "start_date": "2026-09-21", "end_date": "2026-10-20"})
        raw_balance["regularizations"] = [_reg_row(1, "2026-09-20", "pending"),   # previous cycle
                                          _reg_row(2, "2026-09-21", "pending")]   # this one
        done, _ = await _ask(monkeypatch, "what is my regularization quota")

        assert "You've used 1 of 10 for 21 Sep – 20 Oct 2026 (9 left)." in done["data"]["answer"]

    async def test_an_unreadable_request_list_shows_the_limit_alone(self, monkeypatch, raw_balance):
        raw_balance["response"] = _balance_response(payroll_cycle=SEP_CYCLE)
        raw_balance["regularizations"] = None
        done, cards = await _ask(monkeypatch, "what is my regularization quota")

        assert "You've used" not in done["data"]["answer"]
        assert "up to 10 regularizations a month" in done["data"]["answer"]
        assert cards[0]["results"][0]["quota"]["usage_available"] is False

    async def test_a_backend_usage_figure_wins_and_skips_the_count(self, monkeypatch, raw_balance):
        raw_balance["response"] = _balance_response(
            payroll_cycle=SEP_CYCLE,
            leave_quota={"regularization": {"total": 10, "remaining": 4}})
        done, _ = await _ask(monkeypatch, "what is my regularization quota")

        assert "You've used 6 of 10" in done["data"]["answer"]
        assert "/api/v1/ai/regularizations" not in raw_balance["calls"]

    async def test_confirmation_rule_on_probation_is_not_eligible(self, monkeypatch, raw_balance):
        raw_balance["response"] = _balance_response({
            "leave_type": [CASUAL, {**REGULARIZATION_ENTRY, "benefit_start": "confirmation"}]})
        done, cards = await _ask(monkeypatch, "am I eligible for regularization",
                                 employee={**EMPLOYEE, "is_confirmed": False,
                                           "probation_end_date": "2026-12-31"})

        assert done["data"]["answer"].startswith("Not Eligible — Employees currently under probation")
        assert "a month" not in done["data"]["answer"]
        assert cards[0]["results"][0]["eligible"] is False

    async def test_no_policy_entry_fails_closed_without_a_card(self, monkeypatch, raw_balance):
        raw_balance["response"] = _balance_response({"leave_type": [CASUAL]})
        done, cards = await _ask(monkeypatch, "am I eligible for regularization")

        assert "regularization policy isn't available" in done["data"]["answer"]
        assert cards == []

    async def test_all_leave_types_no_longer_lists_regularization(self, monkeypatch, raw_balance):
        done, cards = await _ask(monkeypatch, "what leaves am I eligible for")

        assert "Regularization" not in done["data"]["answer"]
        assert all(r["leave_type"]["slug"] != "regularization"
                   for card in cards for r in card["results"])


# -- the apply flow's back-date window ----------------------------------------------

class TestWindowDays:
    async def test_read_from_the_policy_entry(self, raw_balance):
        raw_balance["response"] = _balance_response({
            "leave_type": [{**REGULARIZATION_ENTRY, "regularization_allowed_days": 15}],
            "regularization_allowed_days": 20})
        days = await regularisation_node._get_regularization_window_days(
            bearer_token="tok", company_id=1, conversation_id="c")
        assert days == 15

    async def test_monthly_limit_is_never_read_as_a_window(self, raw_balance):
        """regularization_limit is the monthly REQUEST quota ("10"), not days."""
        raw_balance["response"] = _balance_response({"leave_type": [], "regularization_limit": "10"})
        days = await regularisation_node._get_regularization_window_days(
            bearer_token="tok", company_id=1, conversation_id="c")
        assert days is None
