from typing import Literal

import typer

from alloy_runtime_types.credential_targets import (
    SupportedCredentialTargets,
    get_supported_credential_targets,
)

from cli.commands.credentials.supported.presenter import present_supported_credentials


SupportedKind = Literal["providers", "tools", "mappings"]


def credentials_supported_command(
    kind: str | None = typer.Option(
        None,
        "--kind",
        help="Optional filter: providers, tools, or mappings",
    ),
) -> None:
    catalog = get_supported_credential_targets()
    filtered_kind = _validate_kind(kind)
    present_supported_credentials(_filter_catalog(catalog, filtered_kind))


def _validate_kind(kind: str | None) -> SupportedKind | None:
    if kind is None:
        return None

    normalized = kind.lower()
    if normalized not in {"providers", "tools", "mappings"}:
        raise typer.BadParameter(
            f"Invalid value for '--kind': '{kind}'. Choose from: providers, tools, mappings"
        )

    return normalized  # type: ignore[return-value]


def _filter_catalog(
    catalog: SupportedCredentialTargets,
    kind: SupportedKind | None,
) -> SupportedCredentialTargets:
    if kind == "providers":
        return SupportedCredentialTargets(
            inference_providers=catalog.inference_providers,
            tool_services=(),
            tool_mappings=(),
        )
    if kind == "tools":
        return SupportedCredentialTargets(
            inference_providers=(),
            tool_services=catalog.tool_services,
            tool_mappings=(),
        )
    if kind == "mappings":
        return SupportedCredentialTargets(
            inference_providers=(),
            tool_services=(),
            tool_mappings=catalog.tool_mappings,
        )
    return catalog
