"""caprail serve"""
from __future__ import annotations
import sys
from pathlib import Path
import typer
from rich.console import Console

console = Console()

def command(
    host: str = typer.Option("127.0.0.1", "--host", "-H", help="Bind address"),
    port: int = typer.Option(8000, "--port", "-p", help="Port to listen on"),
    reload: bool = typer.Option(True, "--reload/--no-reload", help="Enable auto-reload"),
    workers: int = typer.Option(1, "--workers", "-w", help="Number of worker processes"),
) -> None:
    """Start the Caprail development server."""
    import uvicorn

    sys.path.insert(0, str(Path.cwd()))

    # Try to find the ASGI app
    app_module = _find_asgi_app()

    console.print(f"[bold green]Caprail[/] development server started")
    console.print(f"  [cyan]http://{host}:{port}[/]")
    console.print("  Press [bold]Ctrl+C[/] to stop.\n")

    uvicorn.run(
        app_module,
        host=host,
        port=port,
        reload=reload,
        workers=workers if not reload else 1,
        log_level="info",
    )

def _find_asgi_app() -> str:
    candidates = [
        "bootstrap.app:application",
        "app:application",
        "main:application",
        "asgi:application",
    ]
    for candidate in candidates:
        module, _, attr = candidate.partition(":")
        try:
            import importlib
            mod = importlib.import_module(module)
            if hasattr(mod, attr):
                return candidate
        except ImportError:
            continue
    return "bootstrap.app:application"
