"""
MCP Tool 888: JUDGE

Final verdict aggregation via System 2 Orchestrator (APEX Prime).

Constitutional role:
- Aggregates verdicts from all active kernels (AGI, ASI).
- Applies APEX Kernel constraints (F1, F8-F12).
- Emits final verdict: SEAL, PARTIAL, VOID, SABAR, HOLD.

Layer: APEX (Judge) - F1, F8, F9, F11, F12
Authority: arifos_core/system/apex_prime.py
"""

import asyncio
from datetime import datetime, timezone
from typing import Any, Dict

from arifos_core.mcp.models import FloorCheckResult, VerdictResponse
from arifos_core.system.apex_prime import APEXPrime, Verdict


async def mcp_888_judge(request: Dict[str, Any]) -> VerdictResponse:
    """
    MCP Tool 888: JUDGE - Final Verdict via APEX Prime.

    Delegates to System 2 Orchestrator.
    """
    # 1. Initialize System 2 Orchestrator
    judge = APEXPrime()

    # 2. Extract inputs
    # The request is expected to contain the accumulated state or explicit verdicts
    # Trace of previous tool outputs usually passed in metabolic loop
    query = request.get("query", "")
    response = request.get("response", "") # The draft being judged

    # Extract upstream kernel results if available
    # (In a real metabolic loop, these trace objects would be passed)
    agi_results = request.get("agi_results", [])
    asi_results = request.get("asi_results", [])

    # If using simplified "verdicts" dict (legacy/simple mode), we map it
    verdicts_dict = request.get("verdicts", {})
    if verdicts_dict and not (agi_results or asi_results):
        # Fallback mapping for simple integration
        # This is strictly for compatibility with non-metabolic callers
        pass # APEXPrime handles missing upstream data gracefully (defaults to checking own floors)

    # 3. Execute System 2 Judgment
    # judge_output runs the full Trinity check (G, C_dark, Psi) + Hypervisor
    verdict_obj = judge.judge_output(
        query=query,
        response=response,
        agi_results=agi_results, # Type: List[FloorCheckResult]
        asi_results=asi_results, # Type: List[FloorCheckResult]
        user_id=request.get("user_id")
    )

    # 4. Map ApexVerdict -> VerdictResponse
    side_data = verdict_obj.to_dict()
    # Flatten genius_stats into side_data
    side_data.update(verdict_obj.genius_stats)

    return VerdictResponse(
        verdict=verdict_obj.verdict.value,
        reason=verdict_obj.reason,
        side_data=side_data,
        timestamp=datetime.now(timezone.utc).isoformat()
    )

def mcp_888_judge_sync(request: Dict[str, Any]) -> VerdictResponse:
    """Synchronous wrapper for mcp_888_judge."""
    return asyncio.run(mcp_888_judge(request))
