# -*- coding: utf-8 -*-
"""Register and dispatch extended CLI commands."""

from __future__ import annotations

import argparse
from typing import Any

from .common import add_json_flag
from .config import add_config_subparsers, handle_config
from .logs import add_logs_subparsers, handle_logs
from .preview import add_command_subparsers, handle_command_preview
from .project import (
    handle_doctor,
    handle_ids,
    handle_info,
    handle_migrate,
    handle_regen_all,
    handle_status,
)


def add_extended_subparsers(subparsers: argparse._SubParsersAction) -> None:
    info = subparsers.add_parser("info", help="显示项目路径、版本和工具信息")
    info.add_argument("--include-sensitive", action="store_true", help="配置输出中包含敏感字段")
    add_json_flag(info)

    status = subparsers.add_parser("status", aliases=["st"], help="检查服务器节点在线状态")
    status.add_argument("servers", nargs="*", help="服务器目录名或完整节点名；为空时检查全部")
    status.add_argument("--ip", help="目标 IP；节点名不含 @ip 时使用")
    status.add_argument("--strict", action="store_true", help="使用 net_adm:ping 严格检查 cookie 和分布式握手")
    add_json_flag(status)

    ids = subparsers.add_parser("ids", help="查看指定类型已有服务器 ID 和下一个可用 ID")
    ids.add_argument("--type", "-t", required=True, choices=["game", "login", "center", "cross", "client"])
    ids.add_argument("--prefix", "-p", help="服务器前缀，默认读取配置 prefix")
    add_json_flag(ids)

    doctor = subparsers.add_parser("doctor", help="检查目录、配置模板和外部工具可用性")
    add_json_flag(doctor)

    migrate = subparsers.add_parser("migrate", help="手动执行项目配置迁移")
    add_json_flag(migrate)

    config = subparsers.add_parser("config", help="查看或修改项目/服务器配置")
    add_config_subparsers(config)

    logs = subparsers.add_parser("logs", help="列出、读取或检索服务器日志")
    add_logs_subparsers(logs)

    command = subparsers.add_parser("command", aliases=["cmd"], help="只生成并打印启动/停止/连接命令，不执行")
    add_command_subparsers(command)


def handle_extended_command(args: argparse.Namespace, cli: Any) -> bool:
    command = getattr(args, "command", None)
    if command == "info":
        handle_info(args, cli)
    elif command in ("status", "st"):
        handle_status(args, cli)
    elif command == "ids":
        handle_ids(args, cli)
    elif command == "doctor":
        handle_doctor(args, cli)
    elif command == "migrate":
        handle_migrate(args, cli)
    elif command == "config":
        handle_config(args, cli)
    elif command == "logs":
        handle_logs(args, cli)
    elif command in ("command", "cmd"):
        handle_command_preview(args, cli)
    elif command == "regen" and getattr(args, "all", False):
        handle_regen_all(args, cli)
    else:
        return False
    return True
