"""services/regularisation_display.py — the HA-697 card fields derived from a
GET /api/v1/ai/regularizations row, and where they reach the user."""
import pytest

import services.regularisation_approval as regularisation_approval
import services.regularisation_display as display
from services.regularisation_display import (
    LATE_ARRIVAL, MISSED_PUNCH_IN, MISSED_PUNCH_OUT, ON_DUTY, REGULARIZATION_TYPES,
)

# Verbatim from the live payload.
LIVE_ROW = {
    "regularization_id": 22, "applied_to": "ABC Testing", "action_by": None,
    "created_at": "2026-08-31", "employee_id": 674, "employee_number": "geo2",
    "employee_name": "Akash Jio", "apply_date": "2026-08-15",
    "from_time": "10:00:00", "to_time": "19:00:00", "reason": "regularize",
    "status": 0, "status_name": "pending",
}


def test_the_four_types_are_the_designs_chips_in_order():
    assert REGULARIZATION_TYPES == ("Missed punch-out", "Missed punch-in", "Late arrival", "On-duty")


class TestTypeFromReason:
    @pytest.mark.parametrize("reason,expected", [
        ("Forgot to punch out", MISSED_PUNCH_OUT),
        ("missed check-out", MISSED_PUNCH_OUT),
        ("out punch not recorded", MISSED_PUNCH_OUT),
        ("Forgot to punch in", MISSED_PUNCH_IN),
        ("check in missing", MISSED_PUNCH_IN),
        ("login issue", MISSED_PUNCH_IN),
        ("I was a few minutes late today due to excessive traffic", LATE_ARRIVAL),
        ("punched in late", LATE_ARRIVAL),
        ("meeting", ON_DUTY),
        ("client visit", ON_DUTY),
        ("on duty at site", ON_DUTY),
        # The punch wins over on-duty wording in the same reason.
        ("forgot to punch out after the client meeting", MISSED_PUNCH_OUT),
    ])
    def test_reason_maps_to_a_type(self, reason, expected):
        assert display.regularization_type_from_reason(reason) == expected
        assert display.regularization_type(reason) == expected

    @pytest.mark.parametrize("reason", ["regularize", "missed punch", "Testing", "demo test", "", None])
    def test_a_reason_naming_no_type_falls_into_the_default(self, reason):
        assert display.regularization_type_from_reason(reason) is None
        assert display.regularization_type(reason) == display.DEFAULT_REGULARIZATION_TYPE
        assert display.DEFAULT_REGULARIZATION_TYPE == MISSED_PUNCH_OUT


class TestEnrichRow:
    def test_live_row(self):
        row = display.enrich_row(LIVE_ROW)

        assert row["reference_id"] == "REG-22"
        assert row["applied_by"] == "Akash Jio (geo2)"
        assert row["applied_on"] == "2026-08-31"
        assert row["applied_on_display"] == "31-Aug-2026"
        assert row["apply_date_display"] == "15-Aug-2026"
        assert row["status_label"] == "Pending"
        assert row["card_status_label"] == "Pending approval"
        # "regularize" names no type: the default, and marked as such.
        assert row["regularization_type"] == MISSED_PUNCH_OUT
        assert row["regularization_type_source"] == "default"

    def test_a_type_from_the_reason_is_marked_as_such(self):
        row = display.enrich_row({**LIVE_ROW, "reason": "meeting"})
        assert row["regularization_type"] == ON_DUTY
        assert row["regularization_type_source"] == "reason"

    def test_every_row_falls_into_one_of_the_four_types(self):
        for reason in ("regularize", "missed punch", "meeting", "test", "demo test", "late", None):
            assert display.enrich_row({**LIVE_ROW, "reason": reason})["regularization_type"]                 in REGULARIZATION_TYPES

    def test_every_erp_key_is_kept_unchanged(self):
        row = display.enrich_row(LIVE_ROW)
        assert {k: row[k] for k in LIVE_ROW} == LIVE_ROW
        assert "reference_id" not in LIVE_ROW  # the input is not mutated

    @pytest.mark.parametrize("status_name,status,label", [
        ("approved", 1, "Approved"), ("cancelled", None, "Cancelled"),
        ("canceled", None, "Cancelled"), ("rejected", None, "Rejected"),
        (None, 0, "Pending"), (None, 1, "Approved"),
    ])
    def test_status_label(self, status_name, status, label):
        row = display.enrich_row({**LIVE_ROW, "status_name": status_name, "status": status})
        assert row["status_label"] == label
        assert row["card_status_label"] == ("Pending approval" if label == "Pending" else label)

    def test_missing_fields_are_none_not_invented(self):
        row = display.enrich_row({"apply_date": "2026-08-15"})
        assert row["reference_id"] is None
        assert row["applied_by"] is None
        assert row["applied_on"] is None
        assert row["applied_on_display"] is None

    def test_applied_by_falls_back_to_whichever_half_exists(self):
        assert display.applied_by({"employee_name": "Akash Jio"}) == "Akash Jio"
        assert display.applied_by({"employee_number": "geo2"}) == "geo2"


class TestManagerQueue:
    @pytest.mark.parametrize("query", ["approve REG-22", "approve reg 22", "approve Reg-22 please"])
    def test_the_shown_reference_is_understood(self, query):
        assert regularisation_approval._extract_request_id(query) == 22

    async def test_team_rows_carry_the_card_fields(self, monkeypatch):
        async def fake_list(token, employee_id=None, company_id=None, conversation_id=None):
            return {"http_status": 200, "body": {"success": True, "data": {
                "total_pending_regularizations": 1, "regularizations": [LIVE_ROW]}}}

        monkeypatch.setattr(regularisation_approval.erp_client, "get_pending_regularizations", fake_list)
        monkeypatch.setattr(regularisation_approval.leave_slot_service, "get_manager_action",
                            lambda c, k: None)
        events = []
        await regularisation_approval.regularisation_approval_node({
            "query": "show pending regularization requests",
            "intent": regularisation_approval.VIEW_INTENT, "usage_events": [],
            "bearer_token": "t", "company_id": 26, "conversation_id": "conv-display",
            "is_manager_jwt": True, "is_manager": True,
        }, events.append)

        card = next(e for e in events if e.get("type") == "team_pending_regularization")
        row = card["data"]["regularizations"][0]
        assert row["reference_id"] == "REG-22"
        assert row["applied_by"] == "Akash Jio (geo2)"
        assert row["applied_on"] == "2026-08-31"
