"""QA: replies rendered as an EMPTY bubble - only a timestamp - and the text
appeared after a refresh ("1 day SL tomorrow", "meri leave cancel kar do").

Two backend causes, both about what reaches the client, not what was saved:

  * classify_node answered the bare-leave-type question with a "done" and
    no "intent" event before it - the only reply streamed that way;
  * main.py's error and exception paths closed the turn with a "done" that
    carried no message at all.

Plus the classification half of the first report: a leave type with a
duration and a day is an application, not "balance, view, eligibility, or
apply?".
"""

import json
from unittest.mock import AsyncMock, patch

import pytest

import main
import services.classify_node as classify_node
from services.nlp_service import fast_classify, is_leave_type_apply_request


@pytest.mark.parametrize("query", [
    "1 day SL tomorrow", "2 days CL from monday", "half day SL tomorrow",
    "3 days of earned leave from 5th oct", "two days sick leave on friday",
    "cl for 2 days from monday",
])
def test_a_leave_type_with_a_duration_and_day_is_an_application(query):
    assert is_leave_type_apply_request(query) is True
    assert fast_classify(query)[0] == "apply_leave"


@pytest.mark.parametrize("query,intent", [
    ("2 days sick leave policy", "policy"),
    ("how many sick leaves", "leave_balance"),
    ("show my sick leaves", "leave_status"),
    ("3 days cl left?", "leave_balance"),
])
def test_questions_about_a_leave_type_are_not_applications(query, intent):
    assert is_leave_type_apply_request(query) is False
    assert fast_classify(query)[0] == intent


async def test_the_leave_type_question_streams_an_intent_event_before_done(monkeypatch):
    async def _no_shift(query):
        return None, 0.0, None

    async def _llm(prompt, labels, fallback_label="unknown"):
        return "policy", None, False

    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm)
    monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda *a, **k: None)
    monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: None)
    monkeypatch.setattr(classify_node.leave_type_clarify_state, "set_state", lambda *a, **k: None)
    events = []

    out = await classify_node.classify_node(
        {"query": "sick leave", "company_id": 1, "conversation_id": "c", "bearer_token": "t",
         "usage_events": [], "is_manager": False}, events.append)

    assert out["intent"] == "leave_type_clarify"
    types = [e["type"] for e in events]
    # The text as a chunk too: with only intent + done, "el" / "cl" / "sl"
    # still rendered as empty bubbles live.
    assert types == ["intent", "chunk", "done"]
    assert events[1]["content"] == events[2]["message"]
    assert events[2]["message"]


# =============================================================================
# main.py: a failed turn still closes with text
# =============================================================================

async def _stream(graph_events=None, raise_exc=None):
    async def _astream(state, stream_mode=None):
        for ev in graph_events or []:
            yield ev
        if raise_exc:
            raise raise_exc

    with patch.object(main.hr_graph, "astream", _astream), \
            patch.object(main, "_finalize_ai_stream", AsyncMock()):
        chunks = [c async for c in main._ai_stream(
            "q", [], "conv", 1, False, {}, None, 0.0, "1.2.3.4")]
    return [json.loads(c.split("data:", 1)[1]) for c in chunks if "data:" in c]


def _done(payloads):
    return [p for p in payloads if p.get("type") == "done"][-1]


def _assert_helix_fallback(payloads):
    """A failed turn is an ordinary reply: no "error" event (the client turns
    that into "something went wrong"), blocked False, the Helix text in both
    the chunk and the single closing done."""
    assert [p for p in payloads if p.get("type") == "error"] == []
    dones = [p for p in payloads if p.get("type") == "done"]
    assert len(dones) == 1
    done = dones[0]
    assert done["blocked"] is False
    assert done["message"] == main._STREAM_FAILURE_MESSAGE
    assert done["data"]["answer"] == main._STREAM_FAILURE_MESSAGE
    assert "Helix AI" in done["message"]
    chunks = [p for p in payloads if p.get("type") == "chunk"]
    assert chunks and chunks[-1]["content"] == main._STREAM_FAILURE_MESSAGE


async def test_an_exception_mid_turn_closes_with_the_helix_reply():
    payloads = await _stream(raise_exc=RuntimeError("internal detail"))

    _assert_helix_fallback(payloads)
    assert all("internal detail" not in json.dumps(p) for p in payloads)


async def test_an_error_event_becomes_the_helix_reply():
    """Live: the LLM classifier was unreachable, classify_node emitted
    "error" + a blocked done, and the client showed "something went wrong"."""
    payloads = await _stream(graph_events=[{"type": "error", "message": "Could you rephrase that?"}])

    _assert_helix_fallback(payloads)


async def test_a_graph_that_ends_without_a_reply_still_answers():
    payloads = await _stream(graph_events=[{"type": "intent", "intent": "general"}])

    _assert_helix_fallback(payloads)


async def test_a_normal_done_is_not_followed_by_a_fallback():
    done = {"type": "done", "intent": "greeting", "data": {"answer": "Hi!"}}
    with patch.object(main, "_persist_and_build_done",
                      AsyncMock(side_effect=lambda ev, *a: {**ev, "cached": False})):
        payloads = await _stream(graph_events=[{"type": "chunk", "content": "Hi!"}, done])

    dones = [p for p in payloads if p.get("type") == "done"]
    assert len(dones) == 1 and dones[0]["data"]["answer"] == "Hi!"


async def test_a_guardrail_refusal_is_not_marked_blocked():
    with patch.object(main, "save_message", lambda *a, **k: None):
        payloads = await _stream(graph_events=[
            {"type": "guardrail", "stage": "input", "status": "failed", "message": "Not allowed."}])

    done = _done(payloads)
    assert done["blocked"] is False
    assert done["message"] == "Not allowed."


@pytest.mark.parametrize("query,slug,word", [
    ("el", "earned_leave", "earned"),          # reported live: streamed as intent "policy"
    ("sick leave", "sick_leave", "sick"),
    ("cl", "casual_leave", "casual"),
])
async def test_the_leave_type_question_is_streamed_as_a_clarification(monkeypatch, query, slug, word):
    """{"query": "el"} came back intent "policy", with the "balance, applied,
    eligibility or apply?" question as a policy answer. It is a question back
    to the employee: clarify_needed, with the choices as options."""
    async def _no_shift(q):
        return None, 0.0, None

    async def _llm(prompt, labels, fallback_label="unknown"):
        return "policy", None, False

    monkeypatch.setattr(classify_node.ai_service, "classify_shift_intent", _no_shift)
    monkeypatch.setattr(classify_node, "classify_intent_structured", _llm)
    monkeypatch.setattr(classify_node.slot_store, "get_slots", lambda *a, **k: None)
    monkeypatch.setattr(classify_node.leave_slot_service, "get_slots", lambda *a, **k: None)
    stored = {}
    monkeypatch.setattr(classify_node.leave_type_clarify_state, "set_state",
                        lambda c, v, state: stored.update(state))
    events = []

    out = await classify_node.classify_node(
        {"query": query, "company_id": 1, "conversation_id": "c", "bearer_token": "t",
         "usage_events": [], "is_manager": False}, events.append)

    # Internally still the leave-type clarification, so the reply resolves as before.
    assert out["intent"] == "leave_type_clarify"
    assert stored == {"leave_type_slug": slug}
    intent_event, chunk, done = events
    assert chunk["type"] == "chunk" and chunk["content"] == done["message"]
    assert intent_event["intent"] == "clarify_needed"
    assert done["intent"] == "clarify_needed"
    assert done["data"]["answer"] == done["message"]
    assert f"{word} leave balance" in done["message"]
    # balance, applied, eligibility, apply — and that type's leave policy.
    assert len(done["data"]["options"]) == 5
    assert done["data"]["options"][-1].lower() == f"{word} leave policy"
    assert done["data"]["options"][0].lower() == f"{word} leave balance"
    assert done["data"]["clarify_type"] == "leave_type"
    assert done["data"]["leave_type"] == slug
    assert all(e.get("intent") != "policy" for e in events)
