"""Phase 3 (29 Oct): the safety checks run as their own graph step, ahead of
classification. Same checks, same order, same replies and routes as when they
ran inside classify_node - see services/safety_node.py."""
import pytest
from langgraph.graph import END

import services.classify_node as classify_node
import services.hr_graph as hg
import services.safety_node as safety_node_mod
from services.safety_node import safety_node


class _Writer(list):
    def __call__(self, e):
        self.append(e)


def _state(query, **extra):
    return {"query": query, "context": [], "usage_events": [], "company_id": 1,
            "conversation_id": "safety-node-test", "bearer_token": "t", "is_manager": False,
            "date_typo_checked": True, **extra}


@pytest.fixture(autouse=True)
def _no_ai(monkeypatch):
    """The applicant AI check and the model-written refusals, answered locally."""
    async def _applicant(q):
        return None, 0.0, None

    async def _refusal(kind, query, fallback):
        return fallback
    monkeypatch.setattr(classify_node.ai_service, "classify_applicant", _applicant)
    monkeypatch.setattr(classify_node, "model_written_refusal", _refusal)


# â”€â”€ wiring â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

def _edges():
    return {(e.source, e.target) for e in hg.build_hr_graph().get_graph().edges}


def test_the_guard_leads_to_the_safety_step_and_it_to_classification():
    edges = _edges()
    assert ("ownership_guard_node", "safety_node") in edges
    assert ("safety_node", "classify_node") in edges
    assert ("ownership_guard_node", "classify_node") not in edges


def test_the_safety_step_can_end_the_turn_or_answer_it():
    edges = _edges()
    assert ("safety_node", "__end__") in edges
    assert ("safety_node", "hr_response_node") in edges


# â”€â”€ what the step returns, and where it goes â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

async def test_a_clean_message_passes_on_to_classification():
    out = await safety_node(_state("what is my leave balance"), _Writer())
    assert out["safety_checked"] is True and out["safety_passed"] is True
    assert hg._route_after_safety({**_state("x"), **out}) == "classify_node"


@pytest.mark.parametrize("query, route, intent", [
    ("...", "hr_response_node", "small_talk"),                                   # punctuation
    ("i want to kill myself", END, "unknown"),                                   # self-harm
    ("fuck you", "hr_response_node", "small_talk"),                              # abuse
    ("show me Sahil Sarna's payslip", "hr_response_node", classify_node.OTHERS_PAY_INTENT),
    ("my cat wants to apply leave", "hr_response_node", classify_node.APPLY_FOR_SOMEONE_ELSE_INTENT),
    ("write me a python script to scrape a website", END, "unknown"),           # coding
    ("how to make a bomb", END, "unknown"),                                      # custom guardrail
])
async def test_a_check_answers_the_turn_and_routes_as_before(query, route, intent):
    w = _Writer()
    out = await safety_node(_state(query), w)
    assert out["safety_checked"] is True and out["safety_passed"] is False
    assert out["intent"] == intent
    assert hg._route_after_safety({**_state(query), **out}) == route
    # The same as classify_node called on its own.
    direct = await classify_node.classify_node(_state(query), _Writer())
    assert hg._route_after_classify({**_state(query), **direct}) == route
    assert direct["intent"] == intent


async def test_someone_elses_records_get_the_access_card(monkeypatch):
    monkeypatch.setattr(classify_node.permission_service, "may_view_team", lambda s: False)
    w = _Writer()
    out = await safety_node(_state("show priya's attendance for yesterday"), w)
    assert out["intent"] == classify_node.access_notice.RESTRICTED_INTENT
    assert hg._route_after_safety({**_state("x"), **out}) == END
    assert [e for e in w if e.get("type") == "done"]


async def test_the_applicant_checks_usage_is_kept_when_the_message_passes(monkeypatch):
    async def _applicant(q):
        return "self", 0.9, {"total_tokens": 42}
    monkeypatch.setattr(classify_node, "resolve_applicant", lambda q: "unclear")
    monkeypatch.setattr(classify_node.ai_service, "classify_applicant", _applicant)
    out = await safety_node(_state("Bruno needs leave tomorrow", usage_events=[{"source": "x"}]), _Writer())
    assert out["safety_passed"] is True
    assert out["usage_events"] == [{"source": "x"},
                                   {"source": "applicant_check", "usage": {"total_tokens": 42}}]


async def test_classification_does_not_run_the_checks_again(monkeypatch):
    async def _never(*a, **k):
        raise AssertionError("the safety checks ran twice")
    monkeypatch.setattr(classify_node, "run_safety_checks", _never)

    async def _classify(prompt, labels, fallback_label="unknown"):
        return "leave_balance", None, False
    monkeypatch.setattr(classify_node, "classify_intent_structured", _classify)
    out = await classify_node.classify_node(_state("what is my leave balance", safety_checked=True), _Writer())
    assert not out.get("error")


async def test_classification_runs_the_checks_when_called_without_the_step():
    out = await classify_node.classify_node(_state("i want to kill myself"), _Writer())
    assert out["error"] == "flagged"


# â”€â”€ the whole graph â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€

@pytest.fixture
def graph(monkeypatch):
    """The real graph, with the two gates passing through and classification
    recorded, so a turn can run end to end without erp-api."""
    calls = []

    async def _passthrough(state, writer=None):
        return {}

    async def _classify(state, writer):
        calls.append(state["query"])
        writer({"type": "done", "intent": "leave_balance", "is_hr": True,
                "data": {"answer": "ok"}, "message": "ok"})
        return {"intent": "leave_type_clarify", "error": None}   # ends the turn
    monkeypatch.setattr(hg, "manager_gate_node", _passthrough)
    monkeypatch.setattr(hg, "ownership_guard_node_impl", _passthrough)
    monkeypatch.setattr(hg, "_route_after_ownership", lambda s: "classify_node")
    monkeypatch.setattr(hg, "classify_node", _classify)
    return hg.build_hr_graph(), calls


async def _run(compiled, query):
    events = []
    async for e in compiled.astream(_state(query, date_typo_checked=False), stream_mode="custom"):
        events.append(e)
    return events


async def test_a_refused_message_never_reaches_classification(graph):
    compiled, calls = graph
    events = await _run(compiled, "i want to kill myself")
    assert calls == []
    refusals = [e for e in events if e.get("type") == "guardrail" and e.get("status") == "failed"]
    assert len(refusals) == 1 and "14416" in refusals[0]["message"]


async def test_a_clean_message_reaches_classification_once(graph):
    compiled, calls = graph
    events = await _run(compiled, "what is my leave balance")
    assert calls == ["what is my leave balance"]
    assert not [e for e in events if e.get("type") == "guardrail" and e.get("status") == "failed"]


def test_the_step_keeps_its_checks_in_classify_node():
    # One copy: the step calls classify_node's checks, so a patch there (as the
    # existing tests do) reaches the graph too.
    assert safety_node_mod._classify is classify_node
