"""caprail route:list"""
from __future__ import annotations
import sys
from pathlib import Path
import typer
from rich.console import Console
from rich.table import Table

console = Console()

def command() -> None:
    """List all registered routes."""
    sys.path.insert(0, str(Path.cwd()))
    try:
        import importlib
        mod = importlib.import_module("bootstrap.app")
    except ImportError:
        console.print("[red]Could not load bootstrap/app.py[/]")
        raise typer.Exit(1)

    app_obj = getattr(mod, "app", None)
    if app_obj is None:
        console.print("[red]No 'app' object found in bootstrap/app.py[/]")
        raise typer.Exit(1)

    router = app_obj.router
    table = Table(title="Routes")
    table.add_column("Method", style="bold cyan")
    table.add_column("Path", style="green")
    table.add_column("Name", style="yellow")
    table.add_column("Middleware")

    for route in router.routes:
        methods = "|".join(m for m in route.methods if m != "HEAD")
        table.add_row(methods, route.path, route.name or "", ", ".join(route.middleware))

    console.print(table)
