""""show my policy" / "show my company policy" — the company's policies IN
GENERAL, with no topic named — and the retrieval behind every policy answer.

Reported live:
  * both queries answered "Based on the information available in your company
    policy/playbook, I do not have this information." Retrieval had returned
    excerpts from every document; the summarizer answers NO_RELEVANT_POLICY_FOUND
    unless an excerpt ANSWERS the question, and a request to see the policies
    asks nothing any one excerpt answers.
  * then the overview was one line per policy, not what the policies say.
  * "show my leave policy" took ~21s: 3 excerpts from EVERY one of 18 documents
    (~89k characters, ~18.6k prompt tokens, duplicates and placeholder files
    included) went to the summarizer for a question about one policy.

Now: an overview request searches every document for its rule-bearing text,
drops placeholder passages, and has what each policy says written out STREAMED
(in one piece it took ~31s with nothing on screen). A question that names a
policy searches only that policy's document, and duplicate passages are dropped.
The relevance judge and the no-information fallback are unchanged — they are
what keeps a placeholder "policy" from being answered as if it were real.
"""
import pytest

import services.hr_graph as hg
import services.race_rag_service as rag


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

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

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

    @property
    def done(self):
        return self.of_type("done")[-1]


CHUNKS = [
    {"content": "Employees may work from home up to four days a month.", "_source": "Remote Work Policy"},
    {"content": "Wednesday is the weekly leave day.", "_source": "Leave Policy"},
    {"content": "Lorem ipsum dolor sit amet, consectetur.", "_source": "Discipline Policy"},
    {"content": "Up to four WFH days, approved by the manager.", "_source": "Remote Work Policy"},
]


@pytest.fixture
def rag_calls(monkeypatch):
    calls = []

    async def fake_query(query, k_per_doc=3):
        calls.append((query, k_per_doc))
        return [dict(c) for c in CHUNKS]

    monkeypatch.setattr(hg.race_rag_service, "query_all_documents", fake_query)
    return calls


def _stream(chunks=None, fail=False, seen=None):
    async def fake(prompt, max_tokens=None, use_tools=True):
        if seen is not None:
            seen.append({"prompt": prompt, "use_tools": use_tools})
        if fail:
            raise RuntimeError("provider down")
        for piece in chunks or []:
            yield {"type": "chunk", "content": piece}
        yield {"type": "usage", "usage": {"total_tokens": 42}}
    return fake


# -- which questions are overview requests ---------------------------------------

class TestOverviewDetection:
    @pytest.mark.parametrize("query", [
        "show my policy", "show my company policy",           # the reported queries
        "what policies do we have", "list all HR policies",
        "show our company’s policies",                        # curly apostrophe
        "show me the policy documents", "can I see the company handbook",
    ])
    def test_no_topic_named_is_an_overview(self, query):
        assert hg._is_policy_overview_query(query) is True

    @pytest.mark.parametrize("query", [
        "show my leave policy", "what is the notice period policy", "wfh policy",
        "policy for late coming", "what is my regularization policy", "show my leave balance",
    ])
    def test_a_named_topic_is_not(self, query):
        assert hg._is_policy_overview_query(query) is False


class TestRouting:
    """The deterministic policy override (classify_node -> is_policy_question)
    routes these to the policy documents whatever label the LLM picks. Live,
    routing was left to the LLM: "list all HR policies" went to compliance."""

    @pytest.mark.parametrize("query", [
        "show my policy", "show my company policy", "list all HR policies", "what policies do we have",
    ])
    def test_an_overview_request_is_a_policy_question(self, query):
        from services.nlp_service import is_policy_question
        assert is_policy_question(query) is True

    @pytest.mark.parametrize("query", ["show my leave balance", "am I eligible for sick leave"])
    def test_record_and_eligibility_questions_are_not(self, query):
        from services.nlp_service import is_policy_question
        assert is_policy_question(query) is False


# -- policy_rag_node ----------------------------------------------------------------

class TestOverviewRetrieval:
    async def test_searches_for_rules_takes_more_per_document_and_drops_placeholders(
        self, monkeypatch, rag_calls,
    ):
        async def must_not_summarize(*args, **kwargs):
            raise AssertionError("an overview is written by hr_response_node, streamed")

        monkeypatch.setattr(hg, "_call_llm", must_not_summarize)
        out = await hg.policy_rag_node({"query": "show my policy", "usage_events": []}, Writer())

        assert rag_calls == [(hg._POLICY_OVERVIEW_SEARCH, hg._POLICY_OVERVIEW_CHUNKS_PER_DOC)]
        assert out["policy_overview"] is True
        assert out["policy_lookup_failed"] is False
        context = out["policy_context"]
        assert "### From: Remote Work Policy" in context
        assert "### From: Leave Policy" in context
        assert "Lorem ipsum" not in context and "Discipline Policy" not in context

    async def test_a_specific_question_keeps_the_relevance_judged_path(self, monkeypatch, rag_calls):
        prompts = []

        async def judge(prompt, **kwargs):
            prompts.append(prompt)
            return {"__text__": "NO_RELEVANT_POLICY_FOUND"}

        monkeypatch.setattr(hg, "_call_llm", judge)
        monkeypatch.setattr(hg, "_extract_text", lambda raw: raw["__text__"])
        out = await hg.policy_rag_node({"query": "what is the maternity policy", "usage_events": []},
                                       Writer())

        assert rag_calls == [("what is the maternity policy", 3)]
        assert "NO_RELEVANT_POLICY_FOUND" in prompts[0]
        assert out["policy_lookup_failed"] is True
        assert out.get("policy_overview") is None


# -- hr_response_node ---------------------------------------------------------------

CONTEXT = rag.format_retrieved_chunks([c for c in CHUNKS if "Lorem" not in c["content"]])


class TestOverviewAnswer:
    async def test_the_overview_is_streamed_from_its_own_prompt(self, monkeypatch):
        seen = []
        monkeypatch.setattr(hg, "_call_llm_stream",
                            _stream(["## Remote Work Policy\n", "- Up to four WFH days a month."], seen=seen))
        writer = Writer()
        out = await hg.hr_response_node({
            "query": "show my policy", "intent": "policy", "context": [], "usage_events": [],
            "policy_context": CONTEXT, "policy_lookup_failed": False, "policy_overview": True,
        }, writer)

        assert [e["content"] for e in writer.of_type("chunk")] == [
            "## Remote Work Policy\n", "- Up to four WFH days a month."]
        assert out["response_text"] == "## Remote Work Policy\n- Up to four WFH days a month."
        assert writer.done["data"]["answer"] == out["response_text"]
        assert writer.done["intent"] == "policy"
        (call,) = seen
        assert call["use_tools"] is False
        assert "Policies: Remote Work Policy, Leave Policy" in call["prompt"]
        # The Leave Policy upload is marked as a draft; it was left out until the
        # prompt said a draft is still a policy.
        assert "draft" in call["prompt"].lower()
        assert "Which specific policy" not in out["response_text"]

    async def test_a_failed_stream_still_lists_the_policy_names(self, monkeypatch):
        monkeypatch.setattr(hg, "_call_llm_stream", _stream(fail=True))
        writer = Writer()
        out = await hg.hr_response_node({
            "query": "show my company policy", "intent": "policy", "context": [], "usage_events": [],
            "policy_context": CONTEXT, "policy_lookup_failed": False, "policy_overview": True,
        }, writer)

        assert "**Remote Work Policy**" in out["response_text"]
        assert "**Leave Policy**" in out["response_text"]
        assert writer.done["data"]["answer"] == out["response_text"]

    async def test_an_uncovered_question_still_gets_the_approved_fallback(self):
        out = await hg.hr_response_node({
            "query": "what is the maternity policy", "intent": "policy", "context": [],
            "usage_events": [], "policy_context": None, "policy_lookup_failed": True,
        }, Writer())
        assert out["response_text"] == hg.NO_INFO_FALLBACK


# -- race_rag_service: which documents are searched ----------------------------------

DOCS = [
    {"document_id": "d1", "source_name": "leave-policy_1790078260_94dXId.pdf"},
    {"document_id": "d2", "source_name": "leave-policy_1790078299_aa11bb.pdf"},   # duplicate upload
    {"document_id": "d3", "source_name": "payroll-and-benefits-policy_1790078261_x1.pdf"},
    {"document_id": "d4", "source_name": "it-and-security-policy_1790078262_x2.pdf"},
    {"document_id": "d5", "source_name": "remote-work-policy_1790078263_x3.pdf"},
]


class TestNamedPolicy:
    @pytest.mark.parametrize("query,expected", [
        ("show my leave policy", {"d1", "d2"}),
        ("what is the payroll policy", {"d3"}),
        ("what does the benefits policy say", {"d3"}),
        ("it security policy", {"d4"}),
        ("remote work policy", {"d5"}),
    ])
    def test_a_named_policy_selects_its_documents(self, query, expected):
        assert {d["document_id"] for d in rag.documents_named_in(query, DOCS)} == expected

    @pytest.mark.parametrize("query", [
        "what is the notice period",        # no "policy": may span several documents
        "how many wfh days can I take",
        "show my policy",                   # the overview: every document
        "what is the it policy",            # "it" is too short to identify a policy
    ])
    def test_otherwise_every_document_is_searched(self, query):
        assert rag.documents_named_in(query, DOCS) == []

    def test_duplicate_passages_are_dropped(self):
        chunks = [{"content": "Casual leave: 12 days."}, {"content": "casual  leave: 12 days."},
                  {"content": "Sick leave: 12 days."}]
        assert [c["content"] for c in rag._dedupe_chunks(chunks)] == [
            "Casual leave: 12 days.", "Sick leave: 12 days."]

    async def test_query_all_documents_searches_only_the_named_policy(self, monkeypatch):
        searched = []

        async def fake_list(limit=20, offset=0):
            return DOCS

        class Resp:
            def __init__(self, text):
                self._text = text

            def raise_for_status(self):
                pass

            def json(self):
                return {"results": [{"content": self._text}]}

        async def fake_post(url, json=None, headers=None):
            searched.append(json["document_id"])
            # Both leave uploads hold the same text — the duplicate is dropped.
            return Resp("Leave rules." if json["document_id"] in ("d1", "d2") else "Other rules.")

        monkeypatch.setattr(rag, "RACE_API_KEY", "key")
        monkeypatch.setattr(rag, "RACE_RAG_COLLECTION_ID", "col")
        monkeypatch.setattr(rag, "list_documents", fake_list)
        monkeypatch.setattr(rag._http, "post", fake_post)

        chunks = await rag.query_all_documents("show my leave policy")
        assert sorted(searched) == ["d1", "d2"]
        assert [c["content"] for c in chunks] == ["Leave rules."]
        assert chunks[0]["_source"] == "Leave Policy"
