"""alice list-models — List available Bedrock foundation models."""

from __future__ import annotations

import json
from typing import Any

import boto3
import click
from botocore.exceptions import ClientError
from cachetools import TTLCache, cached  # type: ignore[import-untyped,unused-ignore]

from alice_cli import personality
from alice_cli.console import print_banner, print_table, spinner
from alice_cli.errors import AliceCLIError
from alice_cli.retry import with_aws_retry

# Cache model list for 5 minutes (300 seconds)
_model_cache: TTLCache[str, dict[str, Any]] = TTLCache(maxsize=10, ttl=300)


@cached(_model_cache)  # type: ignore[untyped-decorator,misc,unused-ignore]
@with_aws_retry(max_attempts=3, min_wait=1, max_wait=5)
def _fetch_foundation_models(region: str, profile: str | None) -> dict[str, Any]:
    """Fetch foundation models from Bedrock API with caching and automatic retry.

    Results are cached for 5 minutes to reduce API calls.
    Automatically retries on transient AWS errors with exponential backoff.

    Args:
        region: AWS region
        profile: AWS CLI profile name

    Returns:
        Response dict with 'modelSummaries' key

    Raises:
        AliceCLIError: If the API call fails after retries
    """
    session = boto3.Session(profile_name=profile, region_name=region)
    client = session.client("bedrock")
    try:
        return dict(client.list_foundation_models())
    except ClientError as exc:
        raise AliceCLIError(f"Bedrock API error: {exc}") from exc


@click.command("list-models")
@click.option("--json", "output_json", is_flag=True, help="Output as JSON to stdout")
@click.pass_context
def list_models(ctx: click.Context, output_json: bool) -> None:
    """List all Bedrock foundation models."""
    config = ctx.obj["config"]

    print_banner(personality.BANNER, config.quiet)

    with spinner(personality.status_fetching_models(), config.quiet):
        response = _fetch_foundation_models(config.region, config.profile)

    summaries = response.get("modelSummaries", [])

    if output_json:
        data = [
            {
                "modelId": m.get("modelId", ""),
                "modelName": m.get("modelName", ""),
                "providerName": m.get("providerName", ""),
                "inputModalities": m.get("inputModalities", []),
                "outputModalities": m.get("outputModalities", []),
            }
            for m in summaries
        ]
        click.echo(json.dumps(data, indent=2))
        return

    rows: list[list[str]] = []
    for model in summaries:
        rows.append(
            [
                model.get("modelId", ""),
                model.get("modelName", ""),
                model.get("providerName", ""),
                ", ".join(model.get("inputModalities", [])),
                ", ".join(model.get("outputModalities", [])),
            ]
        )

    print_table(
        title="Bedrock Foundation Models",
        columns=["Model ID", "Model Name", "Provider", "Input Modalities", "Output Modalities"],
        rows=rows,
    )
