"""The employee's shift on every reply of the regularization apply flow, from
GET /api/v1/ai/shift-details (data.shift: shift_name, start_time, end_time),
for any role (2026-10-06)."""
from datetime import date
from unittest.mock import AsyncMock

import pytest

import services.regularisation_node as reg
from services import slot_store

COMPANY = "shift-co"
SHIFT_BODY = {"http_status": 200, "body": {"success": True, "message": "Shift details retrieved successfully.",
              "data": {"action_required": None,
                       "employee": {"employee_id": 692, "employee_name": "A Khan Test"},
                       "shift": {"shift_id": 242, "shift_name": "General-Shift", "shift_code": None,
                                 "shift_type": "NORMAL", "start_time": "09:00:00",
                                 "end_time": "18:30:00", "working_minutes": 570}}}}
# What the flow returns: HH:MM, never seconds.
SHIFT = {"shift_name": "General-Shift", "start_time": "09:00", "end_time": "18:30"}


@pytest.fixture
def shift_api(monkeypatch):
    calls = []

    async def get_active_shift(token, company_id=None, conversation_id=None,
                               employee_id=None, employee_name=None):
        calls.append(employee_name)
        return SHIFT_BODY

    monkeypatch.setattr(reg.attendance_client, "get_active_shift", get_active_shift)
    return calls


class TestShiftDetails:
    async def test_reads_shift_name_start_and_end(self, shift_api):
        shift = await reg._get_shift_details(bearer_token="t", company_id=COMPANY,
                                             conversation_id="s-1")
        assert shift == SHIFT

    async def test_one_call_per_conversation(self, shift_api):
        for _ in range(3):
            await reg._get_shift_details(bearer_token="t", company_id=COMPANY, conversation_id="s-2")
        assert len(shift_api) == 1

    @pytest.mark.parametrize("result", [
        {"http_status": 403, "body": {"success": False, "message": "no"}},
        {"http_status": 200, "body": {"success": True, "data": {"shift": None}}},
    ])
    async def test_unreadable_is_none(self, monkeypatch, result):
        monkeypatch.setattr(reg.attendance_client, "get_active_shift", AsyncMock(return_value=result))
        assert await reg._get_shift_details(bearer_token="t", company_id=COMPANY,
                                            conversation_id=f"s-3-{result['http_status']}") is None

    async def test_an_outage_never_blocks(self, monkeypatch):
        monkeypatch.setattr(reg.attendance_client, "get_active_shift",
                            AsyncMock(side_effect=reg.attendance_client.ErpApiUnavailable("down")))
        assert await reg._get_shift_details(bearer_token="t", company_id=COMPANY,
                                            conversation_id="s-4") is None

    def test_sentence(self):
        assert reg._shift_sentence(SHIFT) == " Your shift: General-Shift, 9:00 AM to 6:30 PM."
        assert reg._shift_sentence(None) == ""


class TestOnTheReplies:
    async def test_the_eligible_reply_carries_the_shift(self, monkeypatch, shift_api):
        conv = "s-gate"
        slot_store.clear_slots("regularization", COMPANY, conv)
        monkeypatch.setattr(reg.attendance_mod, "_today", lambda: date(2026, 10, 5))
        monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
            "outcome": reg.DUPLICATE_NONE, "message": None, "existing_request": None, "rows": []}))
        monkeypatch.setattr(reg, "_get_regularization_settings", AsyncMock(return_value={
            "available": True, "window_days": 20, "limit": None, "cycle": None}))
        monkeypatch.setattr(reg, "_classify_and_check_eligibility", AsyncMock(return_value=None))
        events = []
        await reg.regularisation_eligibility_node(
            {"query": "regularize 29 sept", "company_id": COMPANY, "conversation_id": conv,
             "bearer_token": "t", "usage_events": []}, events.append)

        done = [e for e in events if e.get("type") == "done"][-1]
        assert done["data"]["shift"] == SHIFT
        assert "Your shift: General-Shift, 9:00 AM to 6:30 PM." in done["data"]["answer"]

    async def test_a_blocked_reply_carries_it_too(self, monkeypatch, shift_api):
        conv = "s-gate-2"
        slot_store.clear_slots("regularization", COMPANY, conv)
        monkeypatch.setattr(reg.attendance_mod, "_today", lambda: date(2026, 10, 5))
        monkeypatch.setattr(reg, "_check_duplicate_date", AsyncMock(return_value={
            "outcome": reg.DUPLICATE_NONE, "message": None, "existing_request": None, "rows": []}))
        events = []
        await reg.regularisation_eligibility_node(
            {"query": "regularize 9 oct", "company_id": COMPANY, "conversation_id": conv,
             "bearer_token": "t", "usage_events": []}, events.append)
        done = [e for e in events if e.get("type") == "done"][-1]
        assert "future date" in done["data"]["answer"]
        assert done["data"]["shift"] == SHIFT
