"""
arifosmcp/runtime/megaTools/06_asi_heart.py

444_CRITIQUE: Safety, empathy, and consequence modeling
Stage: 444_CRITIQUE | Trinity: OMEGA Ω | Floors: F5, F6, F9

Modes: critique, simulate
"""

from __future__ import annotations

from typing import Any

from arifosmcp.runtime.model import RuntimeEnvelope, RuntimeStatus, Verdict
from arifosmcp.runtime.tools_internal import asi_heart_dispatch_impl


async def asi_heart(
    mode: str | None = None,
    payload: dict[str, Any] | None = None,
    query: str | None = None,
    content: str | None = None,
    session_id: str | None = None,
    actor_id: str | None = None,
    declared_name: str | None = None,
    intent: Any | None = None,
    human_approval: bool = False,
    risk_tier: str = "medium",
    dry_run: bool = True,
    allow_execution: bool = False,
    caller_context: dict | None = None,
    auth_context: dict | None = None,
    debug: bool = False,
    request_id: str | None = None,
    timestamp: str | None = None,
    raw_input: str | None = None,
    ctx: Any | None = None,
) -> RuntimeEnvelope:
    from arifosmcp.runtime.dispatcher import HARDENED_DISPATCH_MAP

    payload = dict(payload or {})
    if content:
        payload.setdefault("content", content)
    if raw_input:
        payload.setdefault("query", raw_input)
    if caller_context:
        payload.setdefault("caller_context", caller_context)
    if auth_context:
        payload.setdefault("auth_context", auth_context)
    if query:
        payload.setdefault("query", query)
        payload.setdefault("content", query)  # asi_heart_dispatch_impl reads payload["content"]
    if session_id:
        payload.setdefault("session_id", session_id)
    if actor_id:
        payload.setdefault("actor_id", actor_id)
    if intent:
        payload.setdefault("intent", intent)
    if human_approval:
        payload.setdefault("human_approval", human_approval)

    if "asi_heart" in HARDENED_DISPATCH_MAP:
        if mode is None:
            mode = "critique"
        res = await HARDENED_DISPATCH_MAP["asi_heart"](mode=mode, payload=payload)
        if isinstance(res, dict):
            ok = res.get("ok", res.get("status") not in ("HOLD", "ERROR", "VOID", None))
            _next_tools = res.get("next_allowed_tools", [])
            _payload = res.get("payload", res) if isinstance(res.get("payload"), dict) else res
            _hold_reason = res.get("warnings", [""])[0] if res.get("warnings") else ""
            _next_action = None
            if not ok and _hold_reason:
                _next_action = {
                    "reason": _hold_reason,
                    "missing_requirements": (
                        _payload.get("missing_requirements", [])
                        if isinstance(_payload, dict)
                        else []
                    ),
                    "next_allowed_tools": _next_tools,
                    "suggested_canonical_call": (
                        _payload.get("suggested_canonical_call")
                        if isinstance(_payload, dict)
                        else None
                    ),
                }
            return RuntimeEnvelope(
                tool="arifos_heart",
                canonical_tool_name="arifos_heart",
                stage=res.get("stage", "444_CRITIQUE"),
                status=RuntimeStatus.SUCCESS if ok else RuntimeStatus.ERROR,
                verdict=Verdict.SEAL if ok else Verdict.VOID,
                allowed_next_tools=_next_tools,
                next_action=_next_action,
                payload=res,
            )
        return res

    resolved_payload = dict(payload or {})
    return await asi_heart_dispatch_impl(
        mode=mode,
        payload=resolved_payload,
        auth_context=resolved_payload.get("auth_context", auth_context),
        risk_tier=resolved_payload.get("risk_tier", risk_tier),
        dry_run=bool(resolved_payload.get("dry_run", dry_run)),
        ctx=ctx,  # Context injected by FastMCP framework,
    )
