"""Conversation trace wiring for kernel runs (MCP ``mugi_read_trace``).

Mirrors the legacy ``agent_loop_run`` trace events without pulling
``tools/conversation_trace`` into ``core/``. The wiring layer injects
``RunTraceHooks`` on ``RunConfig`` and wraps each ``run_agent`` call with
``run_start`` / ``run_end``.
"""
from __future__ import annotations

from core.run import RunTraceHooks


def make_kernel_trace_hooks(thread_id: str, model_id: str) -> RunTraceHooks | None:
    """Return per-turn trace hooks when conversation trace is enabled."""
    from tools import conversation_trace

    if not conversation_trace.is_trace_enabled():
        return None

    def on_turn_start(round_: int, message_count: int) -> None:
        conversation_trace.emit_turn_start(thread_id, round_, message_count, model_id)

    def on_llm_request(round_: int, messages: list, create_kwargs: dict) -> None:
        conversation_trace.emit_llm_request(thread_id, round_, messages, create_kwargs)

    def on_llm_response(round_: int, content: str, tool_calls: list) -> None:
        conversation_trace.emit_llm_response(thread_id, round_, content, tool_calls)

    def on_tool_call(
        round_: int, name: str, args: str, result: str, duration_sec: float
    ) -> None:
        conversation_trace.emit_tool_call(
            thread_id, round_, name, args, result, duration_sec
        )

    def on_turn_end(round_: int, final_content: str | None, reason: str) -> None:
        conversation_trace.emit_turn_end(thread_id, round_, final_content, reason)

    return RunTraceHooks(
        on_turn_start=on_turn_start,
        on_llm_request=on_llm_request,
        on_llm_response=on_llm_response,
        on_tool_call=on_tool_call,
        on_turn_end=on_turn_end,
    )


def trace_kernel_run_start(
    thread_id: str, *, subagent_mode: bool = False, idle_tick: bool = False
) -> None:
    """Log kernel run boundary (``run_start``)."""
    from tools import conversation_trace

    if conversation_trace.is_trace_enabled():
        conversation_trace.emit_run_start(
            thread_id, subagent_mode, idle_tick=idle_tick
        )


def trace_kernel_run_end(thread_id: str) -> None:
    """Log kernel run boundary (``run_end``)."""
    from tools import conversation_trace

    if conversation_trace.is_trace_enabled():
        conversation_trace.emit_run_end(thread_id)
