"""CLI commands for flowly — main app definition and command registration."""

import asyncio
import platform

import typer
from rich.console import Console

from flowly import __version__, __logo__

# Windows needs SelectorEventLoop for uvicorn/aiohttp compatibility
if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

app = typer.Typer(
    name="flowly",
    help=f"{__logo__} flowly - Personal AI Assistant",
    no_args_is_help=True,
)

console = Console()


def version_callback(value: bool):
    if value:
        console.print(f"{__logo__} flowly v{__version__}")
        raise typer.Exit()


@app.callback()
def main(
    version: bool = typer.Option(
        None, "--version", "-v", callback=version_callback, is_eager=True
    ),
):
    """flowly - Personal AI Assistant."""
    pass


# ── Register command groups from sub-modules ──────────────────────

from flowly.cli.setup_cmd import setup_app
app.add_typer(setup_app, name="setup")

from flowly.cli.persona_cmd import persona_app
app.add_typer(persona_app, name="persona")

from flowly.cli.service_cmd import service_app
app.add_typer(service_app, name="service")

from flowly.cli.channels_cmd import channels_app
app.add_typer(channels_app, name="channels")

from flowly.cli.cron_cmd import cron_app
app.add_typer(cron_app, name="cron")

from flowly.cli.skills_cmd import skills_app
app.add_typer(skills_app, name="skills")

from flowly.cli.approvals_cmd import approvals_app, sessions_app
app.add_typer(approvals_app, name="approvals")
app.add_typer(sessions_app, name="sessions")

from flowly.cli.pairing_cmd import pairing_app
app.add_typer(pairing_app, name="pairing")


# ── Standalone commands (registered directly on app) ──────────────

from flowly.cli.onboard_cmd import onboard
app.command("onboard")(onboard)

from flowly.cli.gateway_cmd import gateway
app.command("gateway")(gateway)

from flowly.cli.agent_cmd import agent
app.command("agent")(agent)


@app.command()
def doctor(
    fix: bool = typer.Option(False, "--fix", "-f", help="Auto-repair fixable issues"),
):
    """Check configuration and runtime health. Use --fix to auto-repair."""
    from flowly.cli.doctor import run_doctor
    raise typer.Exit(run_doctor(fix=fix))


@app.command()
def status():
    """Show flowly status."""
    from flowly.config.loader import load_config, get_config_path
    from flowly.utils.helpers import get_workspace_path

    config_path = get_config_path()
    workspace = get_workspace_path()

    console.print(f"{__logo__} Nanobot Status\n")

    console.print(f"Config: {config_path} {'[green]✓[/green]' if config_path.exists() else '[red]✗[/red]'}")
    console.print(f"Workspace: {workspace} {'[green]✓[/green]' if workspace.exists() else '[red]✗[/red]'}")

    if config_path.exists():
        config = load_config()
        console.print(f"Model: {config.agents.defaults.model}")

        has_openrouter = bool(config.providers.openrouter.api_key)
        has_anthropic = bool(config.providers.anthropic.api_key)
        has_openai = bool(config.providers.openai.api_key)
        has_gemini = bool(config.providers.gemini.api_key)
        has_vllm = bool(config.providers.vllm.api_base)

        console.print(f"OpenRouter API: {'[green]✓[/green]' if has_openrouter else '[dim]not set[/dim]'}")
        console.print(f"Anthropic API: {'[green]✓[/green]' if has_anthropic else '[dim]not set[/dim]'}")
        console.print(f"OpenAI API: {'[green]✓[/green]' if has_openai else '[dim]not set[/dim]'}")
        console.print(f"Gemini API: {'[green]✓[/green]' if has_gemini else '[dim]not set[/dim]'}")
        vllm_status = f"[green]✓ {config.providers.vllm.api_base}[/green]" if has_vllm else "[dim]not set[/dim]"
        console.print(f"vLLM/Local: {vllm_status}")


if __name__ == "__main__":
    app()
