"""The safety step of the graph: every message's checks, before classification.

Runs classify_node.run_safety_checks - punctuation only, self-harm, abusive
language, someone else's pay, someone else as the applicant, the custom
guardrail, coding, and someone else's records asked by a normal user - as its
own node, so what a message is allowed to ask is settled before anything decides
what it asks. A check that answers the turn routes exactly as it did from
classify_node (route_after_safety); a message that passes goes on to
classify_node, which then skips the checks (safety_checked).

The checks live in classify_node, not here, on purpose: thousands of tests
patch their helpers there (classify_node._check_moderation, model_written_refusal,
...), and one copy keeps the graph and a direct classify_node call identical.
The AI moderation judge is not here either: it runs in classify_node, in
parallel with the intent classifier, and on messages leaving an open flow.
"""
import logging

from langgraph.types import StreamWriter

from schema.agent import HRState
from services import classify_node as _classify

logger = logging.getLogger(__name__)


async def safety_node(state: HRState, writer: StreamWriter) -> dict:
    usage_events = list(state.get("usage_events", []))
    turn = await _classify.run_safety_checks(state, writer, usage_events)
    if turn is None:
        return {"safety_checked": True, "safety_passed": True, "usage_events": usage_events}
    logger.info("[Graph] safety_node answered the turn: intent=%s error=%s",
                turn.get("intent"), turn.get("error"))
    return {**turn, "safety_checked": True, "safety_passed": False}
