"""
Unit tests for services/punch_details.py — Punch Times & Work Hours
(FR-03.2). Covers date resolution (AC5), session formatting, and
punch_details_node's handling of complete/incomplete/zero-punch days
(AC1-AC4, AC6-AC7). erp_client.get_punch_details and the LLM date
extraction are mocked; no real network or LLM call is made.
"""
from datetime import date, timedelta
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

import services.erp_client as erp_client
import services.punch_details as punch_details
from services.punch_details import (
    AmbiguousDateRange,
    AmbiguousMultipleDates,
    _build_date_expression_prompt,
    _expression_to_requested_date,
    _format_sessions,
    _normalize_date_expression,
    _today,
    punch_details_node,
)


# ── Date resolution (AC5) ───────────────────────────────────────────────────
#
# punch_details no longer pattern-matches the query itself: the LLM
# classifies every date phrase into a symbolic expression and
# date_query_resolver's pure-Python arithmetic turns that symbol into a
# date. So these tests assert the half that IS deterministic — symbol ->
# date, and how punch_details_node's own contract (ISO string / None /
# Ambiguous* / NoSuchOrdinalWeekday / InvalidExplicitDate) is derived from
# it. Every date asserted below was asserted by the previous regex-era
# suite too, so the behavioral contract is unchanged; only what produces
# the symbol moved.
#
# Whether the LLM classifies a given sentence correctly is not testable
# hermetically and is deliberately not asserted here — that is the
# tradeoff of the LLM-first design.

TODAY = date(2026, 8, 18)  # Tuesday


def _resolve(expression: dict, today: date = TODAY, week_start: int = 0):
    """Runs one LLM-shaped symbolic expression through the real validation
    and arithmetic path, exactly as _extract_date_expression_via_llm would
    hand it over."""
    normalized = _normalize_date_expression(expression)
    assert normalized is not None, f"expression rejected by validation: {expression}"
    return _expression_to_requested_date(normalized, today, week_start)


def test_no_date_reference_returns_none():
    """None here means "default to today" — punch_details_node lets
    erp-api apply its own default rather than hardcoding a date."""
    assert _resolve({"type": "unknown"}) is None


def test_today_returns_none_so_erp_api_applies_its_own_default():
    assert _resolve({"type": "today"}) is None


def test_yesterday():
    assert _resolve({"type": "yesterday"}) == "2026-08-17"


def test_last_friday():
    # TODAY is Tuesday 2026-08-18; the most recent past Friday is 2026-08-14.
    assert _resolve({"type": "weekday", "weekday": "friday", "weeks_ago": 1}) == "2026-08-14"


def test_last_weekday_on_that_same_weekday_goes_back_a_full_week():
    assert _resolve({"type": "weekday", "weekday": "tuesday", "weeks_ago": 1}) == "2026-08-11"


def test_bare_weekday_is_retrospective_and_includes_today():
    """A bare "friday" with no qualifier is its own type — the most recent
    occurrence INCLUDING today, never the future."""
    assert _resolve({"type": "weekday_retrospective", "weekday": "saturday"}) == "2026-08-15"
    tuesday = date(2026, 8, 18)
    assert _resolve({"type": "weekday_retrospective", "weekday": "tuesday"}, tuesday) == "2026-08-18"


def test_explicit_iso_date():
    assert _resolve({"type": "explicit_single", "explicit_date": "2026-07-01"}) == "2026-07-01"


# ── Ordinal weekday of a month ──────────────────────────────────────────────

def test_last_month_first_friday():
    # last month = July 2026; July 1, 2026 is a Wednesday -> first Friday = July 3.
    assert _resolve({
        "type": "ordinal_weekday_of_month", "weekday": "friday",
        "ordinal_word": "first", "month": 7, "year": 2026,
    }) == "2026-07-03"


def test_last_year_first_month_last_friday():
    """January 31, 2025 is a Friday, so "last Friday of January 2025" is
    January 31 itself."""
    assert _resolve({
        "type": "ordinal_weekday_of_month", "weekday": "friday",
        "ordinal_word": "last", "month": 1, "year": 2025,
    }) == "2025-01-31"


def test_last_year_last_month_last_friday():
    """December 26, 2025 is a Friday."""
    assert _resolve({
        "type": "ordinal_weekday_of_month", "weekday": "friday",
        "ordinal_word": "last", "month": 12, "year": 2025,
    }) == "2025-12-26"


def test_second_monday_of_this_month():
    # August 2026: Aug 1 is a Saturday -> first Monday = Aug 3, second = Aug 10.
    assert _resolve({
        "type": "ordinal_weekday_of_month", "weekday": "monday",
        "ordinal_word": "second", "month": 8, "year": 2026,
    }) == "2026-08-10"


def test_ordinal_weekday_with_explicit_month_and_year():
    # January 2025: Jan 1 is a Wednesday -> first Friday = Jan 3.
    assert _resolve({
        "type": "ordinal_weekday_of_month", "weekday": "friday",
        "ordinal_word": "first", "month": 1, "year": 2025,
    }) == "2025-01-03"


def test_ordinal_weekday_that_the_month_does_not_have_is_reported_not_guessed():
    """June 2026 has only 4 Wednesdays — punch_details_node answers that
    directly rather than silently falling through to erp-api's
    default-to-today."""
    result = _resolve({
        "type": "ordinal_weekday_of_month", "weekday": "wednesday",
        "ordinal_word": "fifth", "month": 6, "year": 2026,
    })
    assert isinstance(result, punch_details.date_query_resolver.NoSuchOrdinalWeekday)


# ── Calendar-week-anchored vs recency-based weekdays ────────────────────────

def test_last_week_wednesday():
    """TODAY is Tuesday 2026-08-18 (this week: Aug 17-23); last week is
    Aug 10-16, so last week's Wednesday is Aug 12."""
    assert _resolve({
        "type": "week_qualified_weekday", "weekday": "wednesday", "weeks_ago": 1,
    }) == "2026-08-12"


def test_this_week_friday():
    # This week (Aug 17-23): Friday = Aug 21.
    assert _resolve({
        "type": "week_qualified_weekday", "weekday": "friday", "weeks_ago": 0,
    }) == "2026-08-21"


def test_last_weekday_and_last_week_weekday_genuinely_disagree():
    """"last Wednesday" and "last week Wednesday" are NOT the same thing —
    said on a Thursday, "last Wednesday" is yesterday (this week), but
    "last week Wednesday" is the Wednesday of the PRIOR calendar week, a
    full 7 days earlier. Confirms the two arithmetic branches actually
    disagree when they should, not just coincidentally match."""
    thursday = date(2026, 8, 27)
    assert _resolve({"type": "weekday", "weekday": "wednesday", "weeks_ago": 1}, thursday) == "2026-08-26"
    assert _resolve(
        {"type": "week_qualified_weekday", "weekday": "wednesday", "weeks_ago": 1}, thursday,
    ) == "2026-08-19"


def test_week_qualified_weekday_honors_an_employee_stated_week_start():
    """"last week sunday, my week starts on sunday" — week_start is carried
    through from the LLM's week_starts_on field."""
    assert _resolve(
        {"type": "week_qualified_weekday", "weekday": "sunday", "weeks_ago": 1},
        TODAY, week_start=6,
    ) == "2026-08-09"


# ── Backward-anchored counts ("N <unit> ago") ───────────────────────────────

def test_weekday_ago_is_not_the_most_recent_weekday():
    """The reported live bug, at the symbol level: "Friday one month ago"
    must anchor a month back and take the Friday on or before THAT, not
    the most recent Friday. Anchor = 2026-07-18 (Saturday) -> 2026-07-17."""
    assert _resolve({
        "type": "weekday_ago", "weekday": "friday", "n_units": 1, "unit": "month",
    }) == "2026-07-17"


def test_relative_ago_days_is_a_single_day():
    assert _resolve({"type": "relative_ago", "n_units": 3, "unit": "day"}) == "2026-08-15"


def test_relative_ago_month_is_a_range_the_node_asks_about():
    result = _resolve({"type": "relative_ago", "n_units": 1, "unit": "month"})
    assert isinstance(result, AmbiguousDateRange)
    assert (result.start_date, result.end_date) == (date(2026, 7, 1), date(2026, 7, 31))


# ── Shapes this single-day node refuses to narrow ───────────────────────────

def test_range_becomes_an_ambiguous_range_not_a_guessed_day():
    result = _resolve({"type": "last_week"})
    assert isinstance(result, AmbiguousDateRange)
    assert (result.start_date, result.end_date) == (date(2026, 8, 10), date(2026, 8, 16))


def test_several_discontiguous_days_become_ambiguous_multiple_dates():
    result = _resolve({"type": "last_n_weekdays", "weekday": "tuesday", "n_days": 2})
    assert isinstance(result, AmbiguousMultipleDates)
    assert result.dates == [date(2026, 8, 4), date(2026, 8, 11)]


def test_invalid_explicit_date_is_reported_not_ignored():
    result = _resolve({"type": "invalid_explicit_date", "explicit_date": "31/02/2026"})
    assert isinstance(result, punch_details.date_query_resolver.InvalidExplicitDate)
    assert result.matched_text == "31/02/2026"


# ── LLM output validation ───────────────────────────────────────────────────
# A malformed value must degrade to "not extracted", never reach the
# arithmetic as a silently wrong input.

def test_unknown_expression_type_is_rejected():
    assert _normalize_date_expression({"type": "nonsense_type"}) is None


def test_non_dict_llm_output_is_rejected():
    assert _normalize_date_expression("2026-08-14") is None
    assert _normalize_date_expression(None) is None


def test_off_vocabulary_weekday_is_dropped_rather_than_passed_through():
    normalized = _normalize_date_expression(
        {"type": "weekday", "weekday": "funday", "weeks_ago": 1},
    )
    assert normalized["weekday"] is None
    # ... and an expression missing the weekday it needs resolves to nothing
    # rather than to some arbitrary day.
    assert _expression_to_requested_date(normalized, TODAY) is None


def test_booleans_are_not_accepted_as_integers():
    """True is an int in Python — it must not slip through as weeks_ago=1."""
    normalized = _normalize_date_expression(
        {"type": "weekday", "weekday": "friday", "weeks_ago": True},
    )
    assert normalized["weeks_ago"] is None


def test_malformed_explicit_date_string_is_dropped():
    normalized = _normalize_date_expression(
        {"type": "explicit_single", "explicit_date": "July 21st"},
    )
    assert normalized["explicit_date"] is None
    assert _expression_to_requested_date(normalized, TODAY) is None


def test_off_vocabulary_unit_is_dropped():
    normalized = _normalize_date_expression(
        {"type": "relative_ago", "n_units": 2, "unit": "fortnight"},
    )
    assert normalized["unit"] is None
    assert _expression_to_requested_date(normalized, TODAY) is None


# ── The prompt itself ───────────────────────────────────────────────────────

def test_prompt_forbids_the_llm_from_doing_date_arithmetic():
    """The whole design rests on this instruction: the LLM classifies, it
    never computes. If this line ever goes missing the model will start
    emitting dates it calculated itself."""
    prompt = _build_date_expression_prompt("punch time last friday", TODAY)
    assert "must NOT calculate any date yourself" in prompt
    assert "Python does all the calendar arithmetic afterwards" in prompt


def test_prompt_forces_day_first_for_ambiguous_slash_dates():
    """Regression test — confirmed live: "10/08/2026" was resolved as
    2026-10-08 (US MM/DD/YYYY) instead of the intended 2026-08-10
    (DD/MM/YYYY). This can't be caught by mocking _call_llm (that only
    proves the plumbing, not what the LLM does with ambiguous input) — it
    asserts the explicit day-first instruction and worked examples are
    actually present in the prompt."""
    prompt = _build_date_expression_prompt("what time did I check on 10/08/2026", TODAY)
    assert "DD/MM/YYYY" in prompt
    assert "NEVER MM/DD/YYYY" in prompt
    assert "2026-08-10" in prompt  # worked example: 10/08/2026 -> August 10th, not October 8th


def test_prompt_offers_every_type_the_resolver_can_actually_resolve():
    """A type the prompt never mentions is one the LLM can never choose —
    the exact gap that left attendance.py's own extraction stuck on a
    stale subset. Guards against the schema and the prompt drifting apart."""
    prompt = _build_date_expression_prompt("punch time", TODAY)
    for etype in punch_details._DATE_EXPRESSION_TYPES:
        assert f'"{etype}"' in prompt, f"{etype} is resolvable but absent from the prompt"


# ── _format_sessions ─────────────────────────────────────────────────────────

def test_format_sessions_complete():
    sessions = [{"check_in": "2026-07-01 10:04:45", "check_out": "2026-07-01 18:31:06", "complete": True}]
    assert _format_sessions(sessions) == "Session 1: 2026-07-01 10:04:45 to 2026-07-01 18:31:06"


def test_format_sessions_missing_checkout():
    sessions = [{"check_in": "2026-07-01 09:00:00", "check_out": None, "complete": False}]
    result = _format_sessions(sessions)
    assert "checked in at 2026-07-01 09:00" in result
    assert "check-out not recorded" in result


def test_format_sessions_missing_checkin():
    sessions = [{"check_in": None, "check_out": "2026-07-01 18:00:00", "complete": False}]
    result = _format_sessions(sessions)
    assert "checked out at 2026-07-01 18:00" in result
    assert "check-in not recorded" in result


def test_format_sessions_multiple_pairs_are_chronological_and_semicolon_joined():
    """AC6 — split-shift / multiple-session days list every pair."""
    sessions = [
        {"check_in": "2026-07-01 09:00:00", "check_out": "2026-07-01 13:00:00", "complete": True},
        {"check_in": "2026-07-01 14:00:00", "check_out": "2026-07-01 18:00:00", "complete": True},
    ]
    result = _format_sessions(sessions)
    assert result == (
        "Session 1: 2026-07-01 09:00:00 to 2026-07-01 13:00:00; "
        "Session 2: 2026-07-01 14:00:00 to 2026-07-01 18:00:00"
    )


# ── punch_details_node ───────────────────────────────────────────────────────

def _writer_done_event(writer: MagicMock) -> dict:
    """Pulls the single {"type": "done", ...} payload out of all writer()
    calls made during a node run."""
    for call in writer.call_args_list:
        event = call.args[0]
        if event.get("type") == "done":
            return event
    raise AssertionError("no 'done' event was written")


@pytest.fixture(autouse=True)
def _no_real_llm_calls():
    """punch_details now makes an LLM date call on EVERY query, so a node
    test that doesn't care about dates would otherwise attempt a real one.
    Default it to "no date reference here", which is what a query like
    "what were my punch times" genuinely means. Tests that DO care patch
    _call_llm themselves; that inner patch takes precedence and is
    restored to this one on exit."""
    no_date = {"choices": [{"message": {"content": '{"type": "unknown"}'}}], "usage": {}}
    with patch.object(punch_details, "_call_llm", new=AsyncMock(return_value=no_date)):
        yield


@pytest.fixture
def state():
    return {
        "query": "what were my punch times", "bearer_token": "employee-jwt",
        "company_id": 1, "conversation_id": "conv-1", "usage_events": [],
    }


@pytest.mark.asyncio
async def test_complete_day_shows_punches_shift_and_hours(state):
    """AC1 + AC2 + AC3."""
    fake_response = {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "requested_date": "2026-07-01",
                "shift": {"name": "General-Shift", "start_time": "10:00:00", "end_time": "18:30:00"},
                "punch_status": "complete",
                "session_count": 1,
                "sessions": [{"check_in": "2026-07-01 10:04:45", "check_out": "2026-07-01 18:31:06", "complete": True}],
                "work_hours": {"available": True, "value": "08:26"},
            },
            "message": "Punch details fetched successfully.",
        },
    }
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        result = await punch_details_node(state, writer)

    event = _writer_done_event(writer)
    assert event["intent"] == "punch_details"
    msg = event["message"]
    assert "2026-07-01 10:04:45" in msg and "2026-07-01 18:31:06" in msg  # AC1
    assert "General-Shift" in msg and "10:00" in msg and "18:30" in msg  # AC2
    assert "08:26" in msg  # AC3 — the ERP-computed value, never re-derived
    assert result["response_text"] == msg


@pytest.mark.asyncio
async def test_real_erp_api_response_uses_punches_key_not_sessions(state):
    """Regression test — erp-api's real /attendance/punch-details response
    (confirmed live 2026-08-18 against a real employee record) returns the
    punch list under "punches", not "sessions". Using the wrong key silently
    treats real punch data as zero records and returns the AC7 "No punch
    records found" message instead of the actual punch details."""
    fake_response = {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "requested_date": "2026-07-01",
                "logical_shift_date": "2026-07-01",
                "shift": {"id": 173, "name": "HR Test Shift", "start_time": "10:00:00",
                          "end_time": "19:00:00", "week_off_days": [], "relief_time": "15", "status": "1"},
                "attendance": {"attendance": "R(PA)", "working_type": "1", "is_regularized": True},
                "punch_status": "complete",
                "punch_count": 1,
                "punches": [{"punch_number": 1, "check_in": "2026-07-01 10:00:00",
                             "check_out": "2026-07-01 11:01:00", "complete": True, "missing": None}],
                "work_hours": {"available": True, "value": "01:01", "source": "users_attendence", "reason": None},
            },
            "message": "Punch details fetched successfully.",
        },
    }
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert "couldn't find any punch records" not in msg
    assert "2026-07-01 10:00" in msg and "2026-07-01 11:01" in msg
    assert "HR Test Shift" in msg
    assert "01:01" in msg


@pytest.mark.asyncio
async def test_incomplete_day_shows_existing_punch_notes_missing_and_hides_hours(state):
    """AC4 — no work-hours value at all when a punch is missing."""
    fake_response = {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "requested_date": "2026-07-02",
                "shift": {"name": "General-Shift", "start_time": "10:00:00", "end_time": "18:30:00"},
                "punch_status": "incomplete",
                "session_count": 1,
                "sessions": [{"check_in": "2026-07-02 10:04:45", "check_out": None, "complete": False}],
                "work_hours": {"available": False, "value": None},
            },
        },
    }
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert "2026-07-02 10:04:45" in msg
    assert "check-out not recorded" in msg
    assert "Total work hours" not in msg
    assert "hours aren't available" in msg


@pytest.mark.asyncio
async def test_zero_punch_day_with_reason_gives_explicit_zero_state(state):
    """AC7."""
    fake_response = {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "requested_date": "2026-08-16",
                "shift": None,
                "punch_status": "week_off",
                "punch_count": 0,
                "punches": [],
                "work_hours": {"available": False, "value": None},
                "day_status": "Weekly Off",
            },
        },
    }
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert msg == ("I couldn't find any punch records for 16 Aug 2026 — "
                   "it was a Weekly Off, so none were expected.")


@pytest.mark.asyncio
async def test_zero_punch_day_with_shift_assigned_still_shows_shift(state):
    """Regression test — erp-api's real response for an ordinary no-punch
    day (confirmed live 2026-08-18: /attendance/punch-details returned
    punch_status "no_records" with a real "shift" object but attendance/
    day_status both null) still has a shift assigned. The zero-punches
    branch must not silently drop shift info just because there were no
    punches that day."""
    fake_response = {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "requested_date": "2026-08-18",
                "logical_shift_date": "2026-08-18",
                "shift": {"id": 166, "name": "Testing Manual Shift", "start_time": "10:05:00",
                          "end_time": "19:00:00", "week_off_days": [], "relief_time": "0", "status": "1"},
                "attendance": None,
                "day_status": None,
                "punch_status": "no_records",
                "punch_count": 0,
                "punches": [],
                "work_hours": {"available": False, "value": None, "source": "users_attendence",
                               "reason": "No punch records found"},
            },
            "message": "No punch records found for 2026-08-18.",
        },
    }
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert msg == ("I couldn't find any punch records for 18 Aug 2026 — no check-in or "
                   "check-out was logged that day. Shift: Testing Manual Shift "
                   "(10:05–19:00). If you meant a different day, just tell me the "
                   "date and I'll check that one.")


@pytest.mark.asyncio
async def test_zero_punch_day_ignores_raw_attendance_status_code(state):
    """Regression test — confirmed live 2026-08-14 (a regularized-but-
    punchless day): erp-api returns day_status=null but
    attendance.attendance="P", a raw single-letter internal status code,
    not a human-readable day type. Must NOT render as "as it was a P." —
    only day_status is a legitimate reason source."""
    fake_response = {
        "http_status": 200,
        "body": {
            "success": True,
            "data": {
                "requested_date": "2026-08-14",
                "shift": {"id": 173, "name": "HR Test Shift", "start_time": "10:00:00",
                          "end_time": "19:00:00", "week_off_days": [], "relief_time": "15", "status": "1"},
                "attendance": {"attendance": "P", "working_type": "1", "is_regularized": False},
                "day_status": None,
                "punch_status": "no_records",
                "punch_count": 0,
                "punches": [],
                "work_hours": {"available": False, "value": None, "source": "users_attendence",
                               "reason": "No punch records found"},
            },
            "message": "No punch records found for 2026-08-14.",
        },
    }
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert "as it was a P" not in msg
    assert msg == ("I couldn't find any punch records for 14 Aug 2026 — no check-in or "
                   "check-out was logged that day. Shift: HR Test Shift "
                   "(10:00–19:00). If you meant a different day, just tell me the "
                   "date and I'll check that one.")


@pytest.mark.asyncio
async def test_zero_punch_day_without_reason_field_still_avoids_empty_card(state):
    """No day_status/attendance present — must not crash or show a
    blank card; falls back to a plain no-records message."""
    fake_response = {
        "http_status": 200,
        "body": {"success": True, "data": {"requested_date": "2026-08-16", "sessions": []}},
    }
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert msg == ("I couldn't find any punch records for 16 Aug 2026 — no check-in or "
                   "check-out was logged that day. If you meant a different day, just "
                   "tell me the date and I'll check that one.")


@pytest.mark.asyncio
async def test_erp_timeout_gives_friendly_retry_message(state):
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(side_effect=erp_client.ErpApiTimeout("x"))):
        result = await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert "try again in a moment" in msg
    assert result["response_text"] == msg


@pytest.mark.asyncio
async def test_erp_unavailable_gives_friendly_unavailable_message(state):
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(side_effect=erp_client.ErpApiUnavailable("x"))):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert "unable to reach the attendance system" in msg


@pytest.mark.asyncio
async def test_erp_business_failure_surfaces_erp_message(state):
    fake_response = {"http_status": 400, "body": {"success": False, "message": "Invalid date requested."}}
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        await punch_details_node(state, writer)

    msg = _writer_done_event(writer)["message"]
    assert msg == "Invalid date requested."


@pytest.mark.asyncio
async def test_yesterday_query_resolves_and_forwards_date_to_erp_client(state):
    """AC5 — "yesterday" is resolved to a literal YYYY-MM-DD before
    calling erp-api, which understands nothing else. The LLM classifies
    the phrase; the date itself is still computed here."""
    state["query"] = "what were my punch times yesterday"
    llm_response = {"choices": [{"message": {"content": '{"type": "yesterday"}'}}], "usage": {}}
    fake_response = {"http_status": 200, "body": {"success": True, "data": {"sessions": []}}}
    mock_get = AsyncMock(return_value=fake_response)
    writer = MagicMock()
    with patch.object(punch_details, "_call_llm", new=AsyncMock(return_value=llm_response)), \
         patch.object(erp_client, "get_punch_details", new=mock_get):
        await punch_details_node(state, writer)

    expected_date = (_today() - timedelta(days=1)).isoformat()
    mock_get.assert_awaited_once_with(
        "employee-jwt", date=expected_date, company_id=1, conversation_id="conv-1",
    )


@pytest.mark.asyncio
async def test_no_date_in_query_calls_erp_client_with_no_date(state):
    """"today"/unspecified -> None is passed through, letting erp-api
    default to today itself rather than Helix AI guessing a date string."""
    fake_response = {"http_status": 200, "body": {"success": True, "data": {"sessions": []}}}
    mock_get = AsyncMock(return_value=fake_response)
    writer = MagicMock()
    with patch.object(erp_client, "get_punch_details", new=mock_get):
        await punch_details_node(state, writer)

    mock_get.assert_awaited_once_with(
        "employee-jwt", date=None, company_id=1, conversation_id="conv-1",
    )


@pytest.mark.asyncio
async def test_node_sends_the_llm_resolved_date_to_erp_api(state):
    """End-to-end through the node: the LLM returns a SYMBOL, Python turns
    it into the date, and that date is what erp_client is called with.
    Note the symbol carries no computed date at all — "explicit_single"
    plus the parsed components is the most the LLM is ever asked for."""
    state["query"] = "show me my punch details for 21 July 2026"
    llm_response = {
        "choices": [{"message": {"content": '{"type": "explicit_single", "explicit_date": "2026-07-21"}'}}],
        "usage": {"prompt_tokens": 20, "completion_tokens": 5, "total_tokens": 25},
    }
    fake_response = {"http_status": 200, "body": {"success": True, "data": {"sessions": []}}}
    mock_get = AsyncMock(return_value=fake_response)
    writer = MagicMock()
    with patch.object(punch_details, "_call_llm", new=AsyncMock(return_value=llm_response)), \
         patch.object(erp_client, "get_punch_details", new=mock_get):
        await punch_details_node(state, writer)

    mock_get.assert_awaited_once_with(
        "employee-jwt", date="2026-07-21", company_id=1, conversation_id="conv-1",
    )


@pytest.mark.asyncio
async def test_llm_extraction_failure_falls_back_to_none_date(state):
    """If the LLM call itself errors, the query still gets answered
    (against erp-api's own default) instead of the whole feature failing.

    The LLM is the primary path now, so an outage falls back to
    date_query_resolver's deterministic matchers — a safety net, not a
    first pass. This query is one neither layer can resolve ("janx" is not
    a month), so the fallback finds nothing either and date=None is the
    correct outcome. See
    test_llm_outage_falls_back_to_deterministic_resolution below for the
    case where the safety net actually catches something."""
    state["query"] = "show me my punch details for janx"
    fake_response = {"http_status": 200, "body": {"success": True, "data": {"sessions": []}}}
    mock_get = AsyncMock(return_value=fake_response)
    writer = MagicMock()
    with patch.object(punch_details, "_call_llm", new=AsyncMock(side_effect=RuntimeError("LLM down"))), \
         patch.object(erp_client, "get_punch_details", new=mock_get):
        await punch_details_node(state, writer)

    mock_get.assert_awaited_once_with(
        "employee-jwt", date=None, company_id=1, conversation_id="conv-1",
    )


@pytest.mark.asyncio
async def test_llm_outage_falls_back_to_deterministic_resolution(state):
    """The LLM is the only path that READS the query in normal operation,
    but it must not be a single point of failure: when the call itself
    can't be made, date_query_resolver's own matchers still answer a
    phrase they recognize. Without this net an unreachable model would
    leave the date at None, and erp-api's default is TODAY — silently
    answering an unrelated day, the failure mode this node guards against
    everywhere else."""
    state["query"] = "punch details for 2026-07-01"
    fake_response = {"http_status": 200, "body": {"success": True, "data": {"sessions": []}}}
    mock_get = AsyncMock(return_value=fake_response)
    writer = MagicMock()
    with patch.object(punch_details, "_call_llm", new=AsyncMock(side_effect=RuntimeError("LLM down"))), \
         patch.object(erp_client, "get_punch_details", new=mock_get):
        await punch_details_node(state, writer)

    mock_get.assert_awaited_once_with(
        "employee-jwt", date="2026-07-01", company_id=1, conversation_id="conv-1",
    )


@pytest.mark.asyncio
async def test_malformed_llm_output_does_not_reach_erp_api_as_a_wrong_date(state):
    """A response that isn't a usable expression must degrade to the
    deterministic fallback, never to a fabricated date."""
    state["query"] = "what were my punch times"
    llm_response = {"choices": [{"message": {"content": "sure! it was last tuesday"}}], "usage": {}}
    fake_response = {"http_status": 200, "body": {"success": True, "data": {"sessions": []}}}
    mock_get = AsyncMock(return_value=fake_response)
    writer = MagicMock()
    with patch.object(punch_details, "_call_llm", new=AsyncMock(return_value=llm_response)), \
         patch.object(erp_client, "get_punch_details", new=mock_get):
        await punch_details_node(state, writer)

    mock_get.assert_awaited_once_with(
        "employee-jwt", date=None, company_id=1, conversation_id="conv-1",
    )


@pytest.mark.asyncio
async def test_llm_date_extraction_usage_is_recorded(state):
    """The date call's token usage must show up in usage_events for cost
    accounting. ("today"/"yesterday" alone are read without the model - see
    punch_details._names_one_simple_day - so the query names a weekday.)"""
    state["query"] = "punch time last friday"
    llm_response = {
        "choices": [{"message": {"content": '{"type": "yesterday"}'}}],
        "usage": {"prompt_tokens": 300, "completion_tokens": 12, "total_tokens": 312},
    }
    fake_response = {"http_status": 200, "body": {"success": True, "data": {"sessions": []}}}
    writer = MagicMock()
    with patch.object(punch_details, "_call_llm", new=AsyncMock(return_value=llm_response)), \
         patch.object(erp_client, "get_punch_details", new=AsyncMock(return_value=fake_response)):
        result = await punch_details_node(state, writer)

    sources = [e["source"] for e in result["usage_events"]]
    assert "punch_date_extraction" in sources


# ── Intent classification (fast_classify routes punch queries correctly) ────

from services.nlp_service import fast_classify  # noqa: E402


@pytest.mark.parametrize("query", [
    "what were my punch times today",
    "show me yesterday punch details",
    "what time did I check in",
    "what time did I check out",
    "total work hours today",
    "what was my check in time last friday",
])
def test_fast_classify_routes_punch_queries_to_punch_details(query):
    intent, is_hr, confidence = fast_classify(query)
    assert intent == "punch_details"
    assert is_hr is True
    assert confidence >= 0.5


@pytest.mark.parametrize("query", [
    "my shift timing",
    "my shift details",
    "what is my shift start time",
    "what is my shift end time",
    "show my assigned shift",
])
def test_bare_shift_vocabulary_belongs_to_shift_query_not_punch_details(query):
    """FR-06.1 vs FR-03.2. These used to be punch_details keywords, which put
    "my shift timing" under BOTH intents (it was a worked example in each
    one's classifier-prompt definition too). The standing assignment is
    shift_query; punch_details keeps the day-scoped record."""
    intent, is_hr, confidence = fast_classify(query)
    assert intent == "shift_query"
    assert is_hr is True
    assert confidence >= 0.5


@pytest.mark.parametrize("query", [
    "my shift timing today",
    "what was my shift timing yesterday",
    "my shift details on 21 July",
    "shift timing last friday",
    "todays shift",
])
def test_shift_vocabulary_with_a_named_day_goes_back_to_punch_details(query):
    """The date-presence half of the split: a day that could HAVE a record
    makes the same wording a punch_details question."""
    intent, _, confidence = fast_classify(query)
    assert intent == "punch_details", query
    assert confidence >= 0.5


def test_forward_looking_shift_question_stays_shift_query():
    """No punch record can exist for a day that hasn't happened, so
    "tomorrow" must not pull a shift question into punch_details —
    shift_query_node answers it with the current assignment and says so."""
    assert fast_classify("my shift timing tomorrow")[0] == "shift_query"


def test_fast_classify_still_routes_generic_attendance_chat_separately():
    """WFH/office-hours policy chat should NOT be swallowed into the
    live punch-details lookup — it has no specific day to query."""
    intent, is_hr, _ = fast_classify("what is the work from home policy")
    assert intent == "attendance"


# ── Graph routing ────────────────────────────────────────────────────────────

from services.hr_graph import _route_after_classify  # noqa: E402


def test_route_after_classify_sends_punch_details_intent_to_its_node():
    state = {"intent": "punch_details", "is_hr": True, "error": None}
    assert _route_after_classify(state) == "punch_details_node"


def test_route_after_classify_error_short_circuits_before_punch_details():
    state = {"intent": "punch_details", "is_hr": True, "error": "flagged"}
    from langgraph.graph import END
    assert _route_after_classify(state) == END
