"""CLI for Mercury Launcher."""

import asyncio
from pathlib import Path
from typing import Optional

import click

from mercury_launcher.config import add_agent_to_config, load_config
from mercury_launcher.daemon import Daemon
from mercury_launcher.discover import discover_agents
from mercury_launcher.log import setup_logging
from mercury_launcher.models import AgentConfig


def _run_discovery_and_select(agents: list[AgentConfig]) -> list[AgentConfig]:
    """Discover agents, show org selector, return filtered agent configs."""
    click.echo("\nDiscovering agents...")
    orgs = asyncio.run(discover_agents(agents))

    if not orgs:
        click.echo("Could not reach any agents. Starting all configured agents.")
        return agents

    # Build choices for questionary checkbox
    try:
        import questionary
    except ImportError:
        click.echo("questionary not installed — skipping org selector, starting all agents.")
        return agents

    choices = []
    for org_id, org_info in orgs.items():
        agent_names = [a.context.name or a.config.name for a in org_info.agents]
        label = f"{org_info.org_name} ({len(org_info.agents)} agent{'s' if len(org_info.agents) != 1 else ''}: {', '.join(agent_names)})"
        choices.append(questionary.Choice(title=label, value=org_id, checked=True))

    if len(choices) == 1:
        # Only one org — no need to prompt
        click.echo()
        selected_org_ids = [choices[0].value]
    else:
        click.echo()
        selected_org_ids = questionary.checkbox(
            "Select organizations to activate:",
            choices=choices,
        ).ask()

        if selected_org_ids is None:
            # User cancelled (Ctrl+C)
            raise SystemExit(0)

        if not selected_org_ids:
            click.echo("No organizations selected.")
            raise SystemExit(0)

    # Collect agent configs from selected orgs
    selected_configs = []
    for org_id in selected_org_ids:
        for discovered in orgs[org_id].agents:
            selected_configs.append(discovered.config)

    total = sum(len(o.agents) for o in orgs.values())
    if len(selected_configs) < total:
        click.echo(f"\nStarting {len(selected_configs)} of {total} agents...\n")
    else:
        click.echo(f"\nStarting {len(selected_configs)} agents...\n")

    return selected_configs


@click.group()
def main() -> None:
    """Mercury Launcher — spawn Claude Code sessions for Mercury agents."""
    pass


@main.command()
@click.option("-c", "--config", "config_path", type=click.Path(exists=True, path_type=Path), default=None, help="Path to launcher.yaml")
@click.option("--all", "start_all", is_flag=True, default=False, help="Skip org selector and start all agents")
def start(config_path: Optional[Path], start_all: bool) -> None:
    """Start the launcher daemon."""
    config = load_config(config_path)

    if not config.agents:
        click.echo("No agents configured. Use 'mercury-launcher add-agent' or create a launcher.yaml file.")
        raise SystemExit(1)

    setup_logging(level=config.log_level, log_dir=config.log_dir)

    if start_all:
        selected_agents = config.agents
    else:
        selected_agents = _run_discovery_and_select(config.agents)

    daemon = Daemon(config, agents=selected_agents)
    asyncio.run(daemon.run())


@main.command("add-agent")
@click.option("--name", required=True, help="Agent display name")
@click.option("--api-key", required=True, help="MCP API key (mcp_...)")
@click.option("--working-dir", required=True, type=click.Path(path_type=Path), help="Working directory for Claude Code sessions")
@click.option("--mercury-url", default=None, help="Mercury MCP endpoint URL")
@click.option("-c", "--config", "config_path", type=click.Path(path_type=Path), default=Path("launcher.yaml"), help="Config file path")
def add_agent(name: str, api_key: str, working_dir: Path, mercury_url: Optional[str], config_path: Path) -> None:
    """Add an agent to the launcher config."""
    add_agent_to_config(
        config_path=config_path,
        name=name,
        api_key=api_key,
        working_dir=str(working_dir.expanduser()),
        mercury_url=mercury_url,
    )
    click.echo(f"Added agent '{name}' to {config_path}")


@main.command()
@click.option("-c", "--config", "config_path", type=click.Path(exists=True, path_type=Path), default=None, help="Path to launcher.yaml")
def status(config_path: Optional[Path]) -> None:
    """Show configured agents."""
    config = load_config(config_path)

    if not config.agents:
        click.echo("No agents configured.")
        return

    click.echo(f"Configured agents ({len(config.agents)}):\n")
    for agent in config.agents:
        key_preview = agent.mcp_api_key[:8] + "..." if len(agent.mcp_api_key) > 8 else "***"
        click.echo(f"  {agent.name}")
        click.echo(f"    API key:   {key_preview}")
        click.echo(f"    Directory: {agent.working_directory}")
        click.echo(f"    Mercury:   {agent.mercury_url}")
        click.echo()


if __name__ == "__main__":
    main()
