"""Ticket (Oct 22): "tough", "wow", "no way", "how come?" came back as
dictionary entries, 4-19 s late.

  * The race provider searched the web on EVERY message, with the user's raw
    text, and the model answered from dictionary pages. The model now decides:
    it answers, or replies "<search>query</search>" and the search runs with
    ITS query.
  * A manager's short word guessed as an employee's name and not found was
    handed to that always-search lane. It is now answered by the model alone.
  * Small talk was steered back to HR on every reply ("no way" -> "How can I
    help with HR?"). The prompts now say to respond in context.
"""
import pytest
from unittest.mock import AsyncMock, patch

import services.ai_service as ai
import services.hr_graph as hg
import services.individual_report as individual_report
import services.live_info as live_info

pytestmark = pytest.mark.asyncio


class _FakeRace:
    """Stands in for _call_race_stream: the first call (the decision pass)
    streams `first`, every later call streams `second`. Records each call's
    messages and whether the first stream was closed."""

    def __init__(self, first, second=("an answer",), usage=None):
        self.first, self.second, self.usage = list(first), list(second), usage
        self.calls, self.first_closed = [], False

    def __call__(self, messages, max_tokens=None, model=None):
        self.calls.append(messages)
        chunks = self.first if len(self.calls) == 1 else self.second
        return self._gen(chunks, len(self.calls) == 1)

    async def _gen(self, chunks, is_first):
        try:
            if self.usage and is_first:
                yield {"type": "usage", "usage": self.usage}
            for c in chunks:
                yield {"type": "chunk", "content": c}
        finally:
            if is_first:
                self.first_closed = True


async def _run(fake, query="tough", searched=None):
    async def _search(q, k=5):
        if searched is not None:
            searched.append(q)
        return [{"title": "Result", "url": "https://example.com", "content": "fresh fact"}]

    msgs = [{"role": "system", "content": "sys"}, {"role": "user", "content": query}]
    with patch.object(ai, "_call_race_stream", fake), \
            patch.object(ai, "_call_race_brave_search", _search):
        return [e async for e in ai._call_race_stream_with_search(msgs)]


def _text(events):
    return "".join(e["content"] for e in events if e["type"] == "chunk")


# ── the model decides whether to search ────────────────────────────────────

async def test_an_ordinary_answer_is_not_searched():
    searched = []
    fake = _FakeRace(["That does sound ", "tough - what happened?"])
    events = await _run(fake, searched=searched)

    assert searched == []
    assert len(fake.calls) == 1
    assert not [e for e in events if e["type"] == "searching"]
    assert _text(events) == "That does sound tough - what happened?"


async def test_the_answer_streams_on_once_it_is_clearly_not_a_search():
    opening = "x" * ai._SEARCH_LOOKAHEAD_CHARS
    fake = _FakeRace([opening, "Anything ", "else?"])
    events = await _run(fake, "wow")
    chunks = [e["content"] for e in events if e["type"] == "chunk"]
    assert chunks == [opening, "Anything ", "else?"]


async def test_a_short_answer_arrives_whole():
    fake = _FakeRace(["Wow indeed! ", "Anything ", "else?"])
    events = await _run(fake, "wow")
    assert [e["content"] for e in events if e["type"] == "chunk"] == ["Wow indeed! Anything else?"]


async def test_a_request_after_a_sentence_of_preamble_is_still_a_search():
    """QA PR-107: 'Need to find dictionary entry for "wow".<search>wow definition
    dictionary</search>' was streamed to the user, tag and all."""
    searched = []
    fake = _FakeRace(['Need to find dictionary entry for "wow".', "<search>wow definition ",
                      "dictionary</search>", "“Wow” is an interjection"],
                     second=["According to Merriam-Webster, ..."])
    events = await _run(fake, "what does wow mean? cite a dictionary source", searched)
    assert searched == ["wow definition dictionary"]
    assert _text(events) == "According to Merriam-Webster, ..."


async def test_a_tag_split_at_the_lookahead_boundary_is_caught():
    searched = []
    opening = "y" * (ai._SEARCH_LOOKAHEAD_CHARS - 3)
    await _run(_FakeRace([opening + "<se", "arch>split query</search>"]), "q", searched)
    assert searched == ["split query"]


async def test_an_answer_that_starts_like_the_marker_is_still_an_answer():
    """"<" alone could be "<search>" - held until it can tell, never lost."""
    fake = _FakeRace(["<", "3 So, how come? Because ", "the order changed."])
    events = await _run(fake, "how come?")
    assert _text(events) == "<3 So, how come? Because the order changed."
    assert len(fake.calls) == 1


async def test_a_one_letter_answer_is_not_swallowed():
    fake = _FakeRace(["<"])
    assert _text(await _run(fake, "x")) == "<"


async def test_a_search_request_searches_with_the_models_query():
    searched = []
    fake = _FakeRace(["<sea", "rch>current prime minister of India</search>"],
                     second=["Narendra Modi, according to Result."])
    events = await _run(fake, "who is the pm of india now", searched)

    assert searched == ["current prime minister of India"]
    assert [e["type"] for e in events][0] == "searching"
    assert _text(events) == "Narendra Modi, according to Result."
    assert "search>" not in _text(events)
    assert fake.first_closed


async def test_the_request_may_end_the_stream_without_its_closing_tag():
    searched = []
    await _run(_FakeRace(["<search>ICC rankings"]), "rankings", searched)
    assert searched == ["ICC rankings"]


async def test_a_guessed_answer_after_the_request_is_neither_the_query_nor_shown():
    """Live: gpt-oss wrote the query, then its own guess at the answer on the
    same line - and the whole line went out as the search query."""
    searched = []
    fake = _FakeRace(["<search>current prime minister of India</search>",
                      "As of 2026, Narendra Modi is still..."], second=["From the results."])
    events = await _run(fake, "who is the pm", searched)
    assert searched == ["current prime minister of India"]
    assert _text(events) == "From the results."
    assert fake.first_closed


async def test_a_runaway_request_is_cut_short():
    searched = []
    await _run(_FakeRace(["<search>pm of india " + "and more " * 60]), "pm", searched)
    assert len(searched[0]) <= ai._SEARCH_QUERY_MAX_CHARS


async def test_markdown_around_the_request_is_tolerated():
    searched = []
    await _run(_FakeRace(["`<search>\"bitcoin price today\"</search>`"]), "btc", searched)
    assert searched == ["bitcoin price today"]


async def test_an_empty_request_falls_back_to_the_users_message():
    searched = []
    await _run(_FakeRace(["<search></search>"]), "latest news", searched)
    assert searched == ["latest news"]


async def test_the_results_reach_the_answer_and_the_instruction_does_not():
    fake = _FakeRace(["<search>x</search>"], second=["ok"])
    await _run(fake, "q")
    first, second = fake.calls
    assert any(ai._SEARCH_DECISION_INSTRUCTION == m["content"] for m in first)
    assert not any(ai._SEARCH_DECISION_INSTRUCTION == m["content"] for m in second)
    assert any("fresh fact" in m["content"] for m in second)
    assert second[-1] == {"role": "user", "content": "q"}


async def test_the_instruction_sits_just_before_the_users_message():
    fake = _FakeRace(["hi"])
    await _run(fake, "q")
    roles = [(m["role"], m["content"]) for m in fake.calls[0]]
    assert roles[-2] == ("system", ai._SEARCH_DECISION_INSTRUCTION)
    assert roles[-1] == ("user", "q")


async def test_usage_from_the_decision_pass_is_passed_on():
    usage = {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
    events = await _run(_FakeRace(["hello"], usage=usage))
    assert {"type": "usage", "usage": usage} in events


def test_the_instruction_keeps_conversation_off_the_web():
    p = ai._SEARCH_DECISION_INSTRUCTION.lower()
    assert "do not search for conversation" in p
    assert "not a request to define the word" in p


# ── a withdrawn name guess is answered by the model alone ──────────────────

def _withdrawn(query="tough"):
    return {"query": query, "intent": "non_hr", "is_hr": False, "usage_events": [],
            "company_id": 1, "conversation_id": "c1",
            "route_to": individual_report.GUESSED_SUBJECT_NOT_AN_EMPLOYEE}


def _capture(seen):
    async def _stream(messages, max_tokens=None, use_tools=True):
        seen["use_tools"] = use_tools
        yield {"type": "chunk", "content": "That sounds tough."}
    return _stream


@pytest.fixture
def _no_place(monkeypatch):
    monkeypatch.setattr(live_info, "looks_like_bare_place", lambda q: False)


async def test_non_hr_node_does_not_offer_search_for_a_withdrawn_guess(monkeypatch, _no_place):
    seen = {}
    monkeypatch.setattr(hg, "_call_llm_stream", _capture(seen))
    out = await hg.non_hr_node(_withdrawn(), lambda e: None)
    assert seen["use_tools"] is False
    assert out["response_text"] == "That sounds tough."


async def test_non_hr_node_still_offers_search_for_a_real_question(monkeypatch, _no_place):
    # The search path: with the sports source on, the live score answers it.
    monkeypatch.setenv("NON_HR_LIVE_SOURCES", "none")
    seen = {}
    monkeypatch.setattr(hg, "_call_llm_stream", _capture(seen))
    state = {**_withdrawn("who won the last world cup"), "route_to": None}
    await hg.non_hr_node(state, lambda e: None)
    assert seen["use_tools"] is True


async def test_general_chat_does_not_search_a_withdrawn_guess(monkeypatch):
    monkeypatch.setenv("GENERAL_CHAT_WEB_SEARCH_ENABLED", "true")
    seen = {}
    monkeypatch.setattr(hg, "_call_llm_stream", _capture(seen))
    await hg.general_chat_node(_withdrawn("wow"), lambda e: None)
    assert seen["use_tools"] is False


async def test_a_withdrawn_guess_never_reaches_the_search_through_the_real_dispatcher(
        monkeypatch, _no_place):
    """Outcome, not intent: with the race provider, no search call at all."""
    trap = AsyncMock(side_effect=AssertionError("searched a conversational word"))
    fake = _FakeRace(["Tough how? Tell me more."])
    events = []
    with patch.object(ai, "_call_race_brave_search", trap), \
            patch.object(ai, "_call_race_stream", fake), \
            patch.object(ai, "ACTIVE_LLM_PROVIDER", "race"):
        out = await hg.non_hr_node(_withdrawn(), events.append)
    trap.assert_not_called()
    assert not [e for e in events if e.get("type") == "searching"]
    assert out["response_text"] == "Tough how? Tell me more."


# ── conversational replies stay conversational ─────────────────────────────

@pytest.mark.parametrize("prompt", [ai.GENERAL_CHAT_SYSTEM_PROMPT, ai.GENERAL_CHAT_WEB_SEARCH_PROMPT])
def test_the_general_prompts_treat_short_messages_as_conversation(prompt):
    p = prompt.lower()
    assert "## conversation" in p
    assert "define\na word only when the user asks what it means" in p


async def _hr_reply_messages(monkeypatch, intent, query):
    seen = {}

    async def _stream(messages, max_tokens=None, use_tools=True):
        seen["messages"], seen["use_tools"] = messages, use_tools
        yield {"type": "chunk", "content": "ok"}

    monkeypatch.setattr(hg, "_call_llm_stream", _stream)
    monkeypatch.setenv("HR_WEB_SEARCH_ENABLED", "false")
    await hg.hr_response_node({"query": query, "intent": intent, "context": [],
                               "usage_events": []}, lambda e: None)
    return seen


async def test_a_small_talk_turn_is_told_it_is_conversation(monkeypatch):
    seen = await _hr_reply_messages(monkeypatch, "small_talk", "no way")
    contents = [m["content"] for m in seen["messages"] if m["role"] == "system"]
    assert any(c.startswith(ai.SMALL_TALK_TURN_INSTRUCTION) for c in contents)
    assert seen["use_tools"] is False


@pytest.mark.parametrize("intent, query", [
    ("greeting", "Joy"),            # QA: "What HR question can I help you with today?"
    ("greeting", "kaise?"),
    ("conversation_meta", "..."),   # QA: "How can I assist you with HR or workforce matters?"
    ("general_hr", "\U0001F44D"),   # no words at all, whatever it was classified as
])
async def test_conversational_turns_are_told_so(monkeypatch, intent, query):
    seen = await _hr_reply_messages(monkeypatch, intent, query)
    assert any(m["content"].startswith(ai.SMALL_TALK_TURN_INSTRUCTION) for m in seen["messages"])


async def test_a_first_message_is_told_nothing_came_before(monkeypatch):
    """QA: "wow" in a new chat got "those attendance details can be eye-opening"."""
    seen = await _hr_reply_messages(monkeypatch, "small_talk", "wow")
    assert ai.SMALL_TALK_TURN_INSTRUCTION + hg.NO_EARLIER_MESSAGES_NOTE in [
        m["content"] for m in seen["messages"]]


@pytest.mark.parametrize("intent, query", [
    ("conversation_meta", "what was my last question?"),
    ("general_hr", "what is a notice period"),
])
async def test_other_turns_are_not(monkeypatch, intent, query):
    seen = await _hr_reply_messages(monkeypatch, intent, query)
    assert not any(m["content"].startswith(ai.SMALL_TALK_TURN_INSTRUCTION) for m in seen["messages"])


def test_the_small_talk_instruction_keeps_hr_out_of_reactions():
    p = ai.SMALL_TALK_TURN_INSTRUCTION.lower()
    assert "do not steer the reply to hr" in p
    assert "never explain or define the word" in p
    assert "a greeting gets a greeting back" in p


async def test_a_withdrawn_guess_is_not_told_it_can_search(monkeypatch, _no_place):
    """QA: told "you can search the web" with no way to, the model wrote fake
    searches ('Searching web for "Dileep Anumla". Search results: ...')."""
    seen = {}

    async def _stream(messages, max_tokens=None, use_tools=True):
        seen["system"] = messages[0]["content"]
        yield {"type": "chunk", "content": "Who's Dileep?"}

    monkeypatch.setattr(hg, "_call_llm_stream", _stream)
    await hg.non_hr_node(_withdrawn("Dileep Anumla"), lambda e: None)
    assert seen["system"].startswith(ai.GENERAL_CHAT_SYSTEM_PROMPT)
    assert "you can search the web" not in seen["system"].lower()


def test_an_explicit_request_for_sources_is_searched():
    """QA PR-106..109: "cite a dictionary source" was answered from memory
    with an invented "Source: Merriam-Webster"."""
    p = ai._SEARCH_DECISION_INSTRUCTION.lower()
    assert "do search when the user asks you to" in p
    assert "never write a source, citation or link you have not" in p


# ── a leave-policy question does not wait on the document search ────────────

async def test_the_leave_configuration_is_tried_before_the_document_search(monkeypatch):
    """QA PR-131: "hmm, what is the leave policy?" took 10-12 s - the document
    search ran first, and its result was then ignored for the configuration."""
    import services.race_rag_service as rag
    calls = []

    async def _configured(state, query):
        calls.append(query)
        return "Your company's leave policy, as configured in Helixta:\n- **Casual Leave**: 12 days"

    monkeypatch.setattr(hg, "_configured_leave_policy_answer", _configured)
    monkeypatch.setattr(rag, "query_all_documents",
                        AsyncMock(side_effect=AssertionError("searched the documents")))
    state = {"query": "hmm, what is the leave policy?", "intent": "leave_policy",
             "context": [], "usage_events": []}
    out = await hg.policy_rag_node(state, lambda e: None)
    assert out["configured_policy_answer"].startswith("Your company's leave policy")

    events = []
    reply = await hg.hr_response_node({**state, **out}, events.append)
    assert reply["response_text"].startswith("Your company's leave policy")
    assert calls == ["hmm, what is the leave policy?"]  # fetched once, not twice


async def test_without_a_configuration_the_documents_are_still_searched(monkeypatch):
    import services.race_rag_service as rag
    monkeypatch.setattr(hg, "_configured_leave_policy_answer", AsyncMock(return_value=None))
    searched = AsyncMock(return_value=[])
    monkeypatch.setattr(rag, "query_all_documents", searched)
    out = await hg.policy_rag_node({"query": "what is the leave policy?", "intent": "leave_policy",
                                    "usage_events": []}, lambda e: None)
    searched.assert_awaited()
    assert out["policy_lookup_failed"] is True


# ── the classifier gets room to finish ──────────────────────────────────────

class _Resp:
    def __init__(self, body):
        self.body = body

    def raise_for_status(self):
        pass

    def json(self):
        return self.body


def _choice(content, finish):
    return {"choices": [{"message": {"content": content}, "finish_reason": finish}]}


async def test_a_classifier_that_ran_out_of_tokens_is_retried_with_room(monkeypatch):
    """QA: "who is my reporting manager?" -> "Sorry, I'm not sure what you're
    asking" because the reasoning used all 200 tokens and content was empty."""
    budgets = []

    async def _post(url, json=None, headers=None):
        budgets.append(json["max_tokens"])
        return _Resp(_choice(None, "length") if len(budgets) == 1
                     else _choice('{"intent": "general_hr"}', "stop"))

    monkeypatch.setattr(ai, "RACE_API_KEY", "k")
    monkeypatch.setattr(ai._http, "post", _post)
    raw = await ai._call_classification_race([{"role": "user", "content": "q"}], ["general_hr"])
    assert budgets == [400, 800]
    assert raw["choices"][0]["message"]["content"] == '{"intent": "general_hr"}'


def _reasoned_only(reasoning, finish="stop"):
    return {"choices": [{"message": {"content": None, "reasoning": reasoning},
                         "finish_reason": finish}]}


async def test_an_answer_left_in_a_finished_reasoning_is_read_from_it(monkeypatch):
    """QA CW-02/CW-13: "wow" -> content None, finish_reason "stop", reasoning
    'It's not greeting, just exclamation. Could be small_talk. Probably small_talk.'"""
    budgets = []
    reasoning = ('The user says "wow". That\'s small talk? It\'s an expression, maybe greeting? '
                 "It's not greeting, just exclamation. Could be small_talk. Probably small_talk.")

    async def _post(url, json=None, headers=None):
        budgets.append(json["max_tokens"])
        return _Resp(_reasoned_only(reasoning))

    monkeypatch.setattr(ai, "RACE_API_KEY", "k")
    monkeypatch.setattr(ai._http, "post", _post)
    raw = await ai._call_classification_race([{"role": "user", "content": "wow"}],
                                             ["greeting", "small_talk", "general_hr"])
    assert budgets == [400]  # it stopped: its reasoning is the answer, no second call
    assert raw["choices"][0]["message"]["content"] == '{"intent": "small_talk"}'


async def test_a_retry_that_answers_is_used_as_is(monkeypatch):
    replies = [_reasoned_only("Maybe greeting, or", finish="length"), _choice('{"intent": "greeting"}', "stop")]

    async def _post(url, json=None, headers=None):
        return _Resp(replies.pop(0))

    monkeypatch.setattr(ai, "RACE_API_KEY", "k")
    monkeypatch.setattr(ai._http, "post", _post)
    raw = await ai._call_classification_race([{"role": "user", "content": "hi"}],
                                             ["greeting", "small_talk"])
    assert raw["choices"][0]["message"]["content"] == '{"intent": "greeting"}'


async def test_reasoning_that_names_no_label_stays_unanswered(monkeypatch):
    async def _post(url, json=None, headers=None):
        return _Resp(_reasoned_only("Hard to say what this is."))

    monkeypatch.setattr(ai, "RACE_API_KEY", "k")
    monkeypatch.setattr(ai._http, "post", _post)
    raw = await ai._call_classification_race([{"role": "user", "content": "x"}], ["greeting"])
    assert raw["choices"][0]["message"]["content"] is None


async def test_an_answered_classification_is_not_retried(monkeypatch):
    budgets = []

    async def _post(url, json=None, headers=None):
        budgets.append(json["max_tokens"])
        return _Resp(_choice('{"intent": "greeting"}', "stop"))

    monkeypatch.setattr(ai, "RACE_API_KEY", "k")
    monkeypatch.setattr(ai._http, "post", _post)
    await ai._call_classification_race([{"role": "user", "content": "q"}], ["greeting"])
    assert budgets == [400]


def test_the_hr_prompt_answers_reactions_in_context():
    p = ai.HR_SYSTEM_PROMPT.lower()
    assert "respond to them in context" in p
    assert "do not end every conversational reply with an offer of hr help" in p
    assert "invite an hr question" not in p
