"""QA, Oct 14 - three regularization apply-flow fixes.

  * A day typed with a letter ("sept 3o") was read as 30 Sep without a word.
    It is asked about: "did you mean 03 Sep 2026 or 30 Sep 2026?".
  * A typed time outside the assigned shift was sent as typed (and refused by
    erp-api). It is corrected to the shift's edge, and the employee is told.
  * "from time is 9:20 AM and reason is late arrival then submit" saved "late
    arrival then submit" as the reason and brought the review card back. The
    trailing go-ahead is not part of the reason, and it submits.
"""
import json
from datetime import date
from unittest.mock import AsyncMock, patch

import pytest

import services.regularisation_node as reg
import services.slot_store as slot_store

TODAY = date(2026, 10, 14)
SHIFT = {"shift_name": "Hospitality", "start_time": "09:30:00", "end_time": "20:30:00"}


# -- "sept 3o" ---------------------------------------------------------------

@pytest.mark.parametrize("query,options", [
    ("sept 3o", ["2026-09-03", "2026-09-30"]),
    ("apply regularization for 3o sept", ["2026-09-03", "2026-09-30"]),
    ("3o of september", ["2026-09-03", "2026-09-30"]),
    ("1l oct", ["2026-10-01", "2026-10-11"]),
    ("oct 2O 2026", ["2026-10-02", "2026-10-20"]),
    ("3o feb", ["2026-02-03"]),                  # 30 Feb does not exist
    # Live, Oct 14: "o3 oct" went through as 3 Oct and "for 2o" as 30 Sep.
    ("apply regulariztion on o3 oct", ["2026-10-03"]),
    ("apply regularization for 2o", ["2026-10-02", "2026-10-20"]),   # this month
    ("2o", ["2026-10-02", "2026-10-20"]),
    ("on l2", ["2026-10-12"]),
])
def test_a_letter_in_the_day_is_asked_about(query, options):
    assert reg._ambiguous_typo_day(query, TODAY)[1] == options


@pytest.mark.parametrize("query", [
    "30 sept", "sep 3", "3rd october", "2026-09-30", "reason: out of office for 3o min",
    "apply for 2 oct", "reason: arrived at 10 for o2 meeting", "my id is o3",
])
def test_a_real_date_is_not(query):
    assert reg._ambiguous_typo_day(query, TODAY) is None


def test_what_was_typed_is_quoted_without_the_preposition():
    assert reg._ambiguous_typo_day("apply regularization for 2o", TODAY)[0] == "2o"


@pytest.mark.parametrize("reply", ["2o", "o3 oct", "sept 3o", "3o of sept", "for 2o"])
def test_a_typo_day_still_answers_which_date(reply):
    """Live: a bare "2o" in reply to "which date?" went to general chat."""
    import services.classify_node as classify_node
    assert classify_node._BARE_DAY_OF_MONTH_RE.match(reply)


async def test_the_question_is_not_drawn_as_a_refusal(monkeypatch):
    """status=False draws the red "Regularization Not Available" card - the
    typo question is the plain "which date?" shape instead."""
    monkeypatch.setattr(reg, "_get_shift_details", AsyncMock(return_value=None))
    events = []
    await reg.regularisation_eligibility_node(
        {"query": "i want to apply regularization for 3o sept", "company_id": "typo-co",
         "conversation_id": "conv-typo-shape", "bearer_token": "t", "usage_events": []},
        events.append)
    done = [e for e in events if e.get("type") == "done"][-1]
    assert done["intent"] == "regularization_incomplete"
    assert done["data"]["input_required"] == "date"
    assert "regularisation_classification_status" not in done["data"]
    assert "did you mean 03 Sep 2026 or 30 Sep 2026" in done["data"]["answer"]


# -- times outside the shift ---------------------------------------------------

@pytest.mark.parametrize("start,end,fixed", [
    ("09:20", "20:30", ("09:30", "20:30")),
    ("09:00", "21:30", ("09:30", "20:30")),
    ("09:30", "21:00", ("09:30", "20:30")),
    ("09:20", None, ("09:30", None)),
])
def test_times_outside_the_shift_are_corrected_and_said(start, end, fixed):
    entry = {"date": "2026-09-30", "start_time": start, "end_time": end}
    note = reg._align_entry_to_shift(entry, SHIFT)
    assert (entry["start_time"], entry["end_time"]) == fixed
    assert "doesn't match the shift assigned to you" in note
    assert "Hospitality, 9:30 AM – 8:30 PM" in note


@pytest.mark.parametrize("start,end", [("09:30", "20:30"), ("10:15", "19:00"), (None, None)])
def test_times_inside_the_shift_are_the_employees_own(start, end):
    entry = {"date": "2026-09-30", "start_time": start, "end_time": end}
    assert reg._align_entry_to_shift(entry, SHIFT) is None
    assert (entry["start_time"], entry["end_time"]) == (start, end)


def test_reversed_times_are_left_for_the_employee_to_fix():
    """QA TC-053: "in 6:30 PM, out 9:30 AM" became 6:30-8:30 PM and was sent."""
    entry = {"date": "2026-09-30", "start_time": "18:30", "end_time": "09:30"}
    assert reg._align_entry_to_shift(entry, SHIFT) is None
    assert (entry["start_time"], entry["end_time"]) == ("18:30", "09:30")


def test_no_shift_or_an_overnight_shift_changes_nothing():
    entry = {"date": "2026-09-30", "start_time": "08:00", "end_time": "23:00"}
    assert reg._align_entry_to_shift(entry, None) is None
    night = {"shift_name": "Night", "start_time": "22:00:00", "end_time": "06:00:00"}
    assert reg._align_entry_to_shift(entry, night) is None


# -- "... then submit" --------------------------------------------------------

@pytest.mark.parametrize("query,reason,submits", [
    ("from time is 9:20 AM and reason is late arrival then submit", "late arrival", True),
    ("reason is late arrival, submit it", "late arrival", True),
    ("reason: late arrival & submit", "late arrival", True),
    ("reason: forgot to submit", "forgot to submit", False),
    ("reason: missed punch out", "missed punch out", False),
])
def test_a_trailing_go_ahead_is_not_the_reason(query, reason, submits):
    assert reg._verbatim_reason(query) == {"reason": reason}
    assert reg.ends_with_submit(query) is submits


def test_a_bare_submit_is_not_an_edit():
    assert reg.ends_with_submit("submit") is False


def _llm_provide_info(entries):
    """The extraction calling the message provide_info - what it did live."""
    return {"choices": [{"message": {"content": json.dumps(
        {"action": "provide_info", "entries": entries, "employee_name": None})}}]}


@pytest.fixture
def erp(monkeypatch):
    posts = []

    async def fake_post(token, payload, company_id=None, conversation_id=None):
        posts.append(dict(payload))
        return {"http_status": 200, "body": {"success": True, "data": {}}}

    monkeypatch.setattr(reg.attendance_client, "post_regularization", fake_post)
    monkeypatch.setattr(reg, "_get_shift_details", AsyncMock(return_value=SHIFT))
    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}))
    return posts


async def test_edit_then_submit_submits_with_the_shift_correction(erp):
    conv = "conv-then-submit"
    slot_store.set_slots("regularization", "typo-co", conv, {"entries": [
        {"date": "2026-09-30", "start_time": "09:30", "end_time": "20:30",
         "_prevalidated": True, "_prefill_fetched": True}]})
    events = []
    entry = {"date": "2026-09-30", "start_time": "09:20", "end_time": "20:30",
             "reason": "late arrival then submit"}
    with patch("services.slot_flow._call_llm",
               new=AsyncMock(return_value=_llm_provide_info([entry]))):
        await reg.regularisation_node(
            {"query": "from time is 9:20 AM and reason is late arrival then submit",
             "company_id": "typo-co", "conversation_id": conv, "bearer_token": "t",
             "usage_events": []}, events.append)
    done = [e for e in events if e.get("type") == "done"][-1]
    assert done["intent"] == "regularization_submitted", done["data"]["answer"]
    assert "corrected it to 9:30 AM" in done["data"]["answer"]
    assert erp == [{"apply_date": "2026-09-30", "from_time": "09:30", "to_time": "20:30",
                    "reason": "late arrival"}]
