"""CLI entry point for Robot Resources."""

import click

from robot_resources.cli.commands.report import report
from robot_resources.cli.commands.update_pricing import update_pricing


@click.group()
@click.version_option(package_name="robot-resources-router")
def cli() -> None:
    """Robot Resources - Intelligent LLM cost optimization."""
    pass


cli.add_command(report)
cli.add_command(update_pricing)


@cli.command()
@click.option("--host", default="127.0.0.1", help="Host to bind to")
@click.option("--port", default=3838, help="Port to bind to")
@click.option("--reload", is_flag=True, help="Enable auto-reload for development")
def start(host: str, port: int, reload: bool) -> None:
    """Start the Robot Resources proxy server."""
    import uvicorn

    click.echo(f"Starting Robot Resources proxy on {host}:{port}")
    uvicorn.run(
        "robot_resources.proxy.server:app",
        host=host,
        port=port,
        reload=reload,
    )


@cli.command()
def status() -> None:
    """Show proxy status and statistics."""
    import httpx

    from robot_resources.config import get_settings

    settings = get_settings()
    port = settings.router_port
    base_url = f"http://127.0.0.1:{port}"

    from robot_resources import __version__
    click.echo(f"Robot Resources v{__version__}")
    click.echo(f"Port: {port}")

    try:
        response = httpx.get(f"{base_url}/health", timeout=3.0)
        data = response.json()

        status_text = data.get("status", "unknown")
        click.echo(f"Status: {status_text}")

        checks = data.get("checks", {})
        if "database" in checks:
            click.echo(f"Database: {checks['database']}")
        providers = checks.get("providers", [])
        if providers:
            click.echo(f"Providers: {', '.join(providers)}")
        else:
            click.echo("Providers: none configured")
    except httpx.ConnectError:
        click.echo("Status: not running")
        click.echo(f"Start with: rr-router start --port {port}")
    except httpx.HTTPError:
        click.echo("Status: error reaching proxy")


if __name__ == "__main__":
    cli()
