"""CLI command for web chat server."""

from __future__ import annotations

import click

from oclawma.cli_ui import (
    accent,
    header,
    highlight,
    key_value,
    print_error,
    print_info,
    print_success,
    progress_spinner,
    subheader,
)


@click.command(name="web")
@click.option(
    "--port",
    "-p",
    type=int,
    default=8080,
    help="Port to run the server on",
    show_default=True,
)
@click.option(
    "--host",
    "-h",
    type=str,
    default="0.0.0.0",
    help="Host to bind the server to",
    show_default=True,
)
@click.option(
    "--token",
    "-t",
    type=str,
    help="Authentication token (random if not provided)",
)
@click.option(
    "--behind-proxy",
    is_flag=True,
    default=True,
    help="Enable proxy header support (X-Forwarded-For, etc.)",
)
@click.option(
    "--dev",
    is_flag=True,
    help="Enable development mode with auto-reload",
)
@click.option(
    "--no-auth",
    is_flag=True,
    help="Disable authentication (NOT for production)",
)
def web_chat(
    port: int,
    host: str,
    token: str | None,
    behind_proxy: bool,
    dev: bool,
    no_auth: bool,
) -> None:
    """Start the OCLAWMA web chat server.

    Launches a FastAPI-based web server with real-time chat via WebSocket.
    Provides a mobile-responsive interface with dark/light themes and
    markdown rendering.

    \b
    Examples:
        oclawma web                    # Start on default port 8080
        oclawma web --port 3000        # Start on custom port
        oclawma web --token mysecret   # Use custom auth token
        oclawma web --dev              # Development mode with reload
    """
    try:
        import uvicorn

        from oclawma.web.server import create_app
    except ImportError as e:
        print_error(f"Missing required dependencies: {e}")
        click.echo()
        click.echo("Please install web dependencies:")
        click.echo("  pip install 'oclawma[web]'")
        raise click.Abort() from None

    click.echo(header("OCLAWMA WEB CHAT", width=58))
    click.echo()

    # Create the app
    with progress_spinner("Initializing web server..."):
        effective_token = token if token else "demo" if no_auth else None
        app = create_app(
            auth_token=effective_token,
            behind_proxy=behind_proxy,
        )
        actual_token = app.state.auth.get_token()

    # Display configuration
    click.echo(subheader("SERVER CONFIGURATION"))
    click.echo(key_value("Host", host))
    click.echo(key_value("Port", str(port)))
    click.echo(key_value("Proxy Support", "enabled" if behind_proxy else "disabled"))
    click.echo(key_value("Dev Mode", "enabled" if dev else "disabled"))

    if no_auth:
        click.echo(key_value("Authentication", "disabled (WARNING: insecure!)"))
    else:
        click.echo(key_value("Auth Token", highlight(actual_token[:16] + "...")))

    click.echo()
    click.echo(subheader("ACCESS URLs"))

    # Determine display URLs
    local_url = f"http://127.0.0.1:{port}"
    network_url = f"http://{host}:{port}" if host != "127.0.0.1" else None

    click.echo(f"  Local:   {accent(local_url)}")
    if network_url and network_url != local_url:
        click.echo(f"  Network: {accent(network_url)}")

    click.echo()

    # Show token instructions
    if not no_auth:
        print_info("Use the following token to authenticate:")
        click.echo()
        click.echo(f"  {highlight(actual_token)}")
        click.echo()
        click.echo("Or set the token via environment variable:")
        click.echo(f"  export OCLAWMA_WEB_TOKEN={actual_token}")
        click.echo()

    print_success("Starting server... Press Ctrl+C to stop")
    click.echo()

    try:
        uvicorn.run(
            "oclawma.web.server:create_app",
            host=host,
            port=port,
            reload=dev,
            factory=True,
            log_level="info",
        )
    except KeyboardInterrupt:
        click.echo()
        print_info("Server stopped")
