"""AI Infrastructure Service CLI - Public SSH Key helpers."""

import typer
from typer._click.types import ParamType

from . import err_console
from .ai_context import AIContext


def get_user_pubkeys(ctx: AIContext) -> list[str]:
    """Get public keys of all members in the experiment."""

    return [
        f"{pubkey.public_key} {ctx.obj.get_logged_in_userinfo('sub')}"
        for pubkey in ctx.obj.api.public_key.list_for_user(ctx.obj.get_logged_in_userinfo("sub"))
    ]


SSH_PUBKEY_PREFIXES = ["ecdsa-", "ssh-", "sk-", "rsa-"]


class SshKeyParamType(ParamType):
    """Custom SSH Key ParamType."""

    envvar_list_splitter = ","
    name = "ssh-key"

    def convert(self, value: str, param, ctx):  # noqa: ARG002
        """Convert SSH key."""
        if not any(value.startswith(prefix) for prefix in SSH_PUBKEY_PREFIXES):
            raise typer.BadParameter("Not a valid SSH public key (in OpenSSH format).")
        return value


def validate_ssh_key(pubkey: str) -> str:
    """Validate SSH public key."""
    if not any(pubkey.startswith(prefix) for prefix in SSH_PUBKEY_PREFIXES):
        raise typer.BadParameter("Not a valid SSH public key (in OpenSSH format).")
    return pubkey


def get_ssh_keys(
    ctx: AIContext, extra_ssh_keys: list[str] | None, extra_ssh_key_files: list[typer.FileText] | None
) -> list[str]:
    """Retrieve all ssh keys that need to be passed to the AI service.

    Shows an error if none can be found.
    """
    ssh_authorized_keys = get_user_pubkeys(ctx)
    if extra_ssh_keys:
        ssh_authorized_keys.extend(extra_ssh_keys)
    if extra_ssh_key_files:
        for file in extra_ssh_key_files or []:
            ssh_authorized_keys.append(validate_ssh_key(file.read()))

    if not ssh_authorized_keys:
        err_console.print("[red]You need to have at least one public SSH key registered. :x:")
        err_console.print("Use: [blue]slices pubkey register")
        raise typer.Exit(code=1)

    return ssh_authorized_keys
