"""
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 (
    _resolve_date_deterministic,
    _format_sessions,
    _build_date_extraction_prompt,
    _today,
    punch_details_node,
)


# ── _resolve_date_deterministic (AC5) ───────────────────────────────────────

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


def test_resolve_date_no_date_phrase_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_date_deterministic("what were my punch times", TODAY) is None


def test_resolve_date_today_keyword_returns_none():
    assert _resolve_date_deterministic("what were my punch times today", TODAY) is None


def test_resolve_date_yesterday():
    assert _resolve_date_deterministic("show my punch details yesterday", TODAY) == "2026-08-17"


def test_resolve_date_last_friday():
    # TODAY is Tuesday 2026-08-18; the most recent past Friday is 2026-08-14.
    assert _resolve_date_deterministic("what was my check in time last friday", TODAY) == "2026-08-14"


def test_resolve_date_last_weekday_on_that_same_weekday_goes_back_a_full_week():
    tuesday = date(2026, 8, 18)
    assert _resolve_date_deterministic("attendance last tuesday", tuesday) == "2026-08-11"


def test_resolve_date_last_weekday_tolerates_a_filler_word():
    """Regression test — "punch time last for saturday" previously matched
    nothing at all: \\blast\\s+(saturday|...)\\b requires "last" to be
    IMMEDIATELY followed by the weekday name, so the inserted "for" broke
    the match entirely. requested_date silently stayed None and the query
    got answered for TODAY instead of last Saturday. "for"/"on" between
    "last" and the weekday are now tolerated."""
    assert _resolve_date_deterministic("punch time last for saturday", TODAY) == "2026-08-15"
    assert _resolve_date_deterministic("punch time last on saturday", TODAY) == "2026-08-15"


def test_resolve_date_explicit_iso():
    assert _resolve_date_deterministic("punch details for 2026-07-01", TODAY) == "2026-07-01"


# ── Compound "<year/month qualifier> + <ordinal weekday>" resolution ────────
# TODAY = Tuesday 2026-08-18 for all cases below unless noted.

def test_resolve_date_last_month_first_friday():
    # last month = July 2026; July 1, 2026 is a Wednesday -> first Friday = July 3.
    assert _resolve_date_deterministic("what was last month first friday punch time", TODAY) == "2026-07-03"


def test_resolve_date_last_year_first_month_last_friday():
    """Regression test — this exact phrasing previously matched the bare
    _LAST_WEEKDAY_PATTERN on just the trailing "last friday" and silently
    ignored "last year first month", resolving to this year's most recent
    Friday (over a year off from what was actually asked). January 31, 2025
    is a Friday, so "last Friday of January 2025" is January 31 itself."""
    result = _resolve_date_deterministic(
        "what was the punch time last year first month last friday", TODAY,
    )
    assert result == "2025-01-31"


def test_resolve_date_last_year_last_month_last_friday():
    """Regression test — "last month" is ambiguous: alone it means "one
    calendar month before today", but alongside an explicit year it means
    "the last (December) month of that year" — the same ordinal reading
    "last year FIRST month" already gets for January. Treating it as
    relative-to-today here previously gave "last year last month" = July of
    last year (today's month minus one, year minus one — two independent
    offsets) instead of December of last year. December 26, 2025 is a
    Friday, so "last year's last month's last Friday" = Dec 26, 2025."""
    result = _resolve_date_deterministic(
        "what was punch time last year last month last friday", TODAY,
    )
    assert result == "2025-12-26"


def test_resolve_date_last_week_wednesday():
    """Regression test — "last week Wednesday" previously matched neither
    the ordinal-weekday compound resolver (no year/month qualifier) nor the
    bare _LAST_WEEKDAY_PATTERN ("last" isn't immediately followed by the
    weekday name, "week" is in between) — silently defaulted to today.
    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_date_deterministic("punch time last week wednesday", TODAY) == "2026-08-12"


def test_resolve_date_this_week_friday():
    # This week (Aug 17-23): Friday = Aug 21.
    assert _resolve_date_deterministic("punch time this week friday", TODAY) == "2026-08-21"


def test_resolve_date_last_week_weekday_order_independent():
    assert _resolve_date_deterministic("wednesday last week punch time", TODAY) == "2026-08-12"


def test_resolve_date_last_week_weekday_disagrees_with_bare_last_weekday():
    """"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 resolvers actually disagree when
    they should, not just coincidentally match."""
    thursday = date(2026, 8, 27)
    assert _resolve_date_deterministic("last wednesday", thursday) == "2026-08-26"
    assert _resolve_date_deterministic("last week wednesday", thursday) == "2026-08-19"


def test_resolve_date_second_monday_of_this_month():
    # August 2026: Aug 1 is a Saturday -> first Monday = Aug 3, second = Aug 10.
    assert _resolve_date_deterministic("second monday of this month", TODAY) == "2026-08-10"


def test_resolve_date_ordinal_weekday_with_explicit_month_and_year():
    # January 2025: Jan 1 is a Wednesday -> first Friday = Jan 3.
    assert _resolve_date_deterministic("first friday of january 2025", TODAY) == "2025-01-03"


def test_resolve_date_last_month_rolls_year_back_in_january():
    """"last month" said in January must resolve to December of the PREVIOUS
    year, not month=12 of the current year — the exact class of off-by-one
    that a naive today.month - 1 (without checking for the January wrap)
    would get wrong."""
    january_today = date(2026, 1, 15)  # Thursday
    # December 2025: Dec 1 is a Monday -> first Friday = Dec 5.
    result = _resolve_date_deterministic("last month first friday", january_today)
    assert result == "2025-12-05"


def test_resolve_date_bare_last_weekday_unaffected_by_compound_resolver():
    """A plain "last Friday" with no year/month qualifier anywhere must
    still resolve exactly as before — the compound resolver requires an
    explicit year/month qualifier and returns None (deferring to the
    existing bare-weekday handling) when there isn't one."""
    assert _resolve_date_deterministic("what time did I check in last friday", TODAY) == "2026-08-14"


def test_resolve_date_bare_ordinal_weekday_with_no_scope_falls_through():
    """"second Friday" with no year/month named anywhere is too ambiguous
    to guess a month for — returns None (falls through to the LLM-fallback
    gate, same as today's un-parseable-date behavior), not a fabricated
    date in some assumed month."""
    assert _resolve_date_deterministic("what about second friday", TODAY) is None


# ── _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: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: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
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:00" in msg and "18:30:00" 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 "No punch records found" not in msg
    assert "2026-07-01 10:00:00" in msg and "2026-07-01 11:01:00" 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 == "No punch records found for 2026-08-16 as it was a Weekly Off."


@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 == "No punch records found for 2026-08-18. Shift: Testing Manual Shift (10:05:00–19:00:00)."


@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 == "No punch records found for 2026-08-14. Shift: HR Test Shift (10:00:00–19:00:00)."


@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 == "No punch records found for 2026-08-16."


@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 before calling erp-api, which only
    understands a literal YYYY-MM-DD."""
    state["query"] = "what were my punch times yesterday"
    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)

    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_explicit_date_phrase_falls_back_to_llm_extraction(state):
    """"21 July 2026" isn't covered by the deterministic rules, so it must
    trigger the LLM fallback rather than silently defaulting to today."""
    state["query"] = "show me my punch details for 21 July 2026"
    llm_response = {
        "choices": [{"message": {"content": '{"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",
    )


def test_date_extraction_prompt_forces_day_first_for_ambiguous_slash_dates():
    """Regression test — confirmed live: "10/08/2026" was resolved by the
    LLM as 2026-10-08 (US MM/DD/YYYY) instead of the intended 2026-08-10
    (DD/MM/YYYY), because the prompt only implied day-first convention via
    one example ("21/07/2026") where 21 can't possibly be a month — that
    example doesn't disambiguate when BOTH numbers are <= 12. 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_extraction_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


@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.

    Query deliberately has a date HINT (matches _DATE_HINT_PATTERN, so an
    LLM call is actually attempted) but no day number — "21 July 2026"
    used to be here, but that now resolves deterministically via
    _resolve_explicit_date_deterministic and never reaches the LLM at all,
    making this test not exercise the fallback it's named for."""
    state["query"] = "show me my punch details for July"
    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",
    )


# ── 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",
    "my shift timing",
    "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


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
