"""alice gateway — Cheshire Gate configuration and status."""

from __future__ import annotations

import click

from alice_cli.agentcore_config import GatewayConfig, load_agentcore_config, save_agentcore_config
from alice_cli.aws.bedrock_context import _resolve_gateway_url
from alice_cli.console import err_console, print_success
from alice_cli.errors import AliceCLIError


@click.group("gateway")
def gateway_group() -> None:
    """Manage the Cheshire Gate AgentCore Gateway connection."""


@gateway_group.command("init")
@click.option("--name", default="cheshire-gate", help="Gateway name to store in config")
@click.pass_context
def gateway_init(ctx: click.Context, name: str) -> None:
    """Discover the gateway URL from SSM and save it to ~/.alice/agentcore.json.

    \b
    Examples:
        alice gateway init --profile drcc-ai
        alice gateway init --name my-gateway --profile drcc-ai
    """
    config = ctx.obj["config"]

    gateway_url = _resolve_gateway_url(config)
    if not gateway_url:
        raise AliceCLIError(
            "Could not find the Cheshire Gate URL in SSM.\n"
            f"  Expected parameter: /{config.namespace}"
            f"/{config.environment}/cheshire-gate/gateway-url\n"
            "  Ensure the cheshire-gate Terraform module is deployed."
        )

    ac_config = load_agentcore_config()
    ac_config.gateway = GatewayConfig(name=name, endpoint_url=gateway_url)
    save_agentcore_config(ac_config)

    print_success(f"Gateway configured: {name} → {gateway_url}", config.quiet)
    if not config.bedrock_bearer_token:
        err_console.print(
            "  [yellow]⚠[/yellow]  No bearer token found in stored credentials.\n"
            "  Run [bold]alice auth --profile <PROFILE>[/bold] to populate it."
        )


@gateway_group.command("status")
@click.pass_context
def gateway_status(ctx: click.Context) -> None:
    """Show the current gateway configuration and test connectivity.

    \b
    Examples:
        alice gateway status
        alice gateway status --profile drcc-ai
    """
    import httpx

    config = ctx.obj["config"]
    ac_config = load_agentcore_config()

    err_console.print("\n[bold]Cheshire Gate — Gateway Status[/bold]")

    if ac_config.gateway is None:
        err_console.print("  [yellow]⚠[/yellow]  No gateway configured.")
        err_console.print("  Run [bold]alice gateway init[/bold] to set it up.")
        return

    gw = ac_config.gateway
    err_console.print(f"  Name:    [cyan]{gw.name}[/cyan]")
    err_console.print(f"  URL:     {gw.endpoint_url or '[dim]not set[/dim]'}")
    token_status = (
        "[green]present[/green]"
        if config.bedrock_bearer_token
        else "[yellow]not found — run alice auth[/yellow]"
    )
    err_console.print(f"  Token:   {token_status}")

    if gw.endpoint_url:
        err_console.print()
        try:
            resp = httpx.head(gw.endpoint_url, timeout=5.0)
            err_console.print(f"  Reachable: [green]✓[/green] (HTTP {resp.status_code})")
        except Exception as exc:  # noqa: BLE001
            err_console.print(f"  Reachable: [red]✗[/red] ({exc})")

    err_console.print()
