"""sshj.cmd — the exact ssh argv this connection would use.

B2 step 4a: moved verbatim from sshj_cli.py (single-file era) — no
behavior change. Leaf: the footer preview (ui), the tab-insert (run)
and connect() all derive the command from ssh_cmd_args, so it lives
in the module they all depend on instead of the cycle it used to sit
in (ui -> connect -> ui). Owns DOWN_CONNECT_TIMEOUT (its only
consumer). Edge: tailnet.ssh_host (resolved-form target).
"""

import shlex

from .tailnet import ssh_host


DOWN_CONNECT_TIMEOUT = 5   # cap the real ssh timeout when status says down


def ssh_cmd_args(host, status, extra_args=(), resolved=False):
    """The exact ssh argv this connection would use (shared by the footer
    preview, the tab-insert, and connect()). resolved=True swaps the alias
    for the last outgoing address (user@host:port)."""
    args = ["ssh"]
    if status == "down":
        args += ["-o", f"ConnectTimeout={DOWN_CONNECT_TIMEOUT}"]
    # Flags are IDENTICAL for both forms; only the target token differs.
    # A discovered raw target (no ssh-config entry) must carry -p explicitly,
    # in BOTH forms, so the resolved command is the alias command with just
    # the name swapped for the full address — same flags, same result.
    if host.get("src") and host.get("port") not in ("", "22"):
        args += ["-p", host["port"]]
    if resolved:
        tgt = host.get("target") or host["alias"]
    elif host.get("src"):
        tgt = ssh_host(host, with_user=True)
    else:
        tgt = host["alias"]
    args += list(extra_args)
    args += ["--", tgt]
    return args


def ssh_cmd_args_typed(host, status, extra_args=(), resolved=False):
    """The ssh command as it would be TYPED at a prompt: ssh_cmd_args() with
    the `--` separator dropped. `ssh -- target` and `ssh target` run the same
    ssh, but a literal `--` at the shell input line reads as noise, so the
    two-stage inserts (right = the alias command, tab = the address command)
    use this form. Same flags, same target — only the separator is absent.
    resolved=True is the ADDRESS command: the alias swapped for the full
    user@host:port target (what the footer's right side shows)."""
    return [a for a in ssh_cmd_args(host, status, extra_args, resolved)
            if a != "--"]


def ssh_cmd_str(host, status, extra_args=(), resolved=False):
    """shlex-quoted one-liner form of ssh_cmd_args()."""
    return " ".join(shlex.quote(a) for a in
                    ssh_cmd_args(host, status, extra_args, resolved))


def ssh_cmd_str_typed(host, status, extra_args=(), resolved=False):
    """shlex-quoted one-liner of ssh_cmd_args_typed() (no `--`)."""
    return " ".join(shlex.quote(a) for a in
                    ssh_cmd_args_typed(host, status, extra_args, resolved))


