"""The general-purpose lane: a non-HR question answered by ACTIVE_LLM_PROVIDER.

  * `use_tools=False` unless GENERAL_CHAT_WEB_SEARCH_ENABLED is on — the
    default is True and on the race provider that searches the web on EVERY
    message, sending the raw user message out of the building. Off unless
    that switch says otherwise.
  * streamed like every other answer.
"""
import pytest
from unittest.mock import AsyncMock, patch

import services.hr_graph as hg

pytestmark = pytest.mark.asyncio


@pytest.fixture(autouse=True)
def _web_search_off(monkeypatch):
    """Every test here runs with the switch OFF unless it turns it on itself:
    a developer's .env (loaded into os.environ by load_dotenv) may enable it."""
    monkeypatch.setenv("GENERAL_CHAT_WEB_SEARCH_ENABLED", "false")


class _Writer:
    def __init__(self):
        self.events = []

    def __call__(self, ev):
        self.events.append(ev)

    def of_type(self, t):
        return [e for e in self.events if e.get("type") == t]


def _state(query="explain the difference between revenue and profit"):
    return {"query": query, "intent": "non_hr", "is_hr": False,
            "usage_events": [], "company_id": 1, "conversation_id": "c1"}


def _stream(text, usage=None):
    """Stands in for _call_llm_stream, yielding the text in two chunks so a
    node that forwards chunks live is distinguishable from one that buffers."""
    async def _gen(*args, **kwargs):
        half = len(text) // 2
        yield {"type": "chunk", "content": text[:half]}
        yield {"type": "chunk", "content": text[half:]}
        if usage:
            yield {"type": "usage", "usage": usage}
    return _gen


# ── it answers ──────────────────────────────────────────────────────────────

async def test_it_answers_a_general_question():
    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _stream("Revenue is total income.")):
        out = await hg.general_chat_node(_state(), w)

    assert out["response_text"] == "Revenue is total income."
    assert w.of_type("done")[0]["data"]["answer"] == "Revenue is total income."


async def test_the_turn_is_reported_as_non_hr():
    """So the analytics category comes out "general" and nothing downstream
    mistakes this for an HR answer."""
    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _stream("ok")):
        await hg.general_chat_node(_state(), w)

    assert w.of_type("done")[0]["is_hr"] is False


async def test_usage_is_tagged_general_chat():
    """FR-09 reports general vs HR volume off this tag."""
    w = _Writer()
    usage = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
    with patch.object(hg, "_call_llm_stream", _stream("ok", usage)):
        out = await hg.general_chat_node(_state(), w)

    assert [e["source"] for e in out["usage_events"]] == ["general_chat"]


# ── no web search unless switched on ────────────────────────────────────────

async def test_it_never_asks_for_web_search():
    """With GENERAL_CHAT_WEB_SEARCH_ENABLED off. The dispatcher default is
    use_tools=True; if this regresses, every general turn silently starts
    browsing."""
    seen = {}

    def _capture(*args, **kwargs):
        seen.update(kwargs)
        return _stream("ok")(*args, **kwargs)

    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _capture):
        await hg.general_chat_node(_state(), w)

    assert seen.get("use_tools") is False


async def test_no_search_function_is_reachable_from_this_node():
    """The stronger form of the test above: run the node through the REAL
    dispatcher with both search entry points booby-trapped. Asserting the
    kwarg proves intent; this proves outcome — if someone changes the
    dispatcher, flips the default, or adds a provider branch that searches,
    the kwarg test still passes and this one fails.

    Why it matters beyond scope: the race search path sends the raw user
    message to /v1/search/brave on EVERY call, so a regression here would
    quietly start posting what employees type to a third party.
    """
    import services.ai_service as ai

    searched = []

    async def _trap_brave(*a, **k):
        searched.append("brave")
        raise AssertionError("web search called from the general lane")

    async def _trap_with_search(*a, **k):
        searched.append("with_search")
        raise AssertionError("search-augmented stream called from the general lane")
        yield {}

    async def _plain_stream(messages, max_tokens, model=None):
        yield {"type": "chunk", "content": "an answer"}

    w = _Writer()
    with patch.object(ai, "_call_race_brave_search", _trap_brave), \
            patch.object(ai, "_call_race_stream_with_search", _trap_with_search), \
            patch.object(ai, "_call_race_stream", _plain_stream), \
            patch.object(ai, "ACTIVE_LLM_PROVIDER", "race"):
        out = await hg.general_chat_node(_state(), w)

    assert searched == [], f"the general lane reached a search path: {searched}"
    assert out["response_text"] == "an answer"
    # The UI's "Searching the web…" indicator must never fire here either.
    assert w.of_type("searching") == []


# ── web search switched on (GENERAL_CHAT_WEB_SEARCH_ENABLED) ────────────────

async def test_switched_on_it_asks_for_web_search(monkeypatch):
    monkeypatch.setenv("GENERAL_CHAT_WEB_SEARCH_ENABLED", "true")
    seen = {}

    def _capture(*args, **kwargs):
        seen.update(kwargs)
        return _stream("ok")(*args, **kwargs)

    with patch.object(hg, "_call_llm_stream", _capture):
        await hg.general_chat_node(_state(), _Writer())

    assert seen.get("use_tools") is True


async def test_switched_on_the_race_search_runs_and_its_results_reach_the_model(monkeypatch):
    """Through the REAL dispatcher on the race provider: when the model asks
    for a search, the search runs with the model's query, its results are
    handed to the model, and the UI gets its "Searching the web…" event."""
    import services.ai_service as ai
    monkeypatch.setenv("GENERAL_CHAT_WEB_SEARCH_ENABLED", "true")

    searched, sent = [], []

    async def _brave(query, k=5):
        searched.append(query)
        return [{"title": "Match report", "url": "https://example.com/r", "content": "India won by 6 wickets."}]

    async def _plain_stream(messages, max_tokens, model=None):
        sent.append(messages)
        if len(sent) == 1:
            yield {"type": "chunk", "content": "<search>India match result yesterday</search>"}
        else:
            yield {"type": "chunk", "content": "India won."}

    w = _Writer()
    with patch.object(ai, "_call_race_brave_search", _brave),             patch.object(ai, "_call_race_stream", _plain_stream),             patch.object(ai, "ACTIVE_LLM_PROVIDER", "race"):
        out = await hg.general_chat_node(_state("who won yesterday's match"), w)

    assert searched == ["India match result yesterday"]
    assert any("India won by 6 wickets." in m["content"] for m in sent[-1])
    assert len(w.of_type("searching")) == 1
    assert out["response_text"] == "India won."


async def test_switched_on_the_prompt_no_longer_says_it_cannot_search(monkeypatch):
    """Left on the no-search prompt, the model refuses to look things up
    while the search results sit right in front of it."""
    monkeypatch.setenv("GENERAL_CHAT_WEB_SEARCH_ENABLED", "true")
    seen = {}

    def _capture(messages, **kwargs):
        seen["messages"] = messages
        return _stream("ok")(messages, **kwargs)

    with patch.object(hg, "_call_llm_stream", _capture):
        await hg.general_chat_node(_state(), _Writer())

    system = seen["messages"][0]["content"]
    assert system.startswith(hg.GENERAL_CHAT_WEB_SEARCH_PROMPT)
    assert "no live information" not in system.lower()
    assert "you can search the web" in system.lower()


def test_the_search_prompt_keeps_every_other_rule():
    """Only the live-information section is swapped; the HR-data refusal,
    the LaTeX rule and the rest must survive in the search variant."""
    p = hg.GENERAL_CHAT_WEB_SEARCH_PROMPT.lower()
    assert "no access to helixta's hr data" in p
    assert "never invent a fact about this company" in p
    assert "does not render latex" in p
    # Search results must not be mistaken for facts about this company.
    assert "they are never information" in p
    assert "still have no access" in p


# ── the model failing ───────────────────────────────────────────────────────

async def test_an_empty_answer_says_so_rather_than_sending_nothing():
    w = _Writer()

    async def _empty(*a, **k):
        if False:
            yield {}

    with patch.object(hg, "_call_llm_stream", _empty):
        out = await hg.general_chat_node(_state(), w)

    assert out["response_text"] == hg.GENERAL_CHAT_UNAVAILABLE
    assert w.of_type("done")


async def test_a_raising_model_does_not_crash_the_turn():
    w = _Writer()

    async def _boom(*a, **k):
        raise RuntimeError("llm down")
        yield {}

    with patch.object(hg, "_call_llm_stream", _boom):
        out = await hg.general_chat_node(_state(), w)

    assert out["response_text"] == hg.GENERAL_CHAT_UNAVAILABLE


# ── FR-04: no backdoor into HRMS ────────────────────────────────────────────

async def test_the_node_sends_the_model_only_the_question_and_its_own_prompt():
    """Nothing about the company, the employee or their records reaches the
    general model — it gets its system prompt and the question, and that is
    all."""
    captured = {}

    def _capture(messages, *a, **k):
        captured["messages"] = messages
        return _stream("ok")(messages, *a, **k)

    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _capture):
        await hg.general_chat_node(_state("what is a balance sheet"), w)

    msgs = captured["messages"]
    assert [m["role"] for m in msgs] == ["system", "user"]
    assert msgs[0]["content"].startswith(hg.GENERAL_CHAT_SYSTEM_PROMPT)
    assert "Today's date is" in msgs[0]["content"]
    assert msgs[1]["content"] == "what is a balance sheet"


def test_the_prompt_states_it_has_no_live_information():
    """Required by the FR-05 decision: with web search off, the model answers
    current-events questions from training data, confidently and stale.
    Without this line, switching search off trades "I searched" for "here is
    a confident wrong answer about last week"."""
    p = hg.GENERAL_CHAT_SYSTEM_PROMPT.lower()
    assert "no live information" in p
    assert "cannot look it up" in p or "cannot check" in p


def test_the_prompt_refuses_to_answer_hr_data_questions():
    """FR-04: the general lane must not become a way to get at HR data by
    asking the general model instead."""
    p = hg.GENERAL_CHAT_SYSTEM_PROMPT.lower()
    assert "no access to helixta's hr data" in p
    assert "never invent a fact about this company" in p


# -- Review fixes -------------------------------------------------------------

async def test_a_follow_up_sees_the_conversation():
    """Live: "make it shorter" after a drafted email, and "now add type hints"
    after a code answer, came back as "please paste the code" - the node sent
    the model the question alone."""
    captured = {}

    def _capture(messages, *a, **k):
        captured["messages"] = messages
        return _stream("ok")(messages, *a, **k)

    state = {**_state("make it shorter"), "context": [
        {"role": "user", "content": "write a follow-up email to a customer"},
        {"role": "assistant", "content": "Subject: Following up ..."},
    ]}
    with patch.object(hg, "_call_llm_stream", _capture):
        await hg.general_chat_node(state, _Writer())

    assert [m["role"] for m in captured["messages"]] == ["system", "user", "assistant", "user"]
    assert captured["messages"][-1]["content"] == "make it shorter"


async def test_only_the_last_few_messages_are_sent():
    captured = {}

    def _capture(messages, *a, **k):
        captured["messages"] = messages
        return _stream("ok")(messages, *a, **k)

    context = [{"role": "user", "content": f"m{i}"} for i in range(20)]
    with patch.object(hg, "_call_llm_stream", _capture):
        await hg.general_chat_node({**_state(), "context": context}, _Writer())

    sent = [m["content"] for m in captured["messages"][1:-1]]
    assert sent == [f"m{i}" for i in range(14, 20)]


async def test_the_done_intent_is_general_chat():
    """So the next turn can tell a general answer from the HR redirect."""
    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _stream("ok")):
        await hg.general_chat_node(_state(), w)
    done = w.of_type("done")[0]
    assert done["intent"] == hg.GENERAL_CHAT_INTENT
    assert "failure_stage" not in done


async def test_over_the_limit_answers_without_calling_the_model():
    called = []

    def _trap(*a, **k):
        called.append(1)
        return _stream("x")(*a, **k)

    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _trap):
        await hg.general_chat_node({**_state(), "general_chat_over_limit": True}, w)
    done = w.of_type("done")[0]
    assert not called
    assert done["data"]["answer"] == hg.GENERAL_CHAT_LIMIT_REACHED
    assert done["failure_stage"] == hg.LIMITED_STAGE


async def test_the_answer_is_streamed_as_it_arrives():
    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _stream("first half. second half.")):
        out = await hg.general_chat_node(_state(), w)
    chunks = [c["content"] for c in w.of_type("chunk")]
    assert len(chunks) == 2
    assert "".join(chunks) == "first half. second half."
    assert out["response_text"] == "first half. second half."


async def test_a_failed_model_reports_its_failure_stage():
    async def _empty(*a, **k):
        if False:
            yield {}

    w = _Writer()
    with patch.object(hg, "_call_llm_stream", _empty):
        await hg.general_chat_node(_state(), w)
    done = w.of_type("done")[0]
    assert done["data"]["answer"] == hg.GENERAL_CHAT_UNAVAILABLE
    assert done["failure_stage"] == hg.FAILURE_STAGE_LLM


async def test_the_model_is_the_active_provider_dispatcher():
    """No separate model or service: the node calls _call_llm_stream, which
    dispatches on ACTIVE_LLM_PROVIDER."""
    import services.ai_service as ai
    assert hg._call_llm_stream is ai._call_llm_stream
