"""SSH 反向隧道后端 - 零安装，使用系统 SSH"""
from __future__ import annotations

import subprocess

from rich import print


def ssh_client(
    server: str, mappings: list[tuple[int, str, int]], ssh_user: str = "root"
):
    """通过 SSH 反向隧道建立端口映射

    Args:
        server: 服务器地址 host[:port]，默认端口 22
        mappings: [(remote_port, target_host, target_port), ...]
        ssh_user: SSH 用户名
    """
    parts = server.split(":")
    host = parts[0]
    port = parts[1] if len(parts) > 1 else "22"

    cmd = ["ssh", "-N"]
    for remote_port, target_host, target_port in mappings:
        cmd.extend(["-R", f"{remote_port}:{target_host}:{target_port}"])
        print(
            f"  [blue]{host}:{remote_port}[/blue] -> [cyan]{target_host}:{target_port}[/cyan]"
        )

    cmd.extend([f"{ssh_user}@{host}", "-p", port])

    print(f"\n[green]SSH 反向隧道连接到 {ssh_user}@{host}:{port}[/green]")
    print("[dim]注意: 默认只监听服务端 127.0.0.1，需外部访问请设置 GatewayPorts yes[/dim]")
    print("[dim]按 Ctrl+C 断开[/dim]\n")

    try:
        subprocess.run(cmd)
    except KeyboardInterrupt:
        print("\n[yellow]SSH 隧道已断开[/yellow]")
    except FileNotFoundError:
        print("[red]找不到 ssh 命令，请确认系统已安装 OpenSSH[/red]")
