"""服务中转模块 - 支持 chisel / SSH / Python WebSocket 三种后端"""
from __future__ import annotations

from rich import print

METHODS = ("chisel", "ssh", "python")


def parse_mapping(s: str) -> tuple[int, str, int]:
    """解析端口映射字符串

    支持格式:
        '9000:8000'              -> (9000, 'localhost', 8000)
        '9000:192.168.1.5:8000'  -> (9000, '192.168.1.5', 8000)

    Returns:
        (remote_port, target_host, target_port)
    """
    parts = s.split(":")
    if len(parts) == 2:
        return int(parts[0]), "localhost", int(parts[1])
    elif len(parts) == 3:
        return int(parts[0]), parts[1], int(parts[2])
    else:
        raise ValueError(f"无效的端口映射格式: {s}，期望 远程端口:本地端口 或 远程端口:目标IP:目标端口")


def relay_server(
    port: int = 25565,
    host: str = "0.0.0.0",
    auth: str = None,
    method: str = "chisel",
):
    """启动中转服务端

    Args:
        port: 监听端口
        host: 监听地址
        auth: 认证 user:password
        method: 后端类型 chisel/python（SSH 不需要服务端）
    """
    if method == "chisel":
        from .chisel import chisel_server

        chisel_server(port=port, host=host, auth=auth)
    elif method == "python":
        from .ws import ws_server

        ws_server(port=port, host=host, auth=auth)
    elif method == "ssh":
        print("[yellow]SSH 后端使用系统 SSH Server，无需额外启动服务端[/yellow]")
        print("[dim]确保目标机器的 sshd 正在运行即可[/dim]")
    else:
        print(f"[red]未知的后端类型: {method}，可选: {', '.join(METHODS)}[/red]")


def relay_client(
    server: str,
    mappings: list[str],
    auth: str = None,
    method: str = "chisel",
    ssh_user: str = "root",
):
    """启动中转客户端

    Args:
        server: 服务器地址 host:port
        mappings: 端口映射列表 ['9000:8000', '9001:8001']
        auth: 认证
        method: 后端类型 chisel/ssh/python
        ssh_user: SSH 用户名（仅 ssh 后端）
    """
    if not mappings:
        print("[red]请指定端口映射，格式: 远程端口:本地端口[/red]")
        print("示例: maque relay B_IP:25565 9000:8000")
        return

    parsed = [parse_mapping(m) for m in mappings]

    if method == "chisel":
        from .chisel import chisel_client

        chisel_client(server=server, mappings=parsed, auth=auth)
    elif method == "ssh":
        from .ssh import ssh_client

        ssh_client(server=server, mappings=parsed, ssh_user=ssh_user)
    elif method == "python":
        from .ws import ws_client

        ws_client(server=server, mappings=parsed, auth=auth)
    else:
        print(f"[red]未知的后端类型: {method}，可选: {', '.join(METHODS)}[/red]")


def relay_install(use_mirror: bool = None):
    """下载/更新 chisel 二进制"""
    from .chisel import chisel_install

    chisel_install(use_mirror=use_mirror)
