"""Split shifts, the form's Confirm & Submit, and the bare "apply
regularisation".

Live: "QA Team" is a SPLIT shift (10:00-20:00 = "QA 1st" 10:00-14:30 + "QA
2nd" 15:00-20:00) and the employee is assigned "QA 2nd" only. The form showed
and pre-filled 10:00-20:00, and erp-api refused every submission: "Assigned
session does not belong to the employee shift".
"""
import json

import pytest

import services.regularisation_node as reg
from services import slot_store

SPLIT = {
    "assignment": {"assignment_id": 50, "selected_session_id": 37},
    "shift": {"shift_id": 246, "shift_name": "QA Team", "shift_type": "SPLIT",
              "start_time": "10:00:00", "end_time": "20:00:00",
              "sessions": [
                  {"session_id": 36, "session_name": "QA 1st", "start_time": "10:00:00",
                   "end_time": "14:30:00", "is_selected_session": False},
                  {"session_id": 37, "session_name": "QA 2nd", "start_time": "15:00:00",
                   "end_time": "20:00:00", "is_selected_session": True}]},
}


def _shift_api(monkeypatch, data):
    async def _get(*a, **k):
        return {"http_status": 200, "body": {"success": True, "data": data}}
    monkeypatch.setattr(reg.attendance_client, "get_active_shift", _get)


class TestTheAssignedSession:
    async def test_a_split_shift_shows_the_SHIFT_not_a_session(self, monkeypatch):
        """Reverses an earlier rule, on the erp-api developer's own statement
        (2026-10-08): `shift.start_time` and `shift.end_time` are the only
        keys a regularization is concerned with, and sessions are erp-api's
        internal breakdown of a split shift.

        The rule this replaces narrowed the card to the assigned session, so
        a "QA Team" employee saw "QA Team - QA 2nd, 3:00-8:00 PM" instead of
        the shift's 10:00 AM-8:00 PM. It was added because submitting the
        whole shift was refused - but narrowing never made a submission
        succeed, it only changed which error came back.

        Submissions are separately blocked by an erp-api defect that caps
        `to_time` at 18:30 while publishing the shift as ending at 20:00
        (bisected 2026-10-08: 18:30 accepted, 18:31 refused, everything above
        refused; `from_time` unconstrained). 18:30 is not in the
        shift-details response at all, so no prefill can satisfy it. The card
        therefore shows the documented thing and
        _shift_refusal_is_unfixable explains the refusal honestly.
        """
        _shift_api(monkeypatch, SPLIT)
        shift = await reg._get_shift_details(bearer_token="t", company_id=1,
                                             conversation_id="split-1")
        # The SHIFT (both sides of the merge): the session narrowing is gone,
        # and the times are normalised to HH:MM rather than erp-api's
        # "10:00:00".
        assert (shift["start_time"], shift["end_time"]) == ("10:00", "20:00")
        assert shift["shift_name"] == "QA Team"
        assert "session_id" not in shift, "sessions must not leak into the card"

    async def test_the_session_breakdown_is_ignored_entirely(self, monkeypatch):
        """Guards the regression directly: whichever session erp-api marks as
        selected, the card is the same, because sessions are not consulted."""
        flipped = {"assignment": {"assignment_id": 50, "selected_session_id": 36},
                   "shift": {**SPLIT["shift"], "sessions": [
                       {**SPLIT["shift"]["sessions"][0], "is_selected_session": True},
                       {**SPLIT["shift"]["sessions"][1], "is_selected_session": False}]}}
        _shift_api(monkeypatch, flipped)
        shift = await reg._get_shift_details(bearer_token="t", company_id=1,
                                             conversation_id="split-flipped")
        assert (shift["start_time"], shift["end_time"]) == ("10:00", "20:00")
        assert shift["shift_name"] == "QA Team"

    # _assigned_session itself is retained and still correct - it is the one
    # place that knows how erp-api expresses "which session is this employee
    # on", which the erp-api ticket needs. It is simply no longer wired into
    # the regularization shift lookup. These two keep it honest.
    def test_picked_by_is_selected_session_without_an_assignment(self):
        data = {**SPLIT, "assignment": {}}
        assert reg._assigned_session(data)["session_id"] == 37

    def test_a_single_session_is_that_session(self):
        one = {"shift": {**SPLIT["shift"], "sessions": [SPLIT["shift"]["sessions"][0]]}}
        assert reg._assigned_session(one)["session_id"] == 36

    async def test_a_shift_without_sessions_is_unchanged(self, monkeypatch):
        _shift_api(monkeypatch, {"shift": {"shift_name": "General-Shift",
                                           "start_time": "09:00:00", "end_time": "18:30:00"}})
        shift = await reg._get_shift_details(bearer_token="t", company_id=1,
                                             conversation_id="split-2")
        assert shift == {"shift_name": "General-Shift", "start_time": "09:00",
                         "end_time": "18:30"}


class TestNoEmptyCard:
    async def test_a_bare_apply_asks_for_the_date_without_a_card(self, monkeypatch):
        """Live: an empty card was drawn as "Regularization Request Identified"
        with a blank date, and the date was never visibly asked for."""
        events = []
        conv = "bare-apply"
        slot_store.set_slots("regularization", 1, conv, {"entries": [], "employee_name": None})

        async def _no_shift(**k):
            return None

        monkeypatch.setattr(reg, "_get_shift_details", _no_shift)
        from unittest.mock import AsyncMock, patch
        llm = {"choices": [{"message": {"content": json.dumps(
            {"action": "update", "entries": [], "employee_name": None})}}]}
        with patch("services.slot_flow._call_llm", new=AsyncMock(return_value=llm)):
            await reg.regularisation_node(
                {"query": "apply regularisation", "company_id": 1, "conversation_id": conv,
                 "bearer_token": "t", "usage_events": []}, events.append)
        done = [e for e in events if e.get("type") == "done"][-1]
        assert not [e for e in events if e.get("type") == "regularization_card"]
        assert done["data"].get("input_required") == "date"
        assert "which date" in done["data"]["answer"]


class TestEveryWayATimeIsWritten:
    """erp-api compares the times against the shift as 24-hour "HH:MM"."""

    @pytest.mark.parametrize("value, expected", [
        ("10 am", "10:00"), ("10:00 AM", "10:00"), ("11 pm", "23:00"), ("11:00 PM", "23:00"),
        ("23", "23:00"), ("23:00:00", "23:00"), ("2300", "23:00"), ("12 am", "00:00"),
        ("12 pm", "12:00"), ("11.30 pm", "23:30"), ("noon", "12:00"), ("7:30", "07:30"),
        ("25", "25"), ("", None),
    ])
    def test_time_24h(self, value, expected):
        from services.regularisation_display import time_24h
        assert time_24h(value) == expected

    @pytest.mark.parametrize("query, expected", [
        ("10 - 23 late arrival", {"start_time": "10:00", "end_time": "23:00", "reason": "late arrival"}),
        ("10 to 23, missed punch out", {"start_time": "10:00", "end_time": "23:00",
                                        "reason": "missed punch out"}),
        ("from 10 - 23", {"start_time": "10:00", "end_time": "23:00"}),
        ("10 am - 11 pm", {"start_time": "10:00", "end_time": "23:00"}),
    ])
    def test_a_typed_range(self, query, expected):
        entry = reg._fallback_extract_entry(query)
        entry.pop("_times_from_bare_range", None)
        assert entry == expected

    @pytest.mark.parametrize("query", ["2-10-2026", "2 - 3 oct", "10 - 23rd", "late arrival"])
    def test_not_a_time_range(self, query):
        entry = reg._fallback_extract_entry(query) or {}
        assert "start_time" not in entry

    def test_the_form_sends_12_hour_times(self):
        entry = reg._payload_entry({"date": "2026-10-02", "start_time": "10:00 AM",
                                    "end_time": "11:00 PM", "reason": "Late arrival"})
        assert (entry["start_time"], entry["end_time"]) == ("10:00", "23:00")


class TestFutureDates:
    @pytest.mark.parametrize("plural, dates, says", [
        (False, "10 Oct 2026", "10 Oct 2026 hasn't happened yet"),
        (True, "10 Oct 2026, 11 Oct 2026", "10 Oct 2026, 11 Oct 2026 haven't happened yet"),
    ])
    def test_the_refusal(self, plural, dates, says):
        from services.regularisation_display import future_date_message
        msg = future_date_message(dates, "07 Oct 2026", plural=plural)
        assert msg.startswith("You can't regularize future dates")
        assert says in msg and "(07 Oct 2026)" in msg


def test_general_chat_knows_the_time(monkeypatch):
    """Live: "what is today time" got "I don't have access to real-time data"."""
    import services.hr_graph as hg
    monkeypatch.setenv("QUOTA_TIMEZONE", "Asia/Kolkata")
    line = hg._general_chat_clock_line()
    assert "Today's date is" in line and "The current time is" in line
    assert "(Asia/Kolkata)" in line


class TestToday:
    """Live, at 11:33 PM server time: "today" resolved to 08-Oct (the company's
    Asia/Kolkata date), the submit step called 08-Oct a future date ("on or
    before today (07 Oct 2026)" - the server's own clock), and erp-api refused
    3:00-8:00 PM, which hadn't come yet, after the whole form was filled."""

    @pytest.fixture
    def at_11_15_ist(self, monkeypatch):
        from datetime import datetime
        from zoneinfo import ZoneInfo
        now = datetime(2026, 10, 8, 11, 15, tzinfo=ZoneInfo("Asia/Kolkata"))
        monkeypatch.setattr(reg, "_company_now", lambda: now)
        return now

    def test_a_time_still_ahead_today_is_stopped_before_sending(self, at_11_15_ist):
        fix = reg._not_yet_happened_today({"date": "2026-10-08", "start_time": "15:00",
                                           "end_time": "20:00", "reason": "x"})
        assert fix["fields"] == ["start_time", "end_time"]
        assert fix["message"].startswith("It's 11:15 AM now, so 3:00 PM today hasn't come yet")

    def test_only_the_end_still_ahead(self, at_11_15_ist):
        fix = reg._not_yet_happened_today({"date": "2026-10-08", "start_time": "09:00",
                                           "end_time": "18:30"})
        assert fix["fields"] == ["end_time"]

    @pytest.mark.parametrize("entry", [
        {"date": "2026-10-08", "start_time": "09:00", "end_time": "11:00"},
        {"date": "2026-10-07", "start_time": "15:00", "end_time": "20:00"},
    ])
    def test_past_times_go_through(self, at_11_15_ist, entry):
        assert reg._not_yet_happened_today(entry) is None

    def test_slot_flow_uses_the_company_date(self, monkeypatch):
        import services.slot_flow as sf
        monkeypatch.setenv("QUOTA_TIMEZONE", "Asia/Kolkata")
        from datetime import datetime
        from zoneinfo import ZoneInfo
        assert sf._company_today() == datetime.now(ZoneInfo("Asia/Kolkata")).date()

    def test_times_within_the_shift_do_not_get_a_correction_form(self):
        """Supersedes an earlier version of this test, which asserted the
        wording of a correction form for this case. The form itself was the
        bug: there is nothing in it to correct.

        Measured against erp-api on 2026-10-08 for this exact employee and
        split shift:

            15:00-20:00  session 37, the ASSIGNED one  -> 400 refused
            15:30-19:00  session 37, the ASSIGNED one  -> 400 refused
            10:30-14:00  session 36, NOT assigned      -> 200 accepted

        erp-api reports `selected_session_id: 37` when asked, then validates
        against session 36. Every time the employee works is refused and only
        hours they do not work are accepted, so "correct the times and submit
        again" could never come true - which is how it was reported: the same
        message on every attempt.
        """
        fix = reg._shift_correction(
            "Regularization to time must be within shift timing.",
            {"shift_name": "QA Team - QA 2nd", "start_time": "15:00:00", "end_time": "20:00:00"},
            {"start_time": "15:00", "end_time": "20:00"})
        assert fix is None

    def test_times_outside_the_shift_still_get_the_form(self):
        """The other half, and the reason the new rule is narrow: when the
        times really are outside the shift the employee CAN fix them, so that
        refusal still brings the form back exactly as before."""
        fix = reg._shift_correction(
            "Regularization to time must be within shift timing.",
            {"shift_name": "QA Team", "start_time": "10:00", "end_time": "20:00"},
            {"start_time": "21:00", "end_time": "22:00"})
        assert fix["fields"] == ["start_time", "end_time"]

    def test_the_message_does_not_promise_that_correcting_will_work(self):
        msg = reg._unfixable_shift_message(
            "Regularization to time must be within shift timing.",
            {"shift_name": "QA Team", "start_time": "10:00", "end_time": "20:00"},
            {"start_time": "10:00", "end_time": "20:00"})
        assert "nothing wrong with what you entered" in msg
        assert "needs HR" in msg
        # erp-api's own sentence is quoted verbatim, so the employee has
        # something exact to give HR and the text stays true if the wording
        # on erp-api's side changes.
        assert "Regularization to time must be within shift timing." in msg
        # The escape hatch survives: a stale/incorrect shift on OUR side is
        # indistinguishable from erp-api's misconfiguration, so the employee
        # is still invited to give different times if they really worked them.
        assert "tell me the times" in msg


class TestNoSecondsAnywhere:
    """Shift times are sent and shown as HH:MM ("15:00"), never "15:00:00"."""

    def test_shift_hhmm(self):
        from services.regularisation_display import shift_hhmm
        out = shift_hhmm({"shift_name": "QA Team", "start_time": "10:00:00", "end_time": "20:00:00",
                          "sessions": [{"session_name": "QA 2nd", "start_time": "15:00:00",
                                        "end_time": "20:00:00"}]})
        assert (out["start_time"], out["end_time"]) == ("10:00", "20:00")
        assert (out["sessions"][0]["start_time"], out["sessions"][0]["end_time"]) == ("15:00", "20:00")

    async def test_the_regularization_shift(self, monkeypatch):
        """Merged: still asserts no seconds survive, but the expected window
        is the SHIFT (10:00-20:00) rather than the assigned session
        (15:00-20:00) - see test_a_split_shift_shows_the_SHIFT_not_a_session
        for why sessions are no longer consulted."""
        _shift_api(monkeypatch, SPLIT)
        shift = await reg._get_shift_details(bearer_token="t", company_id=1,
                                             conversation_id="split-hhmm")
        assert ":00:00" not in f"{shift['start_time']}{shift['end_time']}"
        assert (shift["start_time"], shift["end_time"]) == ("10:00", "20:00")
