"""Non-interactive (headless) mode — single message -> stream -> exit.

Creates an ICARUS agent and streams the response to stdout.
Exit codes: 0 success, 1 error, 130 interrupt.
"""

from __future__ import annotations

import logging
import sys
from uuid import uuid4

from icarus.session.events import TextDelta
from rich.console import Console

logger = logging.getLogger(__name__)


async def run_headless(
    message: str,
    *,
    model: str | None = None,
    auto_approve: bool = False,
    quiet: bool = False,
) -> int:
    """Run a single task non-interactively and exit.

    Args:
        message: The task/message to execute.
        model: Optional model spec override (e.g. 'azure_ai:Kimi-K2.5').
        auto_approve: Skip HITL approval for all tool calls.
        quiet: Suppress all non-response output.

    Returns:
        Exit code: 0 for success, 1 for error, 130 for keyboard interrupt.
    """
    from icarus.mcp import MCPManager
    from icarus.runtime.builder import create_icarus_agent
    from icarus.runtime.context import UserContext
    from icarus.session.stream import stream_turn

    console = Console(stderr=True) if quiet else Console()
    llm_model = None
    mcp_manager = None

    try:
        ctx = UserContext.default()
        thread_id = str(uuid4())

        if not quiet:
            console.print("[dim]Running task non-interactively...[/dim]")
            if model:
                console.print(f"[dim]Model: {model}[/dim]")
            console.print()

        # Load MCP tools if ~/.icarus/mcp.json exists
        mcp_manager = MCPManager.from_config_file(ctx.config_dir / "mcp.json")
        mcp_tools, _ = await mcp_manager.start() if mcp_manager else ([], [])

        if mcp_tools and not quiet:
            names = ", ".join(mcp_manager.server_names)
            console.print(f"[dim]MCP: {len(mcp_tools)} tools from {names}[/dim]")

        result = create_icarus_agent(
            ctx,
            model=model,
            tools=mcp_tools or None,
            auto_approve=auto_approve,
        )
        llm_model = result.model

        async for event in stream_turn(
            agent=result.graph,
            user_input=message,
            thread_id=thread_id,
            assistant_id="default",
            auto_approve=auto_approve,
        ):
            match event:
                case TextDelta(text=text):
                    sys.stdout.write(text)
                    sys.stdout.flush()
                case _:
                    pass  # Headless ignores non-text events

        sys.stdout.write("\n")
        sys.stdout.flush()

        if not quiet:
            console.print()
            console.print("[green]Task completed[/green]")

        return 0

    except KeyboardInterrupt:
        console.print("\n[yellow]Interrupted[/yellow]")
        return 130
    except Exception as e:
        logger.exception("Error during headless execution")
        console.print(f"\n[red]Error ({type(e).__name__}): {e}[/red]")
        return 1
    finally:
        if mcp_manager is not None:
            await mcp_manager.stop()
        if llm_model is not None and hasattr(llm_model, "aclose"):
            await llm_model.aclose()
