"""
CLI for zwarm orchestration.

Commands:
- zwarm orchestrate: Start an orchestrator session
- zwarm exec: Run a single executor directly (for testing)
- zwarm status: Show current state
- zwarm history: Show event history
- zwarm configs: Manage configurations
"""

from __future__ import annotations

import asyncio
import os
import sys
from enum import Enum
from pathlib import Path
from typing import Annotated, Optional

import typer
from rich import print as rprint
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

# Create console for rich output
console = Console()


def _resolve_task(task: str | None, task_file: Path | None) -> str | None:
    """
    Resolve task from multiple sources (priority order):
    1. --task flag
    2. --task-file flag
    3. stdin (if not a tty)
    """
    # Direct task takes priority
    if task:
        return task

    # Then file
    if task_file:
        if not task_file.exists():
            console.print(f"[red]Error:[/] Task file not found: {task_file}")
            raise typer.Exit(1)
        return task_file.read_text().strip()

    # Finally stdin (only if piped, not interactive)
    if not sys.stdin.isatty():
        stdin_content = sys.stdin.read().strip()
        if stdin_content:
            return stdin_content

    return None

# Main app with rich help
app = typer.Typer(
    name="zwarm",
    help="""
[bold cyan]zwarm[/] - Multi-Agent CLI Orchestration Research Platform

[bold]DESCRIPTION[/]
    Orchestrate multiple CLI coding agents (Codex, Claude Code) with
    delegation, conversation, and trajectory alignment (watchers).

[bold]QUICK START[/]
    [dim]# Initialize zwarm in your project[/]
    $ zwarm init

    [dim]# Run the orchestrator[/]
    $ zwarm orchestrate --task "Build a hello world function"

    [dim]# Check state after running[/]
    $ zwarm status

[bold]COMMANDS[/]
    [cyan]init[/]         Initialize zwarm (creates .zwarm/ with config)
    [cyan]reset[/]        Reset state and optionally config files
    [cyan]orchestrate[/]  Start orchestrator to delegate tasks to executors
    [cyan]exec[/]         Run a single executor directly (for testing)
    [cyan]status[/]       Show current state (sessions, tasks, events)
    [cyan]history[/]      Show event history log
    [cyan]configs[/]      Manage configuration files

[bold]CONFIGURATION[/]
    Config lives in [cyan].zwarm/config.toml[/] (created by init).
    Use [cyan]--config[/] flag for YAML files.
    See [cyan]zwarm configs list[/] for available configurations.

[bold]ADAPTERS[/]
    [cyan]codex_mcp[/]    Codex via MCP server (sync conversations)
    [cyan]claude_code[/]  Claude Code CLI

[bold]WATCHERS[/] (trajectory aligners)
    [cyan]progress[/]     Detects stuck/spinning agents
    [cyan]budget[/]       Monitors step/session limits
    [cyan]scope[/]        Detects scope creep
    [cyan]pattern[/]      Custom regex pattern matching
    [cyan]quality[/]      Code quality checks
    """,
    rich_markup_mode="rich",
    no_args_is_help=True,
    add_completion=False,
)

# Configs subcommand group
configs_app = typer.Typer(
    name="configs",
    help="""
Manage zwarm configurations.

[bold]SUBCOMMANDS[/]
    [cyan]list[/]   List available configuration files
    [cyan]show[/]   Display a configuration file's contents
    """,
    rich_markup_mode="rich",
    no_args_is_help=True,
)
app.add_typer(configs_app, name="configs")


class AdapterType(str, Enum):
    codex_mcp = "codex_mcp"
    claude_code = "claude_code"


class ModeType(str, Enum):
    sync = "sync"
    async_ = "async"


@app.command()
def orchestrate(
    task: Annotated[Optional[str], typer.Option("--task", "-t", help="The task to accomplish")] = None,
    task_file: Annotated[Optional[Path], typer.Option("--task-file", "-f", help="Read task from file")] = None,
    config: Annotated[Optional[Path], typer.Option("--config", "-c", help="Path to config YAML")] = None,
    overrides: Annotated[Optional[list[str]], typer.Option("--set", help="Override config (key=value)")] = None,
    working_dir: Annotated[Path, typer.Option("--working-dir", "-w", help="Working directory")] = Path("."),
    resume: Annotated[bool, typer.Option("--resume", help="Resume from previous state")] = False,
    max_steps: Annotated[Optional[int], typer.Option("--max-steps", help="Maximum orchestrator steps")] = None,
    verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Show detailed output")] = False,
    instance: Annotated[Optional[str], typer.Option("--instance", "-i", help="Instance ID (for isolation/resume)")] = None,
    instance_name: Annotated[Optional[str], typer.Option("--name", "-n", help="Human-readable instance name")] = None,
):
    """
    Start an orchestrator session.

    The orchestrator breaks down tasks and delegates to executor agents
    (Codex, Claude Code). It can have sync conversations or fire-and-forget
    async delegations.

    Each run creates an isolated instance to prevent conflicts when running
    multiple orchestrators in the same directory.

    [bold]Examples:[/]
        [dim]# Simple task[/]
        $ zwarm orchestrate --task "Add a logout button to the navbar"

        [dim]# Task from file[/]
        $ zwarm orchestrate -f task.md

        [dim]# Task from stdin[/]
        $ cat task.md | zwarm orchestrate
        $ zwarm orchestrate < task.md

        [dim]# With config file[/]
        $ zwarm orchestrate -c configs/base.yaml --task "Refactor auth"

        [dim]# Override settings[/]
        $ zwarm orchestrate --task "Fix bug" --set executor.adapter=claude_code

        [dim]# Named instance (easier to track)[/]
        $ zwarm orchestrate --task "Add tests" --name test-work

        [dim]# Resume a specific instance[/]
        $ zwarm orchestrate --resume --instance abc123

        [dim]# List all instances[/]
        $ zwarm instances
    """
    from zwarm.orchestrator import build_orchestrator

    # Resolve task from: --task, --task-file, or stdin
    resolved_task = _resolve_task(task, task_file)
    if not resolved_task:
        console.print("[red]Error:[/] No task provided. Use --task, --task-file, or pipe from stdin.")
        raise typer.Exit(1)

    task = resolved_task

    # Build overrides list
    override_list = list(overrides or [])
    if max_steps:
        override_list.append(f"orchestrator.max_steps={max_steps}")

    console.print(f"[bold]Starting orchestrator...[/]")
    console.print(f"  Task: {task}")
    console.print(f"  Working dir: {working_dir.absolute()}")
    if instance:
        console.print(f"  Instance: {instance}" + (f" ({instance_name})" if instance_name else ""))
    console.print()

    # Output handler to show orchestrator messages
    def output_handler(msg: str) -> None:
        if msg.strip():
            console.print(f"[dim][orchestrator][/] {msg}")

    orchestrator = None
    try:
        orchestrator = build_orchestrator(
            config_path=config,
            task=task,
            working_dir=working_dir.absolute(),
            overrides=override_list,
            resume=resume,
            output_handler=output_handler,
            instance_id=instance,
            instance_name=instance_name,
        )

        if resume:
            console.print("  [dim]Resuming from previous state...[/]")

        # Show instance ID if auto-generated
        if orchestrator.instance_id and not instance:
            console.print(f"  [dim]Instance: {orchestrator.instance_id[:8]}[/]")

        # Run the orchestrator loop
        console.print("[bold]--- Orchestrator running ---[/]\n")
        result = orchestrator.run(task=task)

        console.print(f"\n[bold green]--- Orchestrator finished ---[/]")
        console.print(f"  Steps: {result.get('steps', 'unknown')}")

        # Show exit message if any
        exit_msg = getattr(orchestrator, "_exit_message", "")
        if exit_msg:
            console.print(f"  Exit: {exit_msg[:200]}")

        # Save state for potential resume
        orchestrator.save_state()

        # Update instance status
        if orchestrator.instance_id:
            from zwarm.core.state import update_instance_status
            update_instance_status(
                orchestrator.instance_id,
                "completed",
                working_dir / ".zwarm",
            )
            console.print(f"  [dim]Instance {orchestrator.instance_id[:8]} marked completed[/]")

    except KeyboardInterrupt:
        console.print("\n\n[yellow]Interrupted.[/]")
        if orchestrator:
            orchestrator.save_state()
            console.print("[dim]State saved. Use --resume to continue.[/]")
            # Keep instance as "active" so it can be resumed
        sys.exit(1)
    except Exception as e:
        console.print(f"\n[red]Error:[/] {e}")
        if verbose:
            console.print_exception()
        # Update instance status to failed
        if orchestrator and orchestrator.instance_id:
            from zwarm.core.state import update_instance_status
            update_instance_status(
                orchestrator.instance_id,
                "failed",
                working_dir / ".zwarm",
            )
        sys.exit(1)


@app.command()
def exec(
    task: Annotated[str, typer.Option("--task", "-t", help="Task to execute")],
    adapter: Annotated[AdapterType, typer.Option("--adapter", "-a", help="Executor adapter")] = AdapterType.codex_mcp,
    mode: Annotated[ModeType, typer.Option("--mode", "-m", help="Execution mode")] = ModeType.sync,
    working_dir: Annotated[Path, typer.Option("--working-dir", "-w", help="Working directory")] = Path("."),
    model: Annotated[Optional[str], typer.Option("--model", help="Model override")] = None,
):
    """
    Run a single executor directly (for testing).

    Useful for testing adapters without the full orchestrator loop.

    [bold]Examples:[/]
        [dim]# Test Codex[/]
        $ zwarm exec --task "What is 2+2?"

        [dim]# Test Claude Code[/]
        $ zwarm exec -a claude_code --task "List files in current dir"

        [dim]# Async mode[/]
        $ zwarm exec --task "Build feature" --mode async
    """
    from zwarm.adapters import get_adapter

    console.print(f"[bold]Running executor directly...[/]")
    console.print(f"  Adapter: [cyan]{adapter.value}[/]")
    console.print(f"  Mode: {mode.value}")
    console.print(f"  Task: {task}")

    # Use isolated codex config if available
    config_path = working_dir / ".zwarm" / "codex.toml"
    if not config_path.exists():
        config_path = None

    try:
        executor = get_adapter(adapter.value, model=model, config_path=config_path)
    except ValueError as e:
        console.print(f"[red]Error:[/] {e}")
        sys.exit(1)

    async def run():
        try:
            session = await executor.start_session(
                task=task,
                working_dir=working_dir.absolute(),
                mode=mode.value,
                model=model,
            )

            console.print(f"\n[green]Session started:[/] {session.id[:8]}")

            if mode == ModeType.sync:
                response = session.messages[-1].content if session.messages else "(no response)"
                console.print(f"\n[bold]Response:[/]\n{response}")

                # Interactive loop for sync mode
                while True:
                    try:
                        user_input = console.input("\n[dim]> (type message or 'exit')[/] ")
                        if user_input.lower() == "exit" or not user_input:
                            break

                        response = await executor.send_message(session, user_input)
                        console.print(f"\n[bold]Response:[/]\n{response}")
                    except KeyboardInterrupt:
                        break
            else:
                console.print("[dim]Async mode - session running in background.[/]")
                console.print("Use 'zwarm status' to check progress.")

        finally:
            await executor.cleanup()

    asyncio.run(run())


@app.command()
def status(
    working_dir: Annotated[Path, typer.Option("--working-dir", "-w", help="Working directory")] = Path("."),
):
    """
    Show current state (sessions, tasks, events).

    Displays active sessions, pending tasks, and recent events
    from the .zwarm state directory.

    [bold]Example:[/]
        $ zwarm status
    """
    from zwarm.core.state import StateManager

    state_dir = working_dir / ".zwarm"
    if not state_dir.exists():
        console.print("[yellow]No zwarm state found in this directory.[/]")
        console.print("[dim]Run 'zwarm orchestrate' to start.[/]")
        return

    state = StateManager(state_dir)
    state.load()

    # Sessions table
    sessions = state.list_sessions()
    console.print(f"\n[bold]Sessions[/] ({len(sessions)})")
    if sessions:
        table = Table(show_header=True, header_style="bold")
        table.add_column("ID", style="dim")
        table.add_column("Mode")
        table.add_column("Status")
        table.add_column("Task")

        for s in sessions:
            status_style = {"active": "green", "completed": "blue", "failed": "red"}.get(s.status.value, "white")
            table.add_row(
                s.id[:8],
                s.mode.value,
                f"[{status_style}]{s.status.value}[/]",
                s.task_description[:50] + "..." if len(s.task_description) > 50 else s.task_description,
            )
        console.print(table)
    else:
        console.print("  [dim](none)[/]")

    # Tasks table
    tasks = state.list_tasks()
    console.print(f"\n[bold]Tasks[/] ({len(tasks)})")
    if tasks:
        table = Table(show_header=True, header_style="bold")
        table.add_column("ID", style="dim")
        table.add_column("Status")
        table.add_column("Description")

        for t in tasks:
            status_style = {"pending": "yellow", "in_progress": "cyan", "completed": "green", "failed": "red"}.get(t.status.value, "white")
            table.add_row(
                t.id[:8],
                f"[{status_style}]{t.status.value}[/]",
                t.description[:50] + "..." if len(t.description) > 50 else t.description,
            )
        console.print(table)
    else:
        console.print("  [dim](none)[/]")

    # Recent events
    events = state.get_events(limit=5)
    console.print(f"\n[bold]Recent Events[/]")
    if events:
        for e in events:
            console.print(f"  [dim]{e.timestamp.strftime('%H:%M:%S')}[/] {e.kind}")
    else:
        console.print("  [dim](none)[/]")


@app.command()
def instances(
    working_dir: Annotated[Path, typer.Option("--working-dir", "-w", help="Working directory")] = Path("."),
    all_instances: Annotated[bool, typer.Option("--all", "-a", help="Show all instances (including completed)")] = False,
):
    """
    List all orchestrator instances.

    Shows instances that have been run in this directory. Use --all to include
    completed instances.

    [bold]Examples:[/]
        [dim]# List active instances[/]
        $ zwarm instances

        [dim]# List all instances[/]
        $ zwarm instances --all
    """
    from zwarm.core.state import list_instances as get_instances

    state_dir = working_dir / ".zwarm"
    all_inst = get_instances(state_dir)

    if not all_inst:
        console.print("[dim]No instances found.[/]")
        console.print("[dim]Run 'zwarm orchestrate' to start a new instance.[/]")
        return

    # Filter if not showing all
    if not all_instances:
        all_inst = [i for i in all_inst if i.get("status") == "active"]

    if not all_inst:
        console.print("[dim]No active instances. Use --all to see completed ones.[/]")
        return

    console.print(f"[bold]Instances[/] ({len(all_inst)} total)\n")

    for inst in all_inst:
        status = inst.get("status", "unknown")
        status_icon = {"active": "[green]●[/]", "completed": "[dim]✓[/]", "failed": "[red]✗[/]"}.get(status, "[dim]?[/]")

        inst_id = inst.get("id", "unknown")[:8]
        name = inst.get("name", "")
        task = (inst.get("task") or "")[:60]
        updated = inst.get("updated_at", "")[:19] if inst.get("updated_at") else ""

        console.print(f"  {status_icon} [bold]{inst_id}[/]" + (f" ({name})" if name and name != inst_id else ""))
        if task:
            console.print(f"      [dim]{task}[/]")
        if updated:
            console.print(f"      [dim]Updated: {updated}[/]")
        console.print()

    console.print("[dim]Use --instance <id> with 'orchestrate --resume' to resume an instance.[/]")


@app.command()
def history(
    working_dir: Annotated[Path, typer.Option("--working-dir", "-w", help="Working directory")] = Path("."),
    kind: Annotated[Optional[str], typer.Option("--kind", "-k", help="Filter by event kind")] = None,
    limit: Annotated[int, typer.Option("--limit", "-n", help="Number of events")] = 20,
):
    """
    Show event history.

    Displays the append-only event log with timestamps and details.

    [bold]Examples:[/]
        [dim]# Show last 20 events[/]
        $ zwarm history

        [dim]# Show more events[/]
        $ zwarm history --limit 50

        [dim]# Filter by kind[/]
        $ zwarm history --kind session_started
    """
    from zwarm.core.state import StateManager

    state_dir = working_dir / ".zwarm"
    if not state_dir.exists():
        console.print("[yellow]No zwarm state found.[/]")
        return

    state = StateManager(state_dir)
    events = state.get_events(kind=kind, limit=limit)

    console.print(f"\n[bold]Event History[/] (last {limit})\n")

    if not events:
        console.print("[dim]No events found.[/]")
        return

    table = Table(show_header=True, header_style="bold")
    table.add_column("Time", style="dim")
    table.add_column("Event")
    table.add_column("Session/Task")
    table.add_column("Details")

    for e in events:
        details = ""
        if e.payload:
            details = ", ".join(f"{k}={str(v)[:30]}" for k, v in list(e.payload.items())[:2])

        table.add_row(
            e.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
            e.kind,
            (e.session_id or e.task_id or "-")[:8],
            details[:60],
        )

    console.print(table)


@configs_app.command("list")
def configs_list(
    config_dir: Annotated[Optional[Path], typer.Option("--dir", "-d", help="Directory to search")] = None,
):
    """
    List available agent/experiment configuration files (YAML).

    Note: config.toml is for user environment settings and is loaded
    automatically - use YAML files for agent configurations.

    [bold]Example:[/]
        $ zwarm configs list
    """
    search_dirs = [
        config_dir or Path.cwd(),
        Path.cwd() / "configs",
        Path.cwd() / ".zwarm",
    ]

    console.print("\n[bold]Available Configurations[/]\n")
    found = False

    for d in search_dirs:
        if not d.exists():
            continue
        for pattern in ["*.yaml", "*.yml"]:
            for f in d.glob(pattern):
                found = True
                try:
                    rel = f.relative_to(Path.cwd())
                    console.print(f"  [cyan]{rel}[/]")
                except ValueError:
                    console.print(f"  [cyan]{f}[/]")

    if not found:
        console.print("  [dim]No configuration files found.[/]")
        console.print("\n  [dim]Create a YAML config in configs/ to get started.[/]")

    # Check for config.toml and mention it (check both locations)
    new_config = Path.cwd() / ".zwarm" / "config.toml"
    legacy_config = Path.cwd() / "config.toml"
    if new_config.exists():
        console.print(f"\n[dim]Environment: .zwarm/config.toml (loaded automatically)[/]")
    elif legacy_config.exists():
        console.print(f"\n[dim]Environment: config.toml (legacy location, loaded automatically)[/]")


@configs_app.command("show")
def configs_show(
    config_path: Annotated[Path, typer.Argument(help="Path to configuration file")],
):
    """
    Show a configuration file's contents.

    Loads and displays the resolved configuration including
    any inherited values from 'extends:' directives.

    [bold]Example:[/]
        $ zwarm configs show configs/base.yaml
    """
    from zwarm.core.config import load_config
    import json

    if not config_path.exists():
        console.print(f"[red]File not found:[/] {config_path}")
        raise typer.Exit(1)

    try:
        config = load_config(config_path=config_path)
        console.print(f"\n[bold]Configuration:[/] {config_path}\n")
        console.print_json(json.dumps(config.to_dict(), indent=2))
    except Exception as e:
        console.print(f"[red]Error loading config:[/] {e}")
        raise typer.Exit(1)


@app.command()
def init(
    working_dir: Annotated[Path, typer.Option("--working-dir", "-w", help="Working directory")] = Path("."),
    non_interactive: Annotated[bool, typer.Option("--yes", "-y", help="Accept defaults, no prompts")] = False,
    with_project: Annotated[bool, typer.Option("--with-project", help="Create zwarm.yaml project config")] = False,
):
    """
    Initialize zwarm in the current directory.

    Creates configuration files and the .zwarm state directory.
    Run this once per project to set up zwarm.

    [bold]Creates:[/]
        [cyan].zwarm/[/]              State directory for sessions and events
        [cyan].zwarm/config.toml[/]   Runtime settings (weave, adapter, watchers)
        [cyan]zwarm.yaml[/]           Project config (optional, with --with-project)

    [bold]Examples:[/]
        [dim]# Interactive setup[/]
        $ zwarm init

        [dim]# Quick setup with defaults[/]
        $ zwarm init --yes

        [dim]# Full setup with project config[/]
        $ zwarm init --with-project
    """
    console.print("\n[bold cyan]zwarm init[/] - Initialize zwarm configuration\n")

    state_dir = working_dir / ".zwarm"
    config_toml_path = state_dir / "config.toml"
    zwarm_yaml_path = working_dir / "zwarm.yaml"

    # Check for existing config (also check old location for migration)
    old_config_path = working_dir / "config.toml"
    if old_config_path.exists() and not config_toml_path.exists():
        console.print(f"[yellow]Note:[/] Found config.toml in project root.")
        console.print(f"  Config now lives in .zwarm/config.toml")
        if not non_interactive:
            migrate = typer.confirm("  Move to new location?", default=True)
            if migrate:
                state_dir.mkdir(parents=True, exist_ok=True)
                old_config_path.rename(config_toml_path)
                console.print(f"  [green]✓[/] Moved config.toml to .zwarm/")

    # Check for existing files
    if config_toml_path.exists():
        console.print(f"[yellow]Warning:[/] .zwarm/config.toml already exists")
        if not non_interactive:
            overwrite = typer.confirm("Overwrite?", default=False)
            if not overwrite:
                console.print("[dim]Skipping config.toml[/]")
                config_toml_path = None
        else:
            config_toml_path = None

    # Gather settings
    weave_project = ""
    adapter = "codex_mcp"
    watchers_enabled = ["progress", "budget", "delegation", "delegation_reminder"]
    create_project_config = with_project
    project_description = ""
    project_context = ""

    if not non_interactive:
        console.print("[bold]Configuration[/]\n")

        # Weave project
        weave_project = typer.prompt(
            "  Weave project (entity/project, blank to skip)",
            default="",
            show_default=False,
        )

        # Adapter
        adapter = typer.prompt(
            "  Default adapter",
            default="codex_mcp",
            type=str,
        )

        # Watchers
        console.print("\n  [bold]Watchers[/] (trajectory aligners)")
        available_watchers = ["progress", "budget", "delegation", "delegation_reminder", "scope", "pattern", "quality"]
        watchers_enabled = []
        for w in available_watchers:
            default = w in ["progress", "budget", "delegation", "delegation_reminder"]
            if typer.confirm(f"    Enable {w}?", default=default):
                watchers_enabled.append(w)

        # Project config
        console.print()
        create_project_config = typer.confirm(
            "  Create zwarm.yaml project config?",
            default=with_project,
        )

        if create_project_config:
            project_description = typer.prompt(
                "    Project description",
                default="",
                show_default=False,
            )
            console.print("    [dim]Project context (optional, press Enter twice to finish):[/]")
            context_lines = []
            while True:
                line = typer.prompt("    ", default="", show_default=False)
                if not line:
                    break
                context_lines.append(line)
            project_context = "\n".join(context_lines)

    # Create .zwarm directory
    console.print("\n[bold]Creating files...[/]\n")

    state_dir.mkdir(parents=True, exist_ok=True)
    (state_dir / "sessions").mkdir(exist_ok=True)
    (state_dir / "orchestrator").mkdir(exist_ok=True)
    console.print(f"  [green]✓[/] Created .zwarm/")

    # Create config.toml inside .zwarm/
    if config_toml_path:
        toml_content = _generate_config_toml(
            weave_project=weave_project,
            adapter=adapter,
            watchers=watchers_enabled,
        )
        config_toml_path.write_text(toml_content)
        console.print(f"  [green]✓[/] Created .zwarm/config.toml")

    # Create codex.toml for isolated codex configuration
    codex_toml_path = state_dir / "codex.toml"
    if not codex_toml_path.exists():
        codex_content = _generate_codex_toml()
        codex_toml_path.write_text(codex_content)
        console.print(f"  [green]✓[/] Created .zwarm/codex.toml (isolated codex config)")

    # Create zwarm.yaml
    if create_project_config:
        if zwarm_yaml_path.exists() and not non_interactive:
            overwrite = typer.confirm("  zwarm.yaml exists. Overwrite?", default=False)
            if not overwrite:
                create_project_config = False

        if create_project_config:
            yaml_content = _generate_zwarm_yaml(
                description=project_description,
                context=project_context,
                watchers=watchers_enabled,
            )
            zwarm_yaml_path.write_text(yaml_content)
            console.print(f"  [green]✓[/] Created zwarm.yaml")

    # Summary
    console.print("\n[bold green]Done![/] zwarm is ready.\n")
    console.print("[bold]Next steps:[/]")
    console.print("  [dim]# Run the orchestrator[/]")
    console.print("  $ zwarm orchestrate --task \"Your task here\"\n")
    console.print("  [dim]# Or test an executor directly[/]")
    console.print("  $ zwarm exec --task \"What is 2+2?\"\n")


def _generate_config_toml(
    weave_project: str = "",
    adapter: str = "codex_mcp",
    watchers: list[str] | None = None,
) -> str:
    """Generate config.toml content."""
    watchers = watchers or []

    lines = [
        "# zwarm configuration",
        "# Generated by 'zwarm init'",
        "",
        "[weave]",
    ]

    if weave_project:
        lines.append(f'project = "{weave_project}"')
    else:
        lines.append("# project = \"your-entity/your-project\"  # Uncomment to enable Weave tracing")

    lines.extend([
        "",
        "[orchestrator]",
        "max_steps = 50",
        "",
        "[executor]",
        f'adapter = "{adapter}"',
        "# model = \"\"  # Optional model override",
        "",
        "[watchers]",
        f"enabled = {watchers}",
        "",
        "# Watcher-specific configuration",
        "# [watchers.budget]",
        "# max_steps = 50",
        "# warn_at_percent = 80",
        "",
        "# [watchers.pattern]",
        "# patterns = [\"DROP TABLE\", \"rm -rf\"]",
        "",
    ])

    return "\n".join(lines)


def _generate_codex_toml(
    model: str = "gpt-5.1-codex-mini",
    reasoning_effort: str = "high",
) -> str:
    """
    Generate codex.toml for isolated codex configuration.

    This file is used by zwarm instead of ~/.codex/config.toml to ensure
    consistent behavior across different environments.
    """
    lines = [
        "# Codex configuration for zwarm",
        "# This file isolates zwarm's codex settings from your global ~/.codex/config.toml",
        "# Generated by 'zwarm init'",
        "",
        "# Model settings",
        f'model = "{model}"',
        f'model_reasoning_effort = "{reasoning_effort}"  # low | medium | high',
        "",
        "# Approval settings - zwarm manages these automatically",
        "# disable_response_storage = false",
        "",
        "# You can override any codex setting here",
        "# See: https://github.com/openai/codex#configuration",
        "",
    ]
    return "\n".join(lines)


def _generate_zwarm_yaml(
    description: str = "",
    context: str = "",
    watchers: list[str] | None = None,
) -> str:
    """Generate zwarm.yaml project config."""
    watchers = watchers or []

    lines = [
        "# zwarm project configuration",
        "# Customize the orchestrator for this specific project",
        "",
        f'description: "{description}"' if description else 'description: ""',
        "",
        "# Project-specific context injected into the orchestrator",
        "# This helps the orchestrator understand your codebase",
        "context: |",
    ]

    if context:
        for line in context.split("\n"):
            lines.append(f"  {line}")
    else:
        lines.extend([
            "  # Describe your project here. For example:",
            "  # - Tech stack (FastAPI, React, PostgreSQL)",
            "  # - Key directories (src/api/, src/components/)",
            "  # - Coding conventions to follow",
        ])

    lines.extend([
        "",
        "# Project-specific constraints",
        "# The orchestrator will be reminded to follow these",
        "constraints:",
        "  # - \"Never modify migration files directly\"",
        "  # - \"All new endpoints need tests\"",
        "  # - \"Use existing patterns from src/api/\"",
        "",
        "# Default watchers for this project",
        "watchers:",
    ])

    for w in watchers:
        lines.append(f"  - {w}")

    if not watchers:
        lines.append("  # - progress")
        lines.append("  # - budget")

    lines.append("")

    return "\n".join(lines)


@app.command()
def reset(
    working_dir: Annotated[Path, typer.Option("--working-dir", "-w", help="Working directory")] = Path("."),
    state: Annotated[bool, typer.Option("--state", "-s", help="Reset .zwarm/ state directory")] = True,
    config: Annotated[bool, typer.Option("--config", "-c", help="Also delete config.toml")] = False,
    project: Annotated[bool, typer.Option("--project", "-p", help="Also delete zwarm.yaml")] = False,
    all_files: Annotated[bool, typer.Option("--all", "-a", help="Delete everything (state + config + project)")] = False,
    force: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation")] = False,
):
    """
    Reset zwarm state and optionally configuration files.

    By default, only clears the .zwarm/ state directory (sessions, events, orchestrator history).
    Use flags to also remove configuration files.

    [bold]Examples:[/]
        [dim]# Reset state only (default)[/]
        $ zwarm reset

        [dim]# Reset everything, no confirmation[/]
        $ zwarm reset --all --yes

        [dim]# Reset state and config.toml[/]
        $ zwarm reset --config
    """
    import shutil

    console.print("\n[bold cyan]zwarm reset[/] - Reset zwarm state\n")

    state_dir = working_dir / ".zwarm"
    config_toml_path = state_dir / "config.toml"  # New location
    old_config_toml_path = working_dir / "config.toml"  # Legacy location
    zwarm_yaml_path = working_dir / "zwarm.yaml"

    # Expand --all flag
    if all_files:
        state = True
        config = True
        project = True

    # Collect what will be deleted
    to_delete = []
    if state and state_dir.exists():
        to_delete.append((".zwarm/", state_dir))
    # Config: check both new and legacy locations (but skip if state already deletes it)
    if config and not state:
        if config_toml_path.exists():
            to_delete.append((".zwarm/config.toml", config_toml_path))
        if old_config_toml_path.exists():
            to_delete.append(("config.toml (legacy)", old_config_toml_path))
    if project and zwarm_yaml_path.exists():
        to_delete.append(("zwarm.yaml", zwarm_yaml_path))

    if not to_delete:
        console.print("[yellow]Nothing to reset.[/] No matching files found.")
        raise typer.Exit(0)

    # Show what will be deleted
    console.print("[bold]Will delete:[/]")
    for name, path in to_delete:
        if path.is_dir():
            # Count contents
            files = list(path.rglob("*"))
            file_count = len([f for f in files if f.is_file()])
            console.print(f"  [red]✗[/] {name} ({file_count} files)")
        else:
            console.print(f"  [red]✗[/] {name}")

    # Confirm
    if not force:
        console.print()
        confirm = typer.confirm("Proceed with reset?", default=False)
        if not confirm:
            console.print("[dim]Aborted.[/]")
            raise typer.Exit(0)

    # Delete
    console.print("\n[bold]Deleting...[/]")
    for name, path in to_delete:
        try:
            if path.is_dir():
                shutil.rmtree(path)
            else:
                path.unlink()
            console.print(f"  [green]✓[/] Deleted {name}")
        except Exception as e:
            console.print(f"  [red]✗[/] Failed to delete {name}: {e}")

    console.print("\n[bold green]Reset complete.[/]")
    console.print("\n[dim]Run 'zwarm init' to set up again.[/]\n")


@app.command()
def clean(
    force: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation")] = False,
    dry_run: Annotated[bool, typer.Option("--dry-run", "-n", help="Show what would be killed without killing")] = False,
):
    """
    Clean up orphaned processes from zwarm sessions.

    Finds and kills:
    - Orphaned codex mcp-server processes
    - Orphaned codex exec processes
    - Orphaned claude CLI processes

    [bold]Examples:[/]
        [dim]# See what would be cleaned[/]
        $ zwarm clean --dry-run

        [dim]# Clean without confirmation[/]
        $ zwarm clean --yes
    """
    import subprocess
    import signal

    console.print("\n[bold cyan]zwarm clean[/] - Clean up orphaned processes\n")

    # Patterns to search for
    patterns = [
        ("codex mcp-server", "Codex MCP server"),
        ("codex exec", "Codex exec"),
        ("claude.*--permission-mode", "Claude CLI"),
    ]

    found_processes = []

    for pattern, description in patterns:
        try:
            # Use pgrep to find matching processes
            result = subprocess.run(
                ["pgrep", "-f", pattern],
                capture_output=True,
                text=True,
            )
            if result.returncode == 0 and result.stdout.strip():
                pids = result.stdout.strip().split("\n")
                for pid in pids:
                    pid = pid.strip()
                    if pid and pid.isdigit():
                        # Get process info
                        try:
                            ps_result = subprocess.run(
                                ["ps", "-p", pid, "-o", "pid,ppid,etime,command"],
                                capture_output=True,
                                text=True,
                            )
                            if ps_result.returncode == 0:
                                lines = ps_result.stdout.strip().split("\n")
                                if len(lines) > 1:
                                    # Skip header, get process line
                                    proc_info = lines[1].strip()
                                    found_processes.append((int(pid), description, proc_info))
                        except Exception:
                            found_processes.append((int(pid), description, "(unknown)"))
        except FileNotFoundError:
            # pgrep not available, try ps with grep
            try:
                result = subprocess.run(
                    f"ps aux | grep '{pattern}' | grep -v grep",
                    shell=True,
                    capture_output=True,
                    text=True,
                )
                if result.returncode == 0 and result.stdout.strip():
                    for line in result.stdout.strip().split("\n"):
                        parts = line.split()
                        if len(parts) >= 2:
                            pid = parts[1]
                            if pid.isdigit():
                                found_processes.append((int(pid), description, line[:80]))
            except Exception:
                pass
        except Exception as e:
            console.print(f"[yellow]Warning:[/] Error searching for {description}: {e}")

    if not found_processes:
        console.print("[green]No orphaned processes found.[/] Nothing to clean.\n")
        raise typer.Exit(0)

    # Show what was found
    console.print(f"[bold]Found {len(found_processes)} process(es):[/]\n")
    for pid, description, info in found_processes:
        console.print(f"  [yellow]PID {pid}[/] - {description}")
        console.print(f"    [dim]{info[:100]}{'...' if len(info) > 100 else ''}[/]")

    if dry_run:
        console.print("\n[dim]Dry run - no processes killed.[/]\n")
        raise typer.Exit(0)

    # Confirm
    if not force:
        console.print()
        confirm = typer.confirm(f"Kill {len(found_processes)} process(es)?", default=False)
        if not confirm:
            console.print("[dim]Aborted.[/]")
            raise typer.Exit(0)

    # Kill processes
    console.print("\n[bold]Cleaning up...[/]")
    killed = 0
    failed = 0

    for pid, description, _ in found_processes:
        try:
            # First try SIGTERM
            os.kill(pid, signal.SIGTERM)
            console.print(f"  [green]✓[/] Killed PID {pid} ({description})")
            killed += 1
        except ProcessLookupError:
            console.print(f"  [dim]○[/] PID {pid} already gone")
        except PermissionError:
            console.print(f"  [red]✗[/] PID {pid} - permission denied (try sudo)")
            failed += 1
        except Exception as e:
            console.print(f"  [red]✗[/] PID {pid} - {e}")
            failed += 1

    console.print(f"\n[bold green]Cleanup complete.[/] Killed {killed}, failed {failed}.\n")


@app.command()
def interactive(
    default_dir: Annotated[Path, typer.Option("--dir", "-d", help="Default working directory")] = Path("."),
    model: Annotated[Optional[str], typer.Option("--model", help="Default model override")] = None,
    adapter: Annotated[str, typer.Option("--adapter", "-a", help="Executor adapter")] = "codex_mcp",
    state_dir: Annotated[Path, typer.Option("--state-dir", help="State directory for persistence")] = Path(".zwarm"),
):
    """
    Universal multi-agent CLI for commanding coding agents.

    Spawn multiple agents across different directories, manage them interactively,
    and view their outputs. You are the orchestrator.

    This uses the SAME code path as `zwarm orchestrate` - the adapter layer.
    Interactive is the human-in-the-loop version, orchestrate is the LLM version.

    [bold]Commands:[/]
        [cyan]spawn[/] "task" [opts]      Start a coding agent session (sync mode)
        [cyan]async[/] "task" [opts]      Start async session (fire-and-forget)
        [cyan]ls[/] / [cyan]list[/]               Dashboard of all sessions
        [cyan]?[/] ID                    Quick peek (status + latest message)
        [cyan]show[/] ID                  Full session details & history
        [cyan]traj[/] ID                  Show trajectory (all steps taken)
        [cyan]c[/] / [cyan]continue[/] ID "msg"   Continue a sync conversation
        [cyan]kill[/] ID                  Stop a session (keeps in history)
        [cyan]rm[/] ID                    Delete session entirely
        [cyan]killall[/]                  Stop all running sessions
        [cyan]clean[/]                    Remove old sessions (>7 days)
        [cyan]q[/] / [cyan]quit[/]                Exit

    [bold]Spawn Options:[/]
        spawn "task" --dir ~/project --model gpt-5.1-codex-max --async

    [bold]Examples:[/]
        $ zwarm interactive
        > spawn "Build auth module" --dir ~/api
        > spawn "Fix tests" --dir ~/api
        > c abc123 "Now add error handling"
        > ls
        > ? abc123
    """
    from zwarm.adapters import get_adapter, list_adapters
    from zwarm.core.models import ConversationSession, SessionStatus, SessionMode
    import argparse

    # Initialize adapter (same as orchestrator uses)
    default_model = model or "gpt-5.1-codex-mini"
    default_adapter = adapter

    # Config path for isolated codex configuration
    codex_config_path = state_dir / "codex.toml"
    if not codex_config_path.exists():
        # Try relative to working dir
        codex_config_path = default_dir / ".zwarm" / "codex.toml"
    if not codex_config_path.exists():
        codex_config_path = None  # Fall back to overrides

    # Session tracking - same pattern as orchestrator
    sessions: dict[str, ConversationSession] = {}
    adapters_cache: dict[str, Any] = {}

    def get_or_create_adapter(adapter_name: str, session_model: str | None = None) -> Any:
        """Get or create an adapter instance with isolated config."""
        cache_key = f"{adapter_name}:{session_model or default_model}"
        if cache_key not in adapters_cache:
            adapters_cache[cache_key] = get_adapter(
                adapter_name,
                model=session_model or default_model,
                config_path=codex_config_path,
            )
        return adapters_cache[cache_key]

    def find_session(query: str) -> tuple[ConversationSession | None, str | None]:
        """Find session by full or partial ID."""
        if query in sessions:
            return sessions[query], query
        for sid, session in sessions.items():
            if sid.startswith(query):
                return session, sid
        return None, None

    console.print("\n[bold cyan]zwarm interactive[/] - Multi-Agent Command Center\n")
    console.print(f"  Working dir: {default_dir.absolute()}")
    console.print(f"  Model: [cyan]{default_model}[/]")
    console.print(f"  Adapter: [cyan]{default_adapter}[/]")
    if codex_config_path:
        console.print(f"  Config: [green]{codex_config_path}[/] (isolated)")
    else:
        console.print(f"  Config: [yellow]using fallback overrides[/] (run 'zwarm init' for isolation)")
    console.print(f"  Available: {', '.join(list_adapters())}")
    console.print("\n  Type [cyan]help[/] for commands, [cyan]quit[/] to exit.\n")

    def show_help():
        help_table = Table(show_header=False, box=None, padding=(0, 2))
        help_table.add_column("Command", style="cyan", width=35)
        help_table.add_column("Description")
        help_table.add_row('spawn "task" [options]', "Start session (waits for completion)")
        help_table.add_row("  --dir PATH", "Working directory")
        help_table.add_row("  --model NAME", "Model override")
        help_table.add_row("  --async", "Background mode (don't wait)")
        help_table.add_row("", "")
        help_table.add_row("ls / list", "Dashboard of all sessions")
        help_table.add_row("? ID / peek ID", "Quick peek (status + latest message)")
        help_table.add_row("show ID", "Full session details & messages")
        help_table.add_row("traj ID [--full]", "Show trajectory (all steps taken)")
        help_table.add_row('c ID "msg"', "Continue conversation (wait for response)")
        help_table.add_row('ca ID "msg"', "Continue async (fire-and-forget)")
        help_table.add_row("check ID", "Check session status")
        help_table.add_row("kill ID", "Stop a running session")
        help_table.add_row("rm ID", "Delete session entirely")
        help_table.add_row("killall", "Stop all running sessions")
        help_table.add_row("clean", "Remove old completed sessions")
        help_table.add_row("q / quit", "Exit")
        console.print(help_table)

    def show_sessions():
        """List all sessions from CodexSessionManager (same as orchestrator)."""
        from zwarm.sessions import CodexSessionManager, SessionStatus as SessStatus
        from datetime import datetime

        manager = CodexSessionManager(default_dir / ".zwarm")
        all_sessions = manager.list_sessions()

        if not all_sessions:
            console.print("  [dim]No sessions. Use 'spawn \"task\"' to start one.[/]")
            return

        # Status summary
        running = sum(1 for s in all_sessions if s.status == SessStatus.RUNNING)
        completed = sum(1 for s in all_sessions if s.status == SessStatus.COMPLETED)
        failed = sum(1 for s in all_sessions if s.status == SessStatus.FAILED)
        killed = sum(1 for s in all_sessions if s.status == SessStatus.KILLED)

        summary_parts = []
        if running:
            summary_parts.append(f"[yellow]{running} running[/]")
        if completed:
            summary_parts.append(f"[green]{completed} done[/]")
        if failed:
            summary_parts.append(f"[red]{failed} failed[/]")
        if killed:
            summary_parts.append(f"[dim]{killed} killed[/]")
        if summary_parts:
            console.print(" | ".join(summary_parts))
            console.print()

        def time_ago(iso_str: str) -> str:
            """Convert ISO timestamp to human-readable 'X ago' format."""
            try:
                dt = datetime.fromisoformat(iso_str)
                delta = datetime.now() - dt
                secs = delta.total_seconds()
                if secs < 60:
                    return f"{int(secs)}s"
                elif secs < 3600:
                    return f"{int(secs/60)}m"
                elif secs < 86400:
                    return f"{secs/3600:.1f}h"
                else:
                    return f"{secs/86400:.1f}d"
            except:
                return "?"

        table = Table(box=None, show_header=True, header_style="bold dim")
        table.add_column("ID", style="cyan", width=10)
        table.add_column("", width=2)  # Status icon
        table.add_column("T", width=2)  # Turn
        table.add_column("Task", max_width=30)
        table.add_column("Updated", justify="right", width=8)
        table.add_column("Last Message", max_width=40)

        status_icons = {
            "running": "[yellow]●[/]",
            "completed": "[green]✓[/]",
            "failed": "[red]✗[/]",
            "killed": "[dim]○[/]",
            "pending": "[dim]◌[/]",
        }

        for s in all_sessions:
            icon = status_icons.get(s.status.value, "?")
            task_preview = s.task[:27] + "..." if len(s.task) > 30 else s.task
            updated = time_ago(s.updated_at)

            # Get last assistant message preview
            messages = manager.get_messages(s.id)
            last_msg = ""
            for msg in reversed(messages):
                if msg.role == "assistant":
                    last_msg = msg.content.replace("\n", " ")[:37]
                    if len(msg.content) > 37:
                        last_msg += "..."
                    break

            # Style the last message based on recency
            if s.status == SessStatus.RUNNING:
                last_msg_styled = f"[yellow]{last_msg or '(working...)'}[/]"
                updated_styled = f"[yellow]{updated}[/]"
            elif s.status == SessStatus.COMPLETED:
                # Highlight if recently completed (< 60s)
                try:
                    dt = datetime.fromisoformat(s.updated_at)
                    is_recent = (datetime.now() - dt).total_seconds() < 60
                except:
                    is_recent = False
                if is_recent:
                    last_msg_styled = f"[green bold]{last_msg or '(done)'}[/]"
                    updated_styled = f"[green bold]{updated} ★[/]"
                else:
                    last_msg_styled = f"[green]{last_msg or '(done)'}[/]"
                    updated_styled = f"[dim]{updated}[/]"
            elif s.status == SessStatus.FAILED:
                last_msg_styled = f"[red]{s.error[:37] if s.error else '(failed)'}...[/]"
                updated_styled = f"[red]{updated}[/]"
            else:
                last_msg_styled = f"[dim]{last_msg or '-'}[/]"
                updated_styled = f"[dim]{updated}[/]"

            table.add_row(
                s.short_id,
                icon,
                str(s.turn),
                task_preview,
                updated_styled,
                last_msg_styled,
            )

        console.print(table)

    def parse_spawn_args(args: list[str]) -> dict:
        """Parse spawn command arguments."""
        parser = argparse.ArgumentParser(add_help=False)
        parser.add_argument("task", nargs="*")
        parser.add_argument("--dir", "-d", type=Path, default=None)
        parser.add_argument("--model", "-m", default=None)
        parser.add_argument("--async", dest="async_mode", action="store_true", default=False)

        try:
            parsed, _ = parser.parse_known_args(args)
            return {
                "task": " ".join(parsed.task) if parsed.task else "",
                "dir": parsed.dir,
                "model": parsed.model,
                "async_mode": parsed.async_mode,
            }
        except SystemExit:
            return {"error": "Invalid spawn arguments"}

    def do_spawn(args: list[str]):
        """Spawn a new coding agent session using CodexSessionManager (same as orchestrator)."""
        from zwarm.sessions import CodexSessionManager, SessionStatus as SessStatus
        import time

        parsed = parse_spawn_args(args)

        if "error" in parsed:
            console.print(f"  [red]{parsed['error']}[/]")
            console.print("  [dim]Usage: spawn \"task\" [--dir PATH] [--model NAME] [--async][/]")
            return

        if not parsed["task"]:
            console.print("  [red]Task required[/]")
            console.print("  [dim]Usage: spawn \"task\" [--dir PATH] [--model NAME] [--async][/]")
            return

        task = parsed["task"]
        work_dir = (parsed["dir"] or default_dir).absolute()
        session_model = parsed["model"] or default_model
        is_async = parsed.get("async_mode", False)

        if not work_dir.exists():
            console.print(f"  [red]Directory not found:[/] {work_dir}")
            return

        mode_str = "async" if is_async else "sync"
        console.print(f"\n[dim]Spawning {mode_str} session...[/]")
        console.print(f"  [dim]Dir: {work_dir}[/]")
        console.print(f"  [dim]Model: {session_model}[/]")

        try:
            # Use CodexSessionManager - SAME as orchestrator's delegate()
            manager = CodexSessionManager(work_dir / ".zwarm")
            session = manager.start_session(
                task=task,
                working_dir=work_dir,
                model=session_model,
                sandbox="workspace-write",
                source="user",
                adapter="codex",
            )

            console.print(f"\n[green]✓[/] Session: [cyan]{session.short_id}[/]")
            console.print(f"  [dim]PID: {session.pid}[/]")

            # For sync mode, wait for completion and show response
            if not is_async:
                console.print(f"\n[dim]Waiting for completion...[/]")
                timeout = 300.0
                start = time.time()
                while time.time() - start < timeout:
                    # get_session() auto-updates status based on output completion
                    session = manager.get_session(session.id)
                    if session.status != SessStatus.RUNNING:
                        break
                    time.sleep(1.0)

                # Get all assistant responses
                messages = manager.get_messages(session.id)
                assistant_msgs = [m for m in messages if m.role == "assistant"]
                if assistant_msgs:
                    console.print(f"\n[bold]Response ({len(assistant_msgs)} message{'s' if len(assistant_msgs) > 1 else ''}):[/]")
                    for msg in assistant_msgs:
                        preview = msg.content[:300]
                        if len(msg.content) > 300:
                            preview += "..."
                        console.print(preview)
                        if len(assistant_msgs) > 1:
                            console.print()  # Blank line between multiple messages

            console.print(f"\n[dim]Use 'show {session.short_id}' to see full details[/]")
            console.print(f"[dim]Use 'c {session.short_id} \"message\"' to continue[/]")

        except Exception as e:
            console.print(f"  [red]Error:[/] {e}")
            import traceback
            console.print(f"  [dim]{traceback.format_exc()}[/]")

    def do_orchestrate(args: list[str]):
        """Spawn an orchestrator agent that delegates to sub-sessions."""
        parsed = parse_spawn_args(args)

        if "error" in parsed:
            console.print(f"  [red]{parsed['error']}[/]")
            console.print("  [dim]Usage: orchestrate \"task\" [--dir PATH][/]")
            return

        if not parsed["task"]:
            console.print("  [red]Task required[/]")
            console.print("  [dim]Usage: orchestrate \"task\" [--dir PATH][/]")
            return

        task = parsed["task"]
        work_dir = (parsed["dir"] or default_dir).absolute()

        if not work_dir.exists():
            console.print(f"  [red]Directory not found:[/] {work_dir}")
            return

        console.print(f"\n[dim]Starting orchestrator...[/]")
        console.print(f"  [dim]Dir: {work_dir}[/]")
        console.print(f"  [dim]Task: {task[:60]}{'...' if len(task) > 60 else ''}[/]")

        import subprocess
        from uuid import uuid4

        # Generate instance ID for tracking
        instance_id = str(uuid4())[:8]

        # Build command to run orchestrator in background
        cmd = [
            sys.executable, "-m", "zwarm.cli.main", "orchestrate",
            "--task", task,
            "--working-dir", str(work_dir),
            "--instance", instance_id,
        ]

        # Create log file for orchestrator output
        log_dir = state_dir / "orchestrators"
        log_dir.mkdir(parents=True, exist_ok=True)
        log_file = log_dir / f"{instance_id}.log"

        try:
            with open(log_file, "w") as f:
                proc = subprocess.Popen(
                    cmd,
                    cwd=work_dir,
                    stdout=f,
                    stderr=subprocess.STDOUT,
                    start_new_session=True,
                )

            console.print(f"\n[green]✓[/] Orchestrator started: [magenta]{instance_id}[/]")
            console.print(f"  PID: {proc.pid}")
            console.print(f"  Log: {log_file}")
            console.print(f"\n[dim]Delegated sessions will appear with source 'orch:{instance_id[:4]}'[/]")
            console.print(f"[dim]Use 'ls' to monitor progress[/]")

        except Exception as e:
            console.print(f"  [red]Error starting orchestrator:[/] {e}")

    def do_peek(session_id: str):
        """Quick peek at session - just status + latest message (for fast polling)."""
        from zwarm.sessions import CodexSessionManager, SessionStatus as SessStatus

        manager = CodexSessionManager(default_dir / ".zwarm")
        session = manager.get_session(session_id)

        if not session:
            console.print(f"  [red]Not found:[/] {session_id}")
            return

        # Status icon
        icon = {
            "running": "[yellow]●[/]",
            "completed": "[green]✓[/]",
            "failed": "[red]✗[/]",
            "killed": "[dim]○[/]",
        }.get(session.status.value, "?")

        # Get latest assistant message
        messages = manager.get_messages(session.id)
        latest = None
        for msg in reversed(messages):
            if msg.role == "assistant":
                latest = msg.content.replace("\n", " ")
                break

        if session.status == SessStatus.RUNNING:
            console.print(f"{icon} [cyan]{session.short_id}[/] [yellow](running...)[/]")
        elif latest:
            # Truncate for one-liner
            preview = latest[:120] + "..." if len(latest) > 120 else latest
            console.print(f"{icon} [cyan]{session.short_id}[/] {preview}")
        elif session.status == SessStatus.FAILED:
            error = (session.error or "unknown")[:80]
            console.print(f"{icon} [cyan]{session.short_id}[/] [red]{error}[/]")
        else:
            console.print(f"{icon} [cyan]{session.short_id}[/] [dim](no response)[/]")

    def do_show(session_id: str):
        """Show full session details and messages using CodexSessionManager."""
        from zwarm.sessions import CodexSessionManager, SessionStatus as SessStatus

        manager = CodexSessionManager(default_dir / ".zwarm")
        session = manager.get_session(session_id)

        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            console.print(f"  [dim]Use 'ls' to see available sessions[/]")
            return

        # Status styling
        status_display = {
            "running": "[yellow]● running[/]",
            "completed": "[green]✓ completed[/]",
            "failed": "[red]✗ failed[/]",
            "killed": "[dim]○ killed[/]",
            "pending": "[dim]◌ pending[/]",
        }.get(session.status.value, str(session.status.value))

        console.print()
        console.print(f"[bold cyan]Session {session.short_id}[/]  {status_display}")
        console.print(f"[dim]Adapter:[/] {session.adapter}  [dim]│[/]  [dim]Model:[/] {session.model}")
        console.print(f"[dim]Task:[/] {session.task}")
        console.print(f"[dim]Dir:[/] {session.working_dir}  [dim]│[/]  [dim]Turn:[/] {session.turn}")
        console.print(f"[dim]Source:[/] {session.source_display}  [dim]│[/]  [dim]Runtime:[/] {session.runtime}")
        if session.pid:
            console.print(f"[dim]PID:[/] {session.pid}")

        # Show log file path
        log_path = default_dir / ".zwarm" / "sessions" / session.id / "turns" / f"turn_{session.turn}.jsonl"
        console.print(f"[dim]Log:[/] {log_path}")
        console.print()

        # Get messages from manager
        messages = manager.get_messages(session.id)

        if not messages:
            if session.is_running:
                console.print("[yellow]Session is still running...[/]")
            else:
                console.print("[dim]No messages captured.[/]")
            return

        # Display messages
        for msg in messages:
            if msg.role == "user":
                console.print(Panel(msg.content, title="[bold blue]User[/]", border_style="blue"))
            elif msg.role == "assistant":
                content = msg.content
                if len(content) > 2000:
                    content = content[:2000] + "\n\n[dim]... (truncated)[/]"
                console.print(Panel(content, title="[bold green]Assistant[/]", border_style="green"))
            elif msg.role == "tool":
                console.print(f"  [dim]Tool: {msg.content[:100]}[/]")

        console.print()
        if session.token_usage:
            tokens = session.token_usage
            console.print(f"[dim]Tokens: {tokens.get('input_tokens', 0):,} in / {tokens.get('output_tokens', 0):,} out[/]")

        if session.error:
            console.print(f"[red]Error:[/] {session.error}")

    def do_trajectory(session_id: str, full: bool = False):
        """Show the full trajectory of a session - all steps in order."""
        from zwarm.sessions import CodexSessionManager

        manager = CodexSessionManager(default_dir / ".zwarm")
        session = manager.get_session(session_id)

        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            return

        trajectory = manager.get_trajectory(session_id, full=full)

        if not trajectory:
            console.print("[dim]No trajectory data available.[/]")
            return

        mode = "[bold](full)[/] " if full else ""
        console.print(f"\n[bold cyan]Trajectory: {session.short_id}[/] {mode}({len(trajectory)} steps)")
        console.print(f"[dim]Task: {session.task[:60]}{'...' if len(session.task) > 60 else ''}[/]")
        console.print()

        # Display each step
        for step in trajectory:
            turn = step.get("turn", 1)
            step_num = step.get("step", 0)
            step_type = step.get("type", "unknown")

            prefix = f"[dim]T{turn}.{step_num:02d}[/]"

            if step_type == "reasoning":
                if full and step.get("full_text"):
                    console.print(f"{prefix} [yellow]thinking:[/]")
                    console.print(f"       {step['full_text']}")
                else:
                    summary = step.get("summary", "")
                    console.print(f"{prefix} [yellow]thinking:[/] {summary}")

            elif step_type == "command":
                cmd = step.get("command", "")
                output = step.get("output", "")
                exit_code = step.get("exit_code", "?")
                # Show command
                console.print(f"{prefix} [cyan]$ {cmd}[/]")
                if output:
                    if full:
                        # Show all output
                        for line in output.split("\n"):
                            console.print(f"       [dim]{line}[/]")
                    else:
                        # Indent output, max 5 lines
                        for line in output.split("\n")[:5]:
                            console.print(f"       [dim]{line}[/]")
                        if output.count("\n") > 5:
                            console.print(f"       [dim]... ({output.count(chr(10))} lines)[/]")
                if exit_code != 0 and exit_code is not None:
                    console.print(f"       [red]exit: {exit_code}[/]")

            elif step_type == "tool_call":
                tool = step.get("tool", "unknown")
                if full and step.get("full_args"):
                    import json
                    console.print(f"{prefix} [magenta]tool:[/] {tool}")
                    console.print(f"       {json.dumps(step['full_args'], indent=2)}")
                else:
                    args = step.get("args_preview", "")
                    console.print(f"{prefix} [magenta]tool:[/] {tool}({args})")

            elif step_type == "tool_output":
                output = step.get("output", "")
                if not full:
                    output = output[:100]
                console.print(f"{prefix} [dim]→ {output}[/]")

            elif step_type == "message":
                if full and step.get("full_text"):
                    console.print(f"{prefix} [green]response:[/]")
                    console.print(f"       {step['full_text']}")
                else:
                    summary = step.get("summary", "")
                    full_len = step.get("full_length", 0)
                    console.print(f"{prefix} [green]response:[/] {summary}")
                    if full_len > 200:
                        console.print(f"       [dim]({full_len} chars total)[/]")

        console.print()

    def do_continue(session_id: str, message: str, wait: bool = True):
        """
        Continue a conversation using CodexSessionManager.inject_message().

        Works for both sync and async sessions:
        - If session was sync (or wait=True): wait for response
        - If session was async (or wait=False): fire-and-forget, check later with '?'
        """
        from zwarm.sessions import CodexSessionManager, SessionStatus as SessStatus
        import time

        manager = CodexSessionManager(default_dir / ".zwarm")
        session = manager.get_session(session_id)

        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            console.print(f"  [dim]Use 'ls' to see available sessions[/]")
            return

        if session.status == SessStatus.RUNNING:
            console.print("[yellow]Session is still running.[/]")
            console.print("[dim]Wait for it to complete, or use '?' to check progress.[/]")
            return

        if session.status == SessStatus.KILLED:
            console.print("[yellow]Session was killed.[/]")
            console.print("[dim]Start a new session with 'spawn'.[/]")
            return

        # Determine if we should wait based on session source
        # Sessions from 'user' with --async flag have source='user'
        # We'll use wait parameter to control this
        should_wait = wait

        console.print(f"\n[dim]Sending message to {session.short_id}...[/]")

        try:
            # Inject message - spawns new background process
            updated_session = manager.inject_message(session.id, message)

            if not updated_session:
                console.print(f"  [red]Failed to inject message[/]")
                return

            console.print(f"[green]✓[/] Message sent (turn {updated_session.turn})")

            if should_wait:
                # Sync mode: wait for completion
                console.print(f"[dim]Waiting for response...[/]")
                timeout = 300.0
                start = time.time()
                while time.time() - start < timeout:
                    # get_session() auto-updates status based on output completion
                    session = manager.get_session(session.id)
                    if session.status != SessStatus.RUNNING:
                        break
                    time.sleep(1.0)

                # Get the response (last assistant message)
                messages = manager.get_messages(session.id)
                response = ""
                for msg in reversed(messages):
                    if msg.role == "assistant":
                        response = msg.content
                        break

                console.print(f"\n[bold]Response:[/]")
                if len(response) > 500:
                    console.print(response[:500] + "...")
                    console.print(f"\n[dim]Use 'show {session.short_id}' to see full response[/]")
                else:
                    console.print(response or "(no response captured)")
            else:
                # Async mode: return immediately
                console.print(f"[dim]Running in background (PID: {updated_session.pid})[/]")
                console.print(f"[dim]Use '? {session.short_id}' to check progress[/]")

        except Exception as e:
            console.print(f"  [red]Error:[/] {e}")
            import traceback
            console.print(f"  [dim]{traceback.format_exc()}[/]")

    def do_check(session_id: str):
        """Check status of a session using CodexSessionManager (same as orchestrator)."""
        from zwarm.sessions import CodexSessionManager

        manager = CodexSessionManager(default_dir / ".zwarm")
        session = manager.get_session(session_id)

        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            console.print(f"  [dim]Use 'ls' to see available sessions[/]")
            return

        status_icon = {
            "running": "●",
            "completed": "✓",
            "failed": "✗",
            "killed": "○",
            "pending": "◌",
        }.get(session.status.value, "?")

        console.print(f"\n[bold]Session {session.short_id}[/]: {status_icon} {session.status.value}")
        console.print(f"  [dim]Task: {session.task[:60]}{'...' if len(session.task) > 60 else ''}[/]")
        console.print(f"  [dim]Turn: {session.turn} | Runtime: {session.runtime}[/]")

        if session.status.value == "completed":
            messages = manager.get_messages(session.id)
            for msg in reversed(messages):
                if msg.role == "assistant":
                    console.print(f"\n[bold]Response:[/]")
                    if len(msg.content) > 500:
                        console.print(msg.content[:500] + "...")
                    else:
                        console.print(msg.content)
                    break
        elif session.status.value == "failed":
            console.print(f"[red]Error:[/] {session.error or 'Unknown error'}")
        elif session.status.value == "running":
            console.print("[dim]Session is still running...[/]")
            console.print(f"  [dim]PID: {session.pid}[/]")

    def do_kill(session_id: str):
        """Kill a running session using CodexSessionManager (same as orchestrator)."""
        from zwarm.sessions import CodexSessionManager

        manager = CodexSessionManager(default_dir / ".zwarm")
        session = manager.get_session(session_id)

        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            return

        if not session.is_running:
            console.print(f"[yellow]Session {session.short_id} is not running ({session.status.value}).[/]")
            return

        try:
            killed = manager.kill_session(session.id)
            if killed:
                console.print(f"[green]✓[/] Stopped session {session.short_id}")
            else:
                console.print(f"[red]Failed to stop session[/]")
        except Exception as e:
            console.print(f"[red]Failed to stop session:[/] {e}")

    def do_killall():
        """Kill all running sessions using CodexSessionManager."""
        from zwarm.sessions import CodexSessionManager, SessionStatus as SessStatus

        manager = CodexSessionManager(default_dir / ".zwarm")
        running_sessions = manager.list_sessions(status=SessStatus.RUNNING)

        if not running_sessions:
            console.print("[dim]No running sessions to kill.[/]")
            return

        killed = 0
        for session in running_sessions:
            try:
                if manager.kill_session(session.id):
                    killed += 1
            except Exception as e:
                console.print(f"[red]Failed to stop {session.short_id}:[/] {e}")

        console.print(f"[green]✓[/] Killed {killed} sessions")

    def do_clean():
        """Remove old completed/failed sessions from disk."""
        from zwarm.sessions import CodexSessionManager

        manager = CodexSessionManager(default_dir / ".zwarm")
        cleaned = manager.cleanup_completed(keep_days=7)
        console.print(f"[green]✓[/] Cleaned {cleaned} old sessions")

    def do_delete(session_id: str):
        """Delete a session entirely (removes from disk and ls)."""
        from zwarm.sessions import CodexSessionManager

        manager = CodexSessionManager(default_dir / ".zwarm")
        session = manager.get_session(session_id)

        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            return

        if manager.delete_session(session.id):
            console.print(f"[green]✓[/] Deleted session {session.short_id}")
        else:
            console.print(f"[red]Failed to delete session[/]")

    # REPL loop
    import shlex

    while True:
        try:
            raw_input = console.input("[bold cyan]>[/] ").strip()
            if not raw_input:
                continue

            # Parse command
            try:
                parts = shlex.split(raw_input)
            except ValueError:
                parts = raw_input.split()

            cmd = parts[0].lower()
            args = parts[1:]

            if cmd in ("q", "quit", "exit"):
                active = [s for s in sessions.values() if s.status == SessionStatus.ACTIVE]
                if active:
                    console.print(f"  [yellow]Warning:[/] {len(active)} sessions still active")
                    console.print("  [dim]Use 'killall' first, or they'll continue in background[/]")

                # Cleanup adapters
                for adapter_instance in adapters_cache.values():
                    try:
                        asyncio.run(adapter_instance.cleanup())
                    except Exception:
                        pass

                console.print("\n[dim]Goodbye![/]\n")
                break

            elif cmd in ("h", "help"):
                show_help()

            elif cmd in ("ls", "list"):
                show_sessions()

            elif cmd == "spawn":
                do_spawn(args)

            elif cmd == "async":
                # Async spawn shorthand
                do_spawn(args + ["--async"])

            elif cmd == "orchestrate":
                do_orchestrate(args)

            elif cmd in ("?", "peek"):
                if not args:
                    console.print("  [red]Usage:[/] ? SESSION_ID")
                else:
                    do_peek(args[0])

            elif cmd in ("show", "check"):
                if not args:
                    console.print("  [red]Usage:[/] show SESSION_ID")
                else:
                    do_show(args[0])

            elif cmd in ("traj", "trajectory"):
                if not args:
                    console.print("  [red]Usage:[/] traj SESSION_ID [--full]")
                else:
                    full_mode = "--full" in args
                    session_arg = [a for a in args if a != "--full"]
                    if session_arg:
                        do_trajectory(session_arg[0], full=full_mode)
                    else:
                        console.print("  [red]Usage:[/] traj SESSION_ID [--full]")

            elif cmd in ("c", "continue"):
                # Sync continue - waits for response
                if len(args) < 2:
                    console.print("  [red]Usage:[/] c SESSION_ID \"message\"")
                else:
                    do_continue(args[0], " ".join(args[1:]), wait=True)

            elif cmd in ("ca", "async"):
                # Async continue - fire and forget
                if len(args) < 2:
                    console.print("  [red]Usage:[/] ca SESSION_ID \"message\"")
                    console.print("  [dim]Sends message and returns immediately (check with '?')[/]")
                else:
                    do_continue(args[0], " ".join(args[1:]), wait=False)

            elif cmd == "check":
                if not args:
                    console.print("  [red]Usage:[/] check SESSION_ID")
                else:
                    do_check(args[0])

            elif cmd == "kill":
                if not args:
                    console.print("  [red]Usage:[/] kill SESSION_ID")
                else:
                    do_kill(args[0])

            elif cmd == "killall":
                do_killall()

            elif cmd == "clean":
                do_clean()

            elif cmd in ("rm", "delete", "remove"):
                if not args:
                    console.print("  [red]Usage:[/] rm SESSION_ID")
                else:
                    do_delete(args[0])

            else:
                console.print(f"  [yellow]Unknown command:[/] {cmd}")
                console.print("  [dim]Type 'help' for available commands[/]")

        except KeyboardInterrupt:
            console.print("\n[dim](Ctrl+C to exit, or type 'quit')[/]")
        except EOFError:
            console.print("\n[dim]Goodbye![/]\n")
            break
        except Exception as e:
            console.print(f"  [red]Error:[/] {e}")


# =============================================================================
# Session Manager Commands (background Codex processes)
# =============================================================================

session_app = typer.Typer(
    name="session",
    help="""
[bold cyan]Codex Session Manager[/]

Manage background Codex sessions. Run multiple codex tasks in parallel,
monitor their progress, and inject follow-up messages.

[bold]COMMANDS[/]
    [cyan]start[/]    Start a new session in the background
    [cyan]ls[/]       List all sessions
    [cyan]show[/]     Show messages for a session
    [cyan]logs[/]     Show raw JSONL output
    [cyan]inject[/]   Inject a follow-up message
    [cyan]kill[/]     Kill a running session
    [cyan]clean[/]    Remove old completed sessions

[bold]EXAMPLES[/]
    [dim]# Start a background session[/]
    $ zwarm session start "Add tests for auth module"

    [dim]# List all sessions[/]
    $ zwarm session ls

    [dim]# View session messages[/]
    $ zwarm session show abc123

    [dim]# Continue a completed session[/]
    $ zwarm session inject abc123 "Also add edge case tests"
""",
)
app.add_typer(session_app, name="session")


@session_app.command("start")
def session_start(
    task: Annotated[str, typer.Argument(help="Task description")],
    working_dir: Annotated[Path, typer.Option("--dir", "-d", help="Working directory")] = Path("."),
    model: Annotated[str, typer.Option("--model", "-m", help="Model to use")] = "gpt-5.1-codex-mini",
):
    """
    Start a new Codex session in the background.

    The session runs independently and you can check on it later.

    [bold]Examples:[/]
        [dim]# Simple task[/]
        $ zwarm session start "Fix the bug in auth.py"

        [dim]# With specific model[/]
        $ zwarm session start "Refactor the API" --model gpt-5.1-codex-max
    """
    from zwarm.sessions import CodexSessionManager

    manager = CodexSessionManager(working_dir / ".zwarm")
    session = manager.start_session(
        task=task,
        working_dir=working_dir,
        model=model,
    )

    console.print()
    console.print(f"[green]✓ Session started[/]  [bold cyan]{session.short_id}[/]")
    console.print()
    console.print(f"  [dim]Task:[/]  {task[:70]}{'...' if len(task) > 70 else ''}")
    console.print(f"  [dim]Model:[/] {model}")
    console.print(f"  [dim]PID:[/]   {session.pid}")
    console.print()
    console.print("[dim]Commands:[/]")
    console.print(f"  [cyan]zwarm session ls[/]           [dim]List all sessions[/]")
    console.print(f"  [cyan]zwarm session show {session.short_id}[/]  [dim]View messages[/]")
    console.print(f"  [cyan]zwarm session logs {session.short_id} -f[/]  [dim]Follow live output[/]")


@session_app.command("ls")
def session_list(
    working_dir: Annotated[Path, typer.Option("--dir", "-d", help="Working directory")] = Path("."),
    all_sessions: Annotated[bool, typer.Option("--all", "-a", help="Show all sessions including completed")] = False,
    json_output: Annotated[bool, typer.Option("--json", help="Output as JSON")] = False,
):
    """
    List all sessions.

    Shows running sessions by default. Use --all to include completed.

    [bold]Examples:[/]
        $ zwarm session ls
        $ zwarm session ls --all
    """
    from zwarm.sessions import CodexSessionManager, SessionStatus

    manager = CodexSessionManager(working_dir / ".zwarm")
    sessions = manager.list_sessions()

    if not all_sessions:
        sessions = [s for s in sessions if s.status == SessionStatus.RUNNING]

    if json_output:
        import json
        console.print(json.dumps([s.to_dict() for s in sessions], indent=2))
        return

    if not sessions:
        if all_sessions:
            console.print("[dim]No sessions found.[/]")
        else:
            console.print("[dim]No running sessions.[/]")
            console.print("[dim]Use --all to see completed sessions, or start one with:[/]")
            console.print("  zwarm session start \"your task here\"")
        return

    # Show status summary
    running_count = sum(1 for s in sessions if s.status == SessionStatus.RUNNING)
    completed_count = sum(1 for s in sessions if s.status == SessionStatus.COMPLETED)
    failed_count = sum(1 for s in sessions if s.status == SessionStatus.FAILED)

    summary_parts = []
    if running_count:
        summary_parts.append(f"[yellow]⟳ {running_count} running[/]")
    if completed_count:
        summary_parts.append(f"[green]✓ {completed_count} completed[/]")
    if failed_count:
        summary_parts.append(f"[red]✗ {failed_count} failed[/]")

    if summary_parts:
        console.print(" │ ".join(summary_parts))
        console.print()

    # Build table
    table = Table(box=None, show_header=True, header_style="bold dim")
    table.add_column("ID", style="cyan")
    table.add_column("", width=2)  # Status icon
    table.add_column("Task", max_width=50)
    table.add_column("Runtime", justify="right", style="dim")
    table.add_column("Tokens", justify="right", style="dim")

    status_icons = {
        SessionStatus.RUNNING: "[yellow]⟳[/]",
        SessionStatus.COMPLETED: "[green]✓[/]",
        SessionStatus.FAILED: "[red]✗[/]",
        SessionStatus.KILLED: "[dim]⊘[/]",
        SessionStatus.PENDING: "[dim]○[/]",
    }

    for session in sessions:
        status_icon = status_icons.get(session.status, "?")
        task_preview = session.task[:47] + "..." if len(session.task) > 50 else session.task
        tokens = session.token_usage.get("total_tokens", 0)
        tokens_str = f"{tokens:,}" if tokens else "-"

        table.add_row(
            session.short_id,
            status_icon,
            task_preview,
            session.runtime,
            tokens_str,
        )

    console.print()
    console.print(table)
    console.print()


@session_app.command("show")
def session_show(
    session_id: Annotated[str, typer.Argument(help="Session ID (or prefix)")],
    working_dir: Annotated[Path, typer.Option("--dir", "-d", help="Working directory")] = Path("."),
    raw: Annotated[bool, typer.Option("--raw", "-r", help="Show raw messages without formatting")] = False,
):
    """
    Show messages for a session.

    Displays the conversation history with nice formatting.

    [bold]Examples:[/]
        $ zwarm session show abc123
        $ zwarm session show abc123 --raw
    """
    from zwarm.sessions import CodexSessionManager

    manager = CodexSessionManager(working_dir / ".zwarm")
    session = manager.get_session(session_id)

    if not session:
        console.print(f"[red]Session not found:[/] {session_id}")
        raise typer.Exit(1)

    # Get messages
    messages = manager.get_messages(session.id)

    # Status styling
    status_display = {
        "running": "[yellow]⟳ running[/]",
        "completed": "[green]✓ completed[/]",
        "failed": "[red]✗ failed[/]",
        "killed": "[dim]⊘ killed[/]",
        "pending": "[dim]○ pending[/]",
    }.get(session.status.value, session.status.value)

    console.print()
    console.print(f"[bold cyan]Session {session.short_id}[/]  {status_display}")
    console.print(f"[dim]Task:[/] {session.task}")
    console.print(f"[dim]Model:[/] {session.model}  [dim]│[/]  [dim]Turn:[/] {session.turn}  [dim]│[/]  [dim]Runtime:[/] {session.runtime}")
    console.print()

    if not messages:
        if session.status.value == "running":
            console.print("[yellow]Session is still running...[/]")
            console.print("[dim]Check back later for output.[/]")
        else:
            console.print("[dim]No messages captured.[/]")
        return

    # Display messages
    for msg in messages:
        if msg.role == "user":
            if raw:
                console.print(f"[bold blue]USER:[/] {msg.content}")
            else:
                console.print(Panel(msg.content, title="[bold blue]User[/]", border_style="blue"))

        elif msg.role == "assistant":
            if raw:
                console.print(f"[bold green]ASSISTANT:[/] {msg.content}")
            else:
                # Truncate very long messages
                content = msg.content
                if len(content) > 2000:
                    content = content[:2000] + "\n\n[dim]... (truncated, use --raw for full output)[/]"
                console.print(Panel(content, title="[bold green]Assistant[/]", border_style="green"))

        elif msg.role == "tool":
            if raw:
                console.print(f"[dim]TOOL: {msg.content}[/]")
            else:
                # Extract function name if present
                content = msg.content
                if content.startswith("[Calling:"):
                    console.print(f"  [dim]⚙[/] {content}")
                elif content.startswith("[Output]"):
                    console.print(f"    [dim]└─ {content[9:]}[/]")  # Skip "[Output]:"
                else:
                    console.print(f"  [dim]{content}[/]")

    console.print()

    # Show token usage
    if session.token_usage:
        tokens = session.token_usage
        console.print(f"[dim]Tokens: {tokens.get('input_tokens', 0):,} in / {tokens.get('output_tokens', 0):,} out[/]")

    # Show error if any
    if session.error:
        console.print(f"[red]Error:[/] {session.error}")

    # Helpful tip
    console.print()
    if session.status.value == "running":
        console.print(f"[dim]Tip: Use 'zwarm session logs {session.short_id} --follow' to watch live output[/]")
    elif session.status.value == "completed":
        console.print(f"[dim]Tip: Use 'zwarm session inject {session.short_id} \"your message\"' to continue the conversation[/]")


@session_app.command("logs")
def session_logs(
    session_id: Annotated[str, typer.Argument(help="Session ID (or prefix)")],
    working_dir: Annotated[Path, typer.Option("--dir", "-d", help="Working directory")] = Path("."),
    turn: Annotated[Optional[int], typer.Option("--turn", "-t", help="Specific turn number")] = None,
    follow: Annotated[bool, typer.Option("--follow", "-f", help="Follow output (like tail -f)")] = False,
):
    """
    Show raw JSONL logs for a session.

    [bold]Examples:[/]
        $ zwarm session logs abc123
        $ zwarm session logs abc123 --follow
    """
    from zwarm.sessions import CodexSessionManager

    manager = CodexSessionManager(working_dir / ".zwarm")
    session = manager.get_session(session_id)

    if not session:
        console.print(f"[red]Session not found:[/] {session_id}")
        raise typer.Exit(1)

    if follow and session.status.value == "running":
        # Follow mode - tail the file
        import time
        output_path = manager._output_path(session.id, turn or session.turn)

        console.print(f"[dim]Following {output_path}... (Ctrl+C to stop)[/]")
        console.print()

        try:
            with open(output_path, "r") as f:
                # Print existing content
                for line in f:
                    console.print(line.rstrip())

                # Follow new content
                while session.is_running:
                    line = f.readline()
                    if line:
                        console.print(line.rstrip())
                    else:
                        time.sleep(0.5)
                        # Refresh session status
                        session = manager.get_session(session_id)

        except KeyboardInterrupt:
            console.print("\n[dim]Stopped following.[/]")

    else:
        # Just print the output
        output = manager.get_output(session.id, turn)
        if output:
            console.print(output)
        else:
            console.print("[dim]No output yet.[/]")


@session_app.command("inject")
def session_inject(
    session_id: Annotated[str, typer.Argument(help="Session ID (or prefix)")],
    message: Annotated[str, typer.Argument(help="Follow-up message to inject")],
    working_dir: Annotated[Path, typer.Option("--dir", "-d", help="Working directory")] = Path("."),
):
    """
    Inject a follow-up message into a completed session.

    This continues the conversation with context from the previous turn.
    Can only be used on completed (not running) sessions.

    [bold]Examples:[/]
        $ zwarm session inject abc123 "Also add edge case tests"
        $ zwarm session inject abc123 "Good, now refactor the code"
    """
    from zwarm.sessions import CodexSessionManager, SessionStatus

    manager = CodexSessionManager(working_dir / ".zwarm")
    session = manager.get_session(session_id)

    if not session:
        console.print(f"[red]Session not found:[/] {session_id}")
        raise typer.Exit(1)

    if session.status == SessionStatus.RUNNING:
        console.print("[yellow]Session is still running.[/]")
        console.print("[dim]Wait for it to complete, then inject a follow-up.[/]")
        raise typer.Exit(1)

    # Inject the message
    updated_session = manager.inject_message(session.id, message)

    if not updated_session:
        console.print("[red]Failed to inject message.[/]")
        raise typer.Exit(1)

    console.print()
    console.print(f"[green]✓ Message injected[/]  Turn {updated_session.turn} started")
    console.print()
    console.print(f"  [dim]Message:[/] {message[:70]}{'...' if len(message) > 70 else ''}")
    console.print(f"  [dim]PID:[/]     {updated_session.pid}")
    console.print()
    console.print("[dim]Commands:[/]")
    console.print(f"  [cyan]zwarm session show {session.short_id}[/]  [dim]View messages[/]")
    console.print(f"  [cyan]zwarm session logs {session.short_id} -f[/]  [dim]Follow live output[/]")


@session_app.command("kill")
def session_kill(
    session_id: Annotated[str, typer.Argument(help="Session ID (or prefix)")],
    working_dir: Annotated[Path, typer.Option("--dir", "-d", help="Working directory")] = Path("."),
):
    """
    Kill a running session.

    [bold]Examples:[/]
        $ zwarm session kill abc123
    """
    from zwarm.sessions import CodexSessionManager

    manager = CodexSessionManager(working_dir / ".zwarm")
    session = manager.get_session(session_id)

    if not session:
        console.print(f"[red]Session not found:[/] {session_id}")
        raise typer.Exit(1)

    if not session.is_running:
        console.print(f"[yellow]Session {session.short_id} is not running.[/]")
        console.print(f"  [dim]Status:[/] {session.status.value}")
        return

    killed = manager.kill_session(session.id)

    if killed:
        console.print(f"[green]Killed session {session.short_id}[/]")
    else:
        console.print(f"[red]Failed to kill session {session.short_id}[/]")


@session_app.command("clean")
def session_clean(
    working_dir: Annotated[Path, typer.Option("--dir", "-d", help="Working directory")] = Path("."),
    keep_days: Annotated[int, typer.Option("--keep-days", "-k", help="Keep sessions newer than N days")] = 7,
    yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation")] = False,
):
    """
    Remove old completed sessions.

    [bold]Examples:[/]
        $ zwarm session clean
        $ zwarm session clean --keep-days 1
    """
    from zwarm.sessions import CodexSessionManager, SessionStatus

    manager = CodexSessionManager(working_dir / ".zwarm")
    sessions = manager.list_sessions()

    # Count cleanable sessions
    cleanable = [s for s in sessions if s.status in (SessionStatus.COMPLETED, SessionStatus.FAILED, SessionStatus.KILLED)]

    if not cleanable:
        console.print("[dim]No sessions to clean.[/]")
        return

    console.print(f"Found {len(cleanable)} completed/failed sessions.")

    if not yes:
        confirm = typer.confirm(f"Remove sessions older than {keep_days} days?")
        if not confirm:
            console.print("[dim]Cancelled.[/]")
            return

    cleaned = manager.cleanup_completed(keep_days)
    console.print(f"[green]Cleaned {cleaned} sessions.[/]")


# =============================================================================
# Main callback and entry point
# =============================================================================

def _get_version() -> str:
    """Get version from package metadata."""
    try:
        from importlib.metadata import version as get_pkg_version
        return get_pkg_version("zwarm")
    except Exception:
        return "0.0.0"


@app.callback(invoke_without_command=True)
def main_callback(
    ctx: typer.Context,
    version: Annotated[bool, typer.Option("--version", "-V", help="Show version")] = False,
):
    """Main callback for version flag."""
    if version:
        console.print(f"[bold cyan]zwarm[/] version [green]{_get_version()}[/]")
        raise typer.Exit()


def main():
    """Entry point for the CLI."""
    app()


if __name__ == "__main__":
    main()
