"""Tool to add remote pubkeys to a host."""

from subprocess import PIPE, STDOUT, Popen, TimeoutExpired

from rich.panel import Panel
from slices_clientlib_core.experiment import ExperimentResource

from slices_cli_bi import console
from slices_cli_bi.commands.bi import ProxyOption, make_ssh_command
from slices_cli_bi.commands.bi_context import BIContextObj, WrapContextAsBIContext
from slices_cli_bi.core.context import Context
from slices_cli_bi.util.pubkey_extra import create_add_ssh_pubkey_command


def add_ssh_pubkeys_to_bi_resource(
    ctx: Context,
    resource: ExperimentResource,
    experiment_id: str,
    member_name: str,
    pubkeys: list[str],
    *,
    print_progress: bool = False,
):
    """Use SSH to add SSH public keys to a BI resource."""
    bi_ctx_obj = BIContextObj(
        api=ctx.obj.api,
        user_info=ctx.obj.user_info,
        other_users_info=ctx.obj.other_users_info,
        infra_id=resource.infra_id,
        cluster_id="default",
    )

    base_ssh_command = make_ssh_command(
        WrapContextAsBIContext(ctx, bi_ctx_obj),  # pyright: ignore [reportArgumentType]
        resource.id,
        experiment_id,
        ProxyOption.auto,
    )

    full_command = create_add_ssh_pubkey_command(base_ssh_command, pubkeys, member_name)
    # full_command = "   " + full_command.replace("\n", "\n   ")

    command_error = None
    try:
        with Popen(  # noqa: S603
            ["/usr/bin/sh", "-s"],
            stdout=PIPE,
            stderr=STDOUT,
            stdin=PIPE,
            universal_newlines=True,
        ) as proc:
            try:
                proc.communicate(input=full_command, timeout=5)
            except TimeoutExpired:
                command_error = "Timeout trying to modify ~/.ssh/authorized_keys."
                # console.print("[bold red]Timeout trying to modify ~/.ssh/authorized_keys.")
                proc.kill()
            else:
                res_code = proc.wait()
                if res_code != 0:
                    command_error = f"Failed to modify ~/.ssh/authorized_keys. Return value is {res_code}"
                    # console.print("[bold red]Failed to modify ~/.ssh/authorized_keys.")
    except:
        command_error = "Failure executing command."
        raise
    finally:
        if print_progress:
            console.print(
                Panel(
                    full_command.strip(),
                    highlight=False,
                    expand=False,
                    style="red" if command_error else "blue",
                    title_align="left",
                    title=f"[bold blue]{'Failed to add' if command_error else 'Added'} SSH keys "
                    f"of {member_name!r} to {resource.friendly_name!r}. "
                    f"Command used:",
                    subtitle_align="left",
                    subtitle=command_error or None,
                )
            )
