"""Writing a policy vs looking one up.

Reported: "create me a policy" came back with

    Based on the information available in your company policy/playbook, I do
    not have this information. Would you like to check with HR?

A refusal, to a request to WRITE something. A JD has always worked, because
job_description was never wired to the RAG documents; `policy` was, and the
route is unconditional - so an authoring request searched the uploaded
documents, matched nothing (the user was not asking what any document said)
and hit hr_response_node's "not in our documents" gate, which returns before
the model is ever called.

Both halves are pinned here, and the second is the one that must not move:

  * asking Helix to WRITE a policy is generation, with no document lookup,
    and starts by asking what the policy should be about and cover;
  * asking what the company's policy SAYS is unchanged - the documents, and
    an honest "not in there" when they do not cover it. Not one word of that
    path is loosened by this feature.
"""

import pytest

import services.classify_node as classify_node
import services.policy_draft as policy_draft


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

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

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


AUTHORING = [
    "create a policy",
    "make me a policy",
    "make a policy",
    "draft a leave policy",
    "write a work from home policy",
    "generate a policy for remote work",
    "prepare a code of conduct",
    "put together a policy on expenses",
    "come up with a maternity leave policy",
    "build me an sop for onboarding",
    "formulate a policy on social media use",
]

LOOKUPS = [
    "what is our maternity leave policy",
    "what is the company policy",
    "what does the policy say about notice periods",
    "how many sick days do we get",
    "is there a policy on remote work",
    "what is our wfh policy",
    "as per company policy can i take leave",
    "where can i find the leave policy",
    "do we have a dress code policy",
    "what should our leave policy be",
]


# =============================================================================
# Telling the two apart
# =============================================================================

class TestTheDetector:

    @pytest.mark.parametrize("query", AUTHORING)
    def test_an_authoring_request_is_recognised_without_an_llm(self, query):
        """The unmistakable shapes route on the pattern alone. A drafting
        request that only works when a provider answers is not a fix."""
        assert classify_node._score_policy_draft_query(query) >= 0.9, query

    @pytest.mark.parametrize("query", LOOKUPS)
    def test_a_lookup_scores_nothing_and_pays_for_nothing(self, query):
        """0.0 means two things at once: it will not be drafted, and it will
        not spend an adjudication call to find that out. Policy questions are
        the common case - they must stay exactly as cheap as before."""
        assert classify_node._score_policy_draft_query(query) == 0.0, query

    @pytest.mark.parametrize("query", [
        "i want a policy for interns",
        "give me a leave policy",
        "can you share the wfh policy",
    ])
    def test_a_genuinely_ambiguous_ask_goes_to_the_adjudicator(self, query):
        """"give me a leave policy" can mean write one or show me ours. These
        must neither route nor be dismissed on the pattern alone."""
        score = classify_node._score_policy_draft_query(query)
        assert 0.0 < score < 0.9, query

    async def test_the_ambiguous_band_falls_to_the_documents_when_the_call_fails(self, monkeypatch):
        """The safe side of the tie: a lookup wrongly drafted invents a
        policy, while a draft wrongly looked up merely answers "not in your
        documents" and the user can rephrase."""
        async def _down(query):
            return None, 0.0, None
        monkeypatch.setattr(classify_node.ai_service,
                            "classify_policy_authoring_intent", _down)

        routed, _, _ = await classify_node._resolve_policy_draft_route(
            "give me a leave policy", "give me a leave policy")

        assert routed is False

    async def test_the_adjudicator_can_promote_an_ambiguous_ask(self, monkeypatch):
        async def _yes(query):
            return True, 0.9, {"total_tokens": 20}
        monkeypatch.setattr(classify_node.ai_service,
                            "classify_policy_authoring_intent", _yes)

        routed, confidence, usage = await classify_node._resolve_policy_draft_route(
            "i want a policy for interns", "i want a policy for interns")

        assert routed is True
        assert confidence >= 0.75
        assert usage

    async def test_the_adjudicator_can_veto_an_ambiguous_ask(self, monkeypatch):
        async def _no(query):
            return False, 0.9, None
        monkeypatch.setattr(classify_node.ai_service,
                            "classify_policy_authoring_intent", _no)

        routed, _, _ = await classify_node._resolve_policy_draft_route(
            "give me a leave policy", "give me a leave policy")

        assert routed is False

    @pytest.mark.parametrize("query", LOOKUPS)
    async def test_a_lookup_never_reaches_the_adjudicator(self, monkeypatch, query):
        async def _boom(q):
            raise AssertionError(f"paid for an adjudication call on a lookup: {q!r}")
        monkeypatch.setattr(classify_node.ai_service,
                            "classify_policy_authoring_intent", _boom)

        routed, _, _ = await classify_node._resolve_policy_draft_route(query, query.lower())

        assert routed is False


class TestTheRoute:

    def test_policy_draft_routes_to_its_own_node(self):
        import services.hr_graph as hr_graph
        assert hr_graph._route_after_classify({"intent": "policy_draft"}) == "policy_draft_node"

    def test_a_policy_question_still_routes_to_the_documents(self):
        import services.hr_graph as hr_graph
        assert hr_graph._route_after_classify({"intent": "policy"}) == "policy_rag_node"

    def test_neither_turn_may_be_served_from_the_response_cache(self):
        """The first turn writes the pending brief before asking; a replayed
        cache hit would show the question with nothing recorded for the
        answer to resolve against. The second is a document written for one
        specific brief."""
        import main
        assert "policy_draft" in main._STATEFUL_QUERY_INTENTS
        assert "policy_draft_clarify" in main._STATEFUL_QUERY_INTENTS


# =============================================================================
# The node: ask first, then write
# =============================================================================

class TestTheDraftingFlow:

    @pytest.fixture(autouse=True)
    def _state_store(self, monkeypatch):
        store = {}
        monkeypatch.setattr(policy_draft.policy_draft_state, "get_state",
                            lambda c, v: store.get((c, v)))
        monkeypatch.setattr(policy_draft.policy_draft_state, "set_state",
                            lambda c, v, s: store.__setitem__((c, v), s) or True)
        monkeypatch.setattr(policy_draft.policy_draft_state, "clear_state",
                            lambda c, v: store.pop((c, v), None) or True)
        return store

    @pytest.fixture(autouse=True)
    def _llm(self, monkeypatch):
        calls = []

        async def _fake(prompt, **kwargs):
            calls.append(prompt)
            return {"choices": [{"message": {"content": "# Draft Policy\n\n## Purpose\nText."}}],
                    "usage": {"total_tokens": 900}}
        monkeypatch.setattr(policy_draft, "_call_llm", _fake)
        return calls

    def _state(self, query):
        return {"query": query, "company_id": 1, "conversation_id": "conv-1",
                "usage_events": []}

    async def _turn(self, query):
        writer = FakeWriter()
        result = await policy_draft.policy_draft_node(self._state(query), writer)
        return result["response_text"], writer

    async def test_a_bare_request_asks_what_the_policy_should_be(self, _llm):
        text, writer = await self._turn("make me a policy")

        assert "what kind of policy" in text.lower()
        assert "cover" in text.lower()
        assert _llm == [], "nothing may be drafted before the brief is given"
        assert writer.of_type("done")[0]["intent"] == "policy_draft_clarify"

    async def test_the_question_is_remembered_for_the_next_turn(self, _state_store):
        await self._turn("make me a policy")

        assert _state_store[(1, "conv-1")]["step"] == "awaiting_brief"

    async def test_a_named_subject_is_only_asked_what_to_cover(self, _llm):
        text, _ = await self._turn("create a work from home policy")

        assert "what should it cover" in text.lower()
        assert "work from home" in text.lower()
        assert _llm == []

    async def test_the_reply_produces_the_document(self, _llm, _state_store):
        await self._turn("make me a policy")
        text, writer = await self._turn(
            "remote work, applies to all employees, two days a week from home")

        assert "# Draft Policy" in text
        assert len(_llm) == 1
        assert writer.of_type("done")[0]["intent"] == "policy_draft"
        assert _state_store == {}, "the pending brief must not survive the draft"

    async def test_the_brief_reaches_the_drafting_prompt(self, _llm):
        await self._turn("create a wfh policy")
        await self._turn("two days a week, laptops provided by the company")

        prompt = _llm[0]
        assert "two days a week" in prompt
        assert "laptops provided" in prompt

    async def test_you_decide_drafts_rather_than_asking_again(self, _llm):
        await self._turn("create a leave policy")
        text, _ = await self._turn("you decide")

        assert len(_llm) == 1
        assert "# Draft Policy" in text

    async def test_you_decide_with_no_subject_asks_for_the_topic_once_more(self, _llm, _state_store):
        """"You decide" can settle the structure but not what the policy is
        ABOUT - inventing a topic would be answering a question nobody asked."""
        await self._turn("make me a policy")
        text, _ = await self._turn("you decide")

        assert _llm == []
        assert "what should the policy be about" in text.lower()
        assert _state_store[(1, "conv-1")]["step"] == "awaiting_brief"

    async def test_a_full_brief_up_front_skips_the_question(self, _llm, _state_store):
        text, _ = await self._turn(
            "draft a wfh policy covering eligibility, equipment and working hours")

        assert len(_llm) == 1
        assert "# Draft Policy" in text
        assert _state_store == {}

    async def test_a_failed_drafting_call_says_so(self, monkeypatch):
        async def _boom(prompt, **kwargs):
            raise RuntimeError("provider down")
        monkeypatch.setattr(policy_draft, "_call_llm", _boom)

        text, writer = await self._turn(
            "draft a wfh policy covering eligibility and equipment")

        assert "couldn't draft that" in text
        assert writer.of_type("done")[0]["intent"] == "policy_draft_failed"


class TestTheDraftIsNotPresentedAsCompanyPolicy:
    """The same conversation answers "what is our policy" from real uploaded
    documents. A generated draft must not read like one of those."""

    @pytest.fixture(autouse=True)
    def _state_store(self, monkeypatch):
        store = {}
        monkeypatch.setattr(policy_draft.policy_draft_state, "get_state",
                            lambda c, v: store.get((c, v)))
        monkeypatch.setattr(policy_draft.policy_draft_state, "set_state",
                            lambda c, v, s: store.__setitem__((c, v), s) or True)
        monkeypatch.setattr(policy_draft.policy_draft_state, "clear_state",
                            lambda c, v: store.pop((c, v), None) or True)

    async def test_the_reply_says_it_is_a_draft(self, monkeypatch):
        async def _fake(prompt, **kwargs):
            return {"choices": [{"message": {"content": "# Policy"}}], "usage": {}}
        monkeypatch.setattr(policy_draft, "_call_llm", _fake)

        writer = FakeWriter()
        result = await policy_draft.policy_draft_node(
            {"query": "draft a wfh policy covering eligibility and equipment",
             "company_id": 1, "conversation_id": "conv-1", "usage_events": []}, writer)

        text = result["response_text"]
        assert "draft" in text.lower()
        assert "not your company's current policy" in text.lower()
        assert writer.of_type("done")[0]["data"]["policy_draft"]["is_draft"] is True

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

        async def _fake(prompt, **kwargs):
            prompts.append(prompt)
            return {"choices": [{"message": {"content": "# Policy"}}], "usage": {}}
        monkeypatch.setattr(policy_draft, "_call_llm", _fake)

        await policy_draft.policy_draft_node(
            {"query": "draft a wfh policy covering eligibility and equipment",
             "company_id": 1, "conversation_id": "conv-1", "usage_events": []}, FakeWriter())

        prompt = prompts[0]
        assert "NOT a statement of any existing company policy" in prompt
        assert "Do not invent facts about the user's company" in prompt
        assert "placeholders" in prompt.lower()

    async def test_nothing_is_retrieved_from_the_policy_documents(self, monkeypatch):
        """The documents are what the company's policy IS. A draft is not a
        claim about that, so the lookup is not merely unnecessary here - it
        is what produced the refusal this feature exists to remove."""
        async def _fake(prompt, **kwargs):
            return {"choices": [{"message": {"content": "# Policy"}}], "usage": {}}
        monkeypatch.setattr(policy_draft, "_call_llm", _fake)

        import services.race_rag_service as race_rag_service

        async def _boom(*args, **kwargs):
            raise AssertionError("the policy documents must not be searched to WRITE a policy")
        monkeypatch.setattr(race_rag_service, "query_all_documents", _boom)

        await policy_draft.policy_draft_node(
            {"query": "draft a wfh policy covering eligibility and equipment",
             "company_id": 1, "conversation_id": "conv-1", "usage_events": []}, FakeWriter())


class TestSubjectExtraction:

    @pytest.mark.parametrize("query,expected", [
        ("create a wfh policy", "wfh"),
        ("draft a policy on remote work", "remote work"),
        ("write a leave policy", "leave"),
        ("generate a policy for expense reimbursement", "expense reimbursement"),
        ("prepare a code of conduct", "code of conduct"),
    ])
    def test_the_subject_is_read_off_the_request(self, query, expected):
        assert policy_draft.extract_policy_subject(query) == expected

    @pytest.mark.parametrize("query", ["make me a policy", "create a policy", "draft a policy"])
    def test_a_bare_request_names_no_subject(self, query):
        """Which is the whole reason the clarifying turn exists - there is
        nothing here to write about."""
        assert policy_draft.extract_policy_subject(query) is None
