"""Direct SSH command execution for verification checks.

Note: known_hosts=None is used for local VM automation. This disables host key
verification and is a known limitation for Phase 2. Phase 4 will harden this.
"""

from __future__ import annotations

import logging

import asyncssh

logger = logging.getLogger(__name__)

_KNOWN_HOSTS_WARNING = (
    "SSH connection to %s:%s using known_hosts=None — host key verification disabled. Acceptable for local VMs only."
)


async def _ssh_exec(
    host: str, port: int, username: str, command: str, identity_file: str | None = None
) -> tuple[str, str, int]:
    """Run a command on a remote host via SSH.

    Returns:
        Tuple of (stdout, stderr, exit_code).

    Warning:
        known_hosts=None disables host key verification. Acceptable for local VM
        automation only. Do not use against untrusted remote hosts (Phase 4 hardening).
    """
    logger.warning(_KNOWN_HOSTS_WARNING, host, port)
    kwargs: dict[str, object] = {"host": host, "port": port, "username": username, "known_hosts": None}
    if identity_file is not None:
        kwargs["client_keys"] = [identity_file]
    async with asyncssh.connect(**kwargs) as conn:
        result = await conn.run(command, check=False)
        stdout = result.stdout if isinstance(result.stdout, str) else ""
        stderr = result.stderr if isinstance(result.stderr, str) else ""
        exit_code = result.returncode if isinstance(result.returncode, int) else 0
        return stdout, stderr, exit_code
