"""Regression tests for attendance_node's deterministic date pre-resolution
(Step 1 in services/attendance.py), wired to the shared
services/date_query_resolver.py module.

Confirmed live gap on this branch: attendance_node's Step 1 called the LLM
UNCONDITIONALLY for every single query — the deterministic dispatcher that
used to skip that call for unambiguous phrasing
("_resolve_attendance_type_deterministic", referenced only in surrounding
comments) no longer existed anywhere in the file; only its orphaned helper
functions/regexes remained, never called. This meant every query, including
trivially unambiguous ones ("yesterday", "last Friday"), depended on the LLM
correctly following its own extraction schema every time.

attendance_node had NO dedicated test file at all before this — these tests
both lock in the new deterministic-bypass behavior and give this node a
first baseline of coverage.
"""
import base64
import json
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

import services.attendance as attendance
import services.date_query_resolver as date_query_resolver


def _make_jwt(claims: dict) -> str:
    def b64(d):
        return base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode()
    return f"{b64({'alg': 'JWT'})}.{b64(claims)}.sig"


SELF_TOKEN = _make_jwt({"name": "Akash Jio", "role_id": "5", "emp_no": "geo2"})


def _refuse_llm(*args, **kwargs):
    raise AssertionError("the LLM date-extraction call must not run for a deterministic query")


class TestDeterministicQueriesSkipTheLlmEntirely:

    @pytest.mark.asyncio
    @pytest.mark.parametrize("query", [
        "attendance for last week Sunday",
        "attendance yesterday",
        "attendance for current day",
        "attendance last friday",
        "attendance for the upcoming 2 days",
        "attendance from last week to next week",
        "attendance for 2026-07-01",
        "attendance for 21 July 2026",
    ])
    async def test_common_phrasings_never_reach_the_llm(self, query):
        fake_response = {"success": True, "data": {"status": "Present", "records": []}}
        state = {"query": query, "bearer_token": SELF_TOKEN, "company_id": 1, "conversation_id": "c1"}
        writer = MagicMock()
        with patch.object(attendance, "_call_llm", new=_refuse_llm), \
             patch.object(attendance.attendance_service, "get_attendance_single", new=AsyncMock(return_value=fake_response)), \
             patch.object(attendance.attendance_service, "get_attendance_range", new=AsyncMock(return_value=fake_response)):
            result = await attendance.attendance_node(state, writer)
        assert "I couldn't figure out which date" not in result["response_text"]


class TestNamedEmployeeQueriesStillUseTheLlm:
    """_looks_like_named_employee_query is the gate — a query that LOOKS
    like it might name someone else must still go to the LLM (the only
    place employee_name gets extracted), never bypass it."""

    @pytest.mark.asyncio
    async def test_capitalized_name_routes_through_llm_and_is_denied(self):
        llm_called = {"v": False}

        async def _fake_llm(prompt, max_tokens=None, model=None):
            llm_called["v"] = True
            return {
                "choices": [{"message": {"content": json.dumps({
                    "type": "yesterday", "employee_name": "Priya Sharma",
                })}}],
                "usage": {},
            }

        state = {
            "query": "attendance for Priya Sharma yesterday",
            "bearer_token": SELF_TOKEN, "company_id": 1, "conversation_id": "c1",
        }
        writer = MagicMock()
        with patch.object(attendance, "_call_llm", new=_fake_llm):
            result = await attendance.attendance_node(state, writer)

        assert llm_called["v"] is True
        assert "I can only show your own attendance" in result["response_text"]


class TestDeterministicRangeResolution:

    @pytest.mark.asyncio
    async def test_range_query_calls_erp_with_correct_span_and_no_employee_name(self):
        mock_range = AsyncMock(return_value={"success": True, "data": {"records": []}})
        state = {
            "query": "attendance for last week",
            "bearer_token": SELF_TOKEN, "company_id": 1, "conversation_id": "c1",
        }
        writer = MagicMock()
        with patch.object(attendance, "_call_llm", new=_refuse_llm), \
             patch.object(attendance.attendance_service, "get_attendance_range", new=mock_range):
            await attendance.attendance_node(state, writer)

        assert mock_range.called
        assert mock_range.call_args.kwargs["employee_name"] is None
        start, end = mock_range.call_args.kwargs["start_date"], mock_range.call_args.kwargs["end_date"]
        assert (end - start).days == 6
        assert start.weekday() == 0  # Monday


class TestNoSuchOrdinalWeekdayAnsweredDirectly:

    @pytest.mark.asyncio
    async def test_nonexistent_fifth_weekday_never_calls_erp(self):
        mock_single = AsyncMock()
        state = {
            "query": "attendance for fifth wednesday of june 2026",
            "bearer_token": SELF_TOKEN, "company_id": 1, "conversation_id": "c1",
        }
        writer = MagicMock()
        with patch.object(attendance, "_call_llm", new=_refuse_llm), \
             patch.object(attendance.attendance_service, "get_attendance_single", new=mock_single):
            result = await attendance.attendance_node(state, writer)

        mock_single.assert_not_called()
        assert "June 2026" in result["response_text"]
        assert "Fifth Wednesday" in result["response_text"]
        assert "4 Wednesdays" in result["response_text"]


class TestSelfNameMentionStillNormalizedAfterDeterministicBypass:
    """A query naming the caller's OWN full name deterministically bails to
    the LLM (it looks like a named-employee query), but the LLM's extracted
    employee_name must still be nulled out by the existing self-reference
    check — the deterministic bypass added here must not disturb that."""

    @pytest.mark.asyncio
    async def test_own_name_still_resolves_to_self(self):
        async def _fake_llm(prompt, max_tokens=None, model=None):
            return {
                "choices": [{"message": {"content": json.dumps({
                    "type": "yesterday", "employee_name": "Akash Jio",
                })}}],
                "usage": {},
            }

        mock_single = AsyncMock(return_value={"success": True, "data": {"status": "Present"}})
        state = {
            "query": "attendance for Akash Jio yesterday",
            "bearer_token": SELF_TOKEN, "company_id": 1, "conversation_id": "c1",
        }
        writer = MagicMock()
        with patch.object(attendance, "_call_llm", new=_fake_llm), \
             patch.object(attendance.attendance_service, "get_attendance_single", new=mock_single):
            result = await attendance.attendance_node(state, writer)

        assert mock_single.call_args.kwargs["employee_name"] is None
        assert "Present" in result["response_text"]


class TestGenuinelyUnresolvableQueryStillFallsThroughToLlm:

    @pytest.mark.asyncio
    async def test_unresolvable_phrasing_uses_llm_fallback(self):
        async def _fake_llm(prompt, max_tokens=None, model=None):
            return {
                "choices": [{"message": {"content": json.dumps({"type": "unknown", "employee_name": None})}}],
                "usage": {},
            }

        mock_single = AsyncMock(return_value={"success": True, "data": {"status": "Present"}})
        state = {
            "query": "how was my attendance that one time",
            "bearer_token": SELF_TOKEN, "company_id": 1, "conversation_id": "c1",
        }
        writer = MagicMock()
        with patch.object(attendance, "_call_llm", new=_fake_llm), \
             patch.object(attendance.attendance_service, "get_attendance_single", new=mock_single):
            result = await attendance.attendance_node(state, writer)

        assert "Present" in result["response_text"]
