"""CLI Utils."""

from collections.abc import Collection
from pathlib import Path

from slices_cli_bi.util.shell import shlex_quote_if_needed

PUBLIC_SSH_KEY_LOCATIONS = ["~/.ssh/id_ed25519.pub", "~/.ssh/id_ecdsa.pub", "~/.ssh/id_rsa.pub"]


def load_public_ssh_keys() -> list[str]:
    """Load SSH keys from well known locations."""
    public_ssh_keys = []
    for ssh_key_location in PUBLIC_SSH_KEY_LOCATIONS:
        path = Path(ssh_key_location).expanduser()
        if path.exists():
            public_ssh_keys.append(path.read_text())

    return public_ssh_keys


def create_add_ssh_pubkey_command(
    base_ssh_command: list[str], pubkeys_to_add: Collection[str], member_name: str | None
) -> str:
    """Create a command for accessing a node via SSH."""
    pubkey_lines = [f"COMMENT='{member_name or ''}'"]
    for pubkey in pubkeys_to_add:
        pubkey_lines.append(f"PUBKEY='{pubkey}'")
        pubkey_lines.append(
            'grep -qsF -- "$PUBKEY" ~/.ssh/authorized_keys || echo "$PUBKEY $COMMENT" >> ~/.ssh/authorized_keys'
        )

    escaped_ssh_command = " ".join([shlex_quote_if_needed(a) for a in base_ssh_command])

    lines = "\n".join(pubkey_lines)
    return f"""{escaped_ssh_command} 'sh -s' <<'EOF'\n{lines}\nexit 0\nEOF\n"""
