# -*- coding: utf-8 -*-
"""Command preview extended CLI commands."""

from __future__ import annotations

import argparse
from typing import Any

from services.commands import (
    build_remsh_command,
    build_start_command_by_config,
    build_stop_command,
    generate_start_config,
    get_local_ip,
    subprocess_args_to_display,
)

from .common import add_json_flag, emit_json, is_json_output


def add_command_subparsers(parent: argparse.ArgumentParser) -> None:
    command_sub = parent.add_subparsers(dest="command_action", help="命令类型")

    cmd_start = command_sub.add_parser("start", help="打印启动命令")
    cmd_start.add_argument("server")
    cmd_start.add_argument("--quick", "-q", action="store_true", help="生成快速启动 erl 命令")
    add_json_flag(cmd_start)

    cmd_stop = command_sub.add_parser("stop", help="打印停止命令")
    cmd_stop.add_argument("server")
    add_json_flag(cmd_stop)

    cmd_connect = command_sub.add_parser("connect", help="打印 remsh 连接命令")
    cmd_connect.add_argument("server")
    cmd_connect.add_argument("--ip", help="目标 IP")
    add_json_flag(cmd_connect)


def handle_command_preview(args: argparse.Namespace, cli: Any) -> None:
    action = getattr(args, "command_action", None)
    if not action:
        raise SystemExit("请指定 command 子命令：start/stop/connect")
    if action == "start":
        merged = generate_start_config(cli.server_root, args.server)
        if not merged:
            raise SystemExit(f"无法生成 {args.server} 的启动配置")
        command = build_start_command_by_config(
            cli.server_root,
            merged,
            cli.cookie,
            use_rebar=not args.quick,
            erl_path=cli.config.get("erl_path"),
        )
        data = {"action": "start", "server": args.server, "cwd": cli.server_root, "command": command}
    elif action == "stop":
        command_args = build_stop_command(args.server, cli.cookie, local_host=get_local_ip(), erl_path=cli.config.get("erl_path"))
        data = {
            "action": "stop",
            "server": args.server,
            "cwd": cli.server_root,
            "args": command_args,
            "command": subprocess_args_to_display(command_args),
        }
    else:
        command = build_remsh_command(args.server, cli.cookie, target_ip=args.ip, local_host=get_local_ip(), erl_path=cli.config.get("erl_path"))
        data = {"action": "connect", "server": args.server, "cwd": cli.server_root, "command": command}
    if is_json_output(args):
        emit_json(data)
        return
    print(f"cwd: {data['cwd']}")
    print(data["command"])
