"""无 TUI 时执行单轮主对话：将工具事件打印到 stdout，最后打印助手回复并退出。"""

from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING

import typer

if TYPE_CHECKING:
    from aicd.runtime import RuntimeContext


async def run_noui_ai_turn(ctx: RuntimeContext, user_message: str) -> int:
    """
    执行一轮 ``agent.chat``；期间把总线 ``agent`` 工具事件打到 stdout；
    结束后打印最终助手文本，再优雅关闭运行时。
    """
    q = ctx.bus.subscribe()

    async def _tool_pump() -> None:
        try:
            while True:
                ev = await q.get()
                if ev.get("topic") != "agent":
                    continue
                if ev.get("event") == "phase":
                    typer.echo(f"[phase {ev.get('phase', '')}] {ev.get('detail', '')}")
                elif ev.get("event") == "tool":
                    name = ev.get("name", "")
                    prev = ev.get("preview", "")
                    typer.echo(f"[tool {name}] {prev}")
                elif ev.get("event") == "log":
                    line = str(ev.get("line", "")).strip()
                    if line:
                        typer.echo(line)
        except asyncio.CancelledError:
            raise
        finally:
            ctx.bus.unsubscribe(q)

    pump = asyncio.create_task(_tool_pump())
    try:
        reply = await ctx.agent.chat(user_message)
    except asyncio.CancelledError:
        pump.cancel()
        try:
            await pump
        except asyncio.CancelledError:
            pass
        raise
    except Exception as e:  # noqa: BLE001
        pump.cancel()
        try:
            await pump
        except asyncio.CancelledError:
            pass
        typer.echo(f"错误: {e}", err=True)
        try:
            await ctx.shutdown_graceful()
        except Exception:
            pass
        try:
            ctx.session_log.close()
        except Exception:
            pass
        return 1
    else:
        pump.cancel()
        try:
            await pump
        except asyncio.CancelledError:
            pass
        typer.echo(reply)
        try:
            await ctx.shutdown_graceful()
        except Exception:
            pass
        try:
            ctx.session_log.close()
        except Exception:
            pass
        return 0
