"""Gateway command - Start OpenAI-compatible API gateway."""

from __future__ import annotations

import sys

import click
from sage.common.config.ports import SagePorts as _SagePorts


@click.command()
@click.option("--port", type=int, default=_SagePorts.SAGELLM_GATEWAY, help="Server port")
@click.option("--host", type=str, default="0.0.0.0", help="Server host")
@click.option("--workers", type=int, default=1, help="Number of workers")
@click.option("--reload", is_flag=True, help="Enable auto-reload (dev mode)")
def gateway(port: int, host: str, workers: int, reload: bool) -> None:
    """Start the OpenAI-compatible API gateway.

    \b
    Examples:
            sagellm gateway                    # Start gateway
        sagellm gateway --port 8889        # Custom port
        sagellm gateway --reload           # Dev mode with reload
    """
    from ..utils.console import get_console

    console = get_console()

    console.print("\n🌐 [bold blue]Starting sageLLM Gateway...[/bold blue]\n")

    try:
        # Try to import gateway
        import uvicorn

        console.print(f"  Listening on: http://{host}:{port}")
        console.print(f"  API docs: http://{host}:{port}/docs")
        console.print()

        # Start uvicorn
        uvicorn.run(
            "sagellm_gateway.server:app",
            host=host,
            port=port,
            workers=workers,
            reload=reload,
            log_level="info",
        )

    except ImportError as e:
        console.print(f"[red]❌ Gateway not installed: {e}[/red]")
        console.print("\n[yellow]💡 Install sageLLM: pip install isagellm[/yellow]")
        sys.exit(1)
    except Exception as e:
        console.print(f"[red]❌ Failed to start gateway: {e}[/red]")
        sys.exit(1)
