"""
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}")

    try:
        executor = get_adapter(adapter.value, model=model)
    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 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_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_adapter: Annotated[AdapterType, typer.Option("--adapter", "-a", help="Default executor adapter")] = AdapterType.codex_mcp,
    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,
    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 (Codex, Claude Code) across different directories,
    manage them interactively, and view their outputs. You are the orchestrator.

    [bold]Commands:[/]
        [cyan]spawn[/] "task" [opts]      Start a session (see spawn --help)
        [cyan]ls[/] / [cyan]list[/]               Dashboard of all sessions
        [cyan]?[/] / [cyan]check[/] ID            Check session status & response
        [cyan]c[/] / [cyan]converse[/] ID "msg"   Continue sync conversation
        [cyan]view[/] ID                  Open session output in $EDITOR
        [cyan]kill[/] ID                  Stop a session
        [cyan]killall[/]                  Stop all running sessions
        [cyan]refresh[/]                  Poll all async sessions
        [cyan]q[/] / [cyan]quit[/]                Exit

    [bold]Spawn Options:[/]
        spawn "task" --dir ~/project --adapter claude_code --async

    [bold]Examples:[/]
        $ zwarm interactive
        > spawn "Build auth module" --dir ~/api --async
        > spawn "Fix tests" --dir ~/api --async
        > spawn "Add docs" --dir ~/docs
        > ls
        > ? abc123
        > view abc123
    """
    from zwarm.adapters import get_adapter, list_adapters
    from zwarm.core.models import ConversationSession
    import argparse
    import tempfile
    import subprocess as sp

    console.print("\n[bold cyan]zwarm interactive[/] - Universal Multi-Agent CLI\n")
    console.print(f"  Default adapter: [cyan]{default_adapter.value}[/]")
    console.print(f"  Default dir: {default_dir.absolute()}")
    console.print(f"  Available adapters: {', '.join(list_adapters())}")
    console.print("\n  Type [cyan]help[/] for commands, [cyan]quit[/] to exit.\n")

    # Adapter cache (lazy-loaded per adapter type)
    adapters: dict[str, Any] = {}

    def get_or_create_adapter(adapter_name: str, adapter_model: str | None = None) -> Any:
        """Get cached adapter or create new one."""
        key = f"{adapter_name}:{adapter_model or 'default'}"
        if key not in adapters:
            adapters[key] = get_adapter(adapter_name, model=adapter_model)
        return adapters[key]

    # Session tracking with metadata
    sessions: dict[str, ConversationSession] = {}
    session_dirs: dict[str, Path] = {}  # session_id -> working_dir
    session_adapters: dict[str, str] = {}  # session_id -> adapter_name

    # Persistence directory
    interactive_state_dir = state_dir / "interactive"
    interactive_state_dir.mkdir(parents=True, exist_ok=True)

    def short_id(session_id: str) -> str:
        """Get short display ID."""
        return session_id[:8]

    def find_session(query: str) -> tuple[ConversationSession | None, str | None]:
        """Find session by full or partial ID. Returns (session, full_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

    def save_session_output(session: ConversationSession) -> Path:
        """Save session output to file for viewing."""
        session_dir = interactive_state_dir / short_id(session.id)
        session_dir.mkdir(exist_ok=True)

        output_file = session_dir / "output.txt"
        with open(output_file, "w") as f:
            f.write(f"Session: {session.id}\n")
            f.write(f"Task: {session.task_description}\n")
            f.write(f"Adapter: {session.adapter}\n")
            f.write(f"Model: {session.model}\n")
            f.write(f"Status: {session.status.value}\n")
            f.write(f"Mode: {session.mode.value}\n")
            f.write(f"Working Dir: {session.working_dir}\n")
            f.write(f"Tokens: {session.token_usage}\n")
            f.write("\n" + "="*60 + "\n\n")

            for msg in session.messages:
                f.write(f"[{msg.role.upper()}]\n")
                f.write(msg.content)
                f.write("\n\n" + "-"*40 + "\n\n")

        return output_file

    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 new session")
        help_table.add_row("  --dir PATH", "Working directory for this session")
        help_table.add_row("  --adapter NAME", f"Adapter ({', '.join(list_adapters())})")
        help_table.add_row("  --async / -a", "Fire-and-forget mode")
        help_table.add_row("  --model NAME", "Model override")
        help_table.add_row("", "")
        help_table.add_row("ls / list", "Dashboard of all sessions")
        help_table.add_row("? / check ID", "Check session status & messages")
        help_table.add_row("c / converse ID \"msg\"", "Continue sync conversation")
        help_table.add_row("view ID", "Open session output in $EDITOR")
        help_table.add_row("raw ID", "Show raw session JSON")
        help_table.add_row("kill ID", "Stop a session")
        help_table.add_row("killall", "Stop all running sessions")
        help_table.add_row("refresh", "Poll all async sessions for updates")
        help_table.add_row("q / quit", "Exit interactive mode")
        console.print(help_table)

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

        table = Table(title="Sessions Dashboard", show_header=True)
        table.add_column("ID", style="cyan", width=10)
        table.add_column("Status", width=12)
        table.add_column("Adapter", width=12)
        table.add_column("Dir", width=20)
        table.add_column("Tokens", width=8, justify="right")
        table.add_column("Task", width=35)

        for sid, s in sessions.items():
            status_icons = {
                "active": "[green]● active[/]",
                "completed": "[dim]✓ done[/]",
                "failed": "[red]✗ failed[/]",
            }
            status = status_icons.get(s.status.value, f"? {s.status.value}")

            # Add mode indicator
            if s.mode.value == "async" and s.status.value == "active":
                status = "[yellow]⟳ running[/]"

            work_dir = session_dirs.get(sid, s.working_dir)
            dir_display = str(work_dir.name) if work_dir else "."

            table.add_row(
                short_id(sid),
                status,
                s.adapter,
                dir_display,
                str(s.token_usage.get("total_tokens", 0)),
                s.task_description[:32] + "..." if len(s.task_description) > 32 else s.task_description,
            )

        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("--adapter", default=None)
        parser.add_argument("--model", "-m", default=None)
        parser.add_argument("--async", "-a", dest="is_async", action="store_true")

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

    def do_spawn(args: list[str]):
        """Spawn a new session with optional per-session config."""
        parsed = parse_spawn_args(args)

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

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

        task = parsed["task"]
        work_dir = (parsed["dir"] or default_dir).absolute()
        adapter_name = parsed["adapter"] or default_adapter.value
        adapter_model = parsed["model"] or model
        mode = "async" if parsed["is_async"] else "sync"

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

        console.print(f"\n[dim]Spawning {mode} session...[/]")
        console.print(f"  [dim]Dir: {work_dir}[/]")
        console.print(f"  [dim]Adapter: {adapter_name}[/]")

        try:
            executor = get_or_create_adapter(adapter_name, adapter_model)
            session = asyncio.run(
                executor.start_session(
                    task=task,
                    working_dir=work_dir,
                    mode=mode,
                    model=adapter_model,
                )
            )

            sessions[session.id] = session
            session_dirs[session.id] = work_dir
            session_adapters[session.id] = adapter_name

            console.print(f"  [green]✓[/] Session: [cyan]{short_id(session.id)}[/]")
            console.print(f"  Tokens: {session.token_usage.get('total_tokens', 0)}")

            if mode == "sync" and session.messages:
                for msg in session.messages:
                    if msg.role == "assistant":
                        console.print(f"\n[bold]Response:[/]")
                        content = msg.content[:2000] + ("..." if len(msg.content) > 2000 else "")
                        console.print(Panel(content, border_style="green"))
            else:
                console.print(f"  [dim]Async session started. Use '? {short_id(session.id)}' to check status.[/]")

            # Save output for viewing
            save_session_output(session)

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

    def do_converse(session_id: str, message: str):
        session, sid = find_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.mode.value != "sync":
            console.print(f"  [yellow]Warning:[/] Session is async, can't converse")
            return

        if session.status.value != "active":
            console.print(f"  [yellow]Warning:[/] Session is {session.status.value}")
            return

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

        try:
            adapter_name = session_adapters.get(sid, default_adapter.value)
            executor = get_or_create_adapter(adapter_name)
            response = asyncio.run(executor.send_message(session, message))
            console.print(f"  [green]✓[/] Response received")
            console.print(f"  Tokens: {session.token_usage.get('total_tokens', 0)}")
            console.print(f"\n[bold]Response:[/]")
            console.print(Panel(response[:2000] + ("..." if len(response) > 2000 else ""), border_style="green"))

            # Update saved output
            save_session_output(session)

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

    def do_check(session_id: str):
        session, sid = find_session(session_id)
        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            return

        work_dir = session_dirs.get(sid, session.working_dir)

        console.print(f"\n[bold]Session {short_id(session.id)}[/]")
        console.print(f"  Status: {session.status.value}")
        console.print(f"  Mode: {session.mode.value}")
        console.print(f"  Adapter: {session.adapter}")
        console.print(f"  Model: {session.model}")
        console.print(f"  Directory: {work_dir}")
        console.print(f"  Messages: {len(session.messages)}")
        console.print(f"  Tokens: {session.token_usage}")
        console.print(f"  Task: {session.task_description}")

        if session.mode.value == "async" and session.status.value == "active":
            try:
                adapter_name = session_adapters.get(sid, default_adapter.value)
                executor = get_or_create_adapter(adapter_name)
                status = asyncio.run(executor.check_status(session))
                console.print(f"\n[bold]Async status:[/]")
                for k, v in status.items():
                    if k != "events":  # Skip verbose events
                        val_str = str(v)[:200] + "..." if len(str(v)) > 200 else str(v)
                        console.print(f"  {k}: {val_str}")

                # Update saved output after status check
                save_session_output(session)

            except Exception as e:
                console.print(f"  [red]Status check error:[/] {e}")

        # Show messages
        if session.messages:
            console.print(f"\n[bold]Messages:[/]")
            for i, msg in enumerate(session.messages):
                role_color = {"user": "blue", "assistant": "green", "system": "yellow"}.get(msg.role, "white")
                content_preview = msg.content[:500] + "..." if len(msg.content) > 500 else msg.content
                console.print(f"  [{role_color}]{msg.role}[/]: {content_preview}")

    def do_view(session_id: str):
        """Open session output in $EDITOR."""
        session, sid = find_session(session_id)
        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            return

        output_file = save_session_output(session)
        editor = os.environ.get("EDITOR", "less")

        console.print(f"  [dim]Opening {output_file} in {editor}...[/]")
        try:
            sp.run([editor, str(output_file)])
        except Exception as e:
            console.print(f"  [red]Error opening editor:[/] {e}")
            console.print(f"  [dim]File saved at: {output_file}[/]")

    def do_raw(session_id: str):
        """Show raw session data for debugging."""
        session, _ = find_session(session_id)
        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            return

        import json
        console.print(f"\n[bold]Raw session data for {short_id(session.id)}:[/]")
        console.print(json.dumps(session.to_dict(), indent=2, default=str))

    def do_kill(session_id: str):
        session, sid = find_session(session_id)
        if not session:
            console.print(f"  [red]Session not found:[/] {session_id}")
            return

        try:
            adapter_name = session_adapters.get(sid, default_adapter.value)
            executor = get_or_create_adapter(adapter_name)
            asyncio.run(executor.stop(session))
            console.print(f"  [green]✓[/] Session {short_id(session.id)} killed")
            save_session_output(session)
        except Exception as e:
            console.print(f"  [red]Error:[/] {e}")

    def do_killall():
        """Kill all running sessions."""
        killed = 0
        for sid, session in sessions.items():
            if session.status.value == "active":
                try:
                    adapter_name = session_adapters.get(sid, default_adapter.value)
                    executor = get_or_create_adapter(adapter_name)
                    asyncio.run(executor.stop(session))
                    killed += 1
                except Exception:
                    pass
        console.print(f"  [green]✓[/] Killed {killed} sessions")

    def do_refresh():
        """Poll all async sessions for status updates."""
        updated = 0
        for sid, session in sessions.items():
            if session.mode.value == "async" and session.status.value == "active":
                try:
                    adapter_name = session_adapters.get(sid, default_adapter.value)
                    executor = get_or_create_adapter(adapter_name)
                    status = asyncio.run(executor.check_status(session))
                    save_session_output(session)
                    updated += 1

                    if status.get("status") in ("completed", "failed"):
                        icon = "[green]✓[/]" if status["status"] == "completed" else "[red]✗[/]"
                        console.print(f"  {icon} {short_id(sid)}: {status['status']}")
                except Exception as e:
                    console.print(f"  [red]✗[/] {short_id(sid)}: {e}")

        if updated == 0:
            console.print("  [dim]No async sessions to refresh[/]")
        else:
            console.print(f"  [dim]Refreshed {updated} sessions[/]")

    # 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:
                # Handle unclosed quotes
                parts = raw_input.split()

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

            if cmd in ("q", "quit", "exit"):
                # Offer to kill running sessions
                running = [s for s in sessions.values() if s.status.value == "active"]
                if running:
                    console.print(f"  [yellow]Warning:[/] {len(running)} sessions still running")
                    console.print("  [dim]Use 'killall' first, or they'll continue in background[/]")
                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)

            # Keep old shortcuts for convenience
            elif cmd in ("d", "delegate"):
                if not args:
                    console.print("  [red]Usage:[/] d \"task\" or spawn \"task\" [options]")
                else:
                    do_spawn(args)  # Sync by default

            elif cmd in ("a", "async"):
                if not args:
                    console.print("  [red]Usage:[/] a \"task\" or spawn \"task\" --async")
                else:
                    do_spawn(args + ["--async"])

            elif cmd in ("c", "converse"):
                if len(args) < 2:
                    console.print("  [red]Usage:[/] c SESSION_ID \"message\"")
                else:
                    do_converse(args[0], " ".join(args[1:]))

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

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

            elif cmd == "raw":
                if not args:
                    console.print("  [red]Usage:[/] raw SESSION_ID")
                else:
                    do_raw(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 == "refresh":
                do_refresh()

            elif cmd in ("e", "end"):
                # Alias for kill
                if not args:
                    console.print("  [red]Usage:[/] kill SESSION_ID")
                else:
                    do_kill(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}")


@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("[bold cyan]zwarm[/] version [green]0.1.0[/]")
        raise typer.Exit()


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


if __name__ == "__main__":
    main()
