#! /usr/bin/env python
"""
@Author: xiaobaiTser
@Time  : 2022/8/24 2:26
@File  : xiaobaicmd.py

命令行工具 - 使用 argparse 实现子命令模式

用法:
    xiaobaicmd template (t)    # 创建项目模板
    xiaobaicmd monitor (m)     # 监控功能
    xiaobaicmd device (d)      # 设备监控
    xiaobaicmd tools           # 工具命令
    xiaobaicmd -h/--help      # 显示帮助
"""
import argparse
import sys
from pathlib import Path
from shutil import copytree, rmtree

CUR_DIR = Path(__file__).resolve().parent
PARENT_DIR = CUR_DIR.parent


def cmd_template(args):
    """创建项目模板"""
    template_type = args.type
    target_dir = Path(args.dirname).resolve()

    templates = {
        "web": ("WEB_Project", PARENT_DIR / "templates"),
        "api": ("API_Project", PARENT_DIR / "templates"),
        "app": ("app", PARENT_DIR / "example"),
    }

    if template_type not in templates:
        print(f"错误: 无效的模板类型 '{template_type}'")
        print(f"支持的类型: {', '.join(templates.keys())}")
        sys.exit(1)

    src_name, src_base = templates[template_type]
    src_path = src_base / src_name
    dest_path = target_dir / src_name

    if not src_path.exists():
        print(f"错误: 模板目录不存在: {src_path}")
        sys.exit(1)

    if dest_path.exists():
        response = input(f"目标目录已存在 '{dest_path}'，是否覆盖? [y/N]: ")
        if response.lower() != 'y':
            print("已取消")
            sys.exit(0)
        rmtree(dest_path)

    copytree(src_path, dest_path)
    print(f"✓ 模板 '{template_type}' 已创建到: {dest_path}")


def cmd_monitor(args):
    """监控功能"""
    monitor_type = args.type

    if monitor_type in ("gui", "cli", "power", "memory"):
        if monitor_type in ("power", "memory"):
            from saf.utils.MonitorAndroidPackagePower import power
            power()
        elif monitor_type == "gui":
            from saf.utils.MonitorAndroidPackageGUI import gui
            gui()
        elif monitor_type == "cli":
            from saf.utils.MonitorAndroidPackageCLI import cli
            cli()
    elif monitor_type == "cp":
        from saf.utils.MonitorCP import cpmain
        cpmain()
    else:
        print(f"错误: 无效的监控类型 '{monitor_type}'")
        print("支持的类型: gui, cli, power, memory, cp")
        sys.exit(1)


def cmd_device(args):
    """设备监控"""
    index = args.index
    if index is None:
        index = 1
    try:
        from saf.utils.MonitorAndroidDeviceGUI import MonitorDevice
        MonitorDevice(index - 1)
    except Exception as e:
        print(f"错误: 设备监控启动失败: {e}")
        sys.exit(1)


def cmd_tools(args):
    """工具命令"""
    tool = args.tool

    if tool == "dns":
        domains = args.domains
        if not domains:
            from saf.utils.FlushDNSUtils import GITHUB_DOMAINS
            domains = GITHUB_DOMAINS.copy()
        elif isinstance(domains, str):
            domains = [d.strip() for d in domains.split(",") if d.strip()]
        
        if not domains:
            print("错误: 未提供域名")
            sys.exit(1)
        
        try:
            from saf.utils.FlushDNSUtils import flush_dns
            flush_dns(domains)
        except Exception as e:
            print(f"错误: DNS更新失败: {e}")
            sys.exit(1)

    elif tool == "install":
        try:
            from saf.utils.SoftwareManager import SoftwareManagerUI
            SoftwareManagerUI()
        except Exception as e:
            print(f"错误: 软件管理器启动失败: {e}")
            sys.exit(1)

    elif tool == "curl2locust" or tool == "c2l":
        try:
            from saf.utils.Curl2Locust import main as curl2locust_main
            sys.argv = ["xiaobaic2l"]
            if args.port != 8899:
                sys.argv.extend(["-p", str(args.port)])
            if args.host != "0.0.0.0":
                sys.argv.extend(["-i", str(args.host)])
            if args.filename:
                for f in args.filename:
                    sys.argv.extend(["-f", f])
            if args.dir:
                sys.argv.extend(["-d", args.dir])
            if args.curl:
                sys.argv.extend(["-c", args.curl])
            if args.browser:
                sys.argv.extend(["-b", args.browser])
            curl2locust_main()
        except Exception as e:
            print(f"错误: Curl2Locust 启动失败: {e}")
            sys.exit(1)

    elif tool == "openclaw":
        try:
            from saf.utils.OllamaOpenclaw import main as openclaw_main
            openclaw_main()
        except Exception as e:
            print(f"错误: Openclaw 启动失败: {e}")
            sys.exit(1)

    else:
        print(f"错误: 无效的工具 '{tool}'")
        print("支持的工具: dns, install, curl2locust, openclaw")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        description="xiaobai 命令行工具",
        prog="xiaobaicmd",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  xiaobaicmd template api                           # 创建 API 项目模板
  xiaobaicmd template web -d myproject              # 创建 WEB 项目模板到指定目录
  xiaobaicmd monitor gui                           # 启动 GUI 监控
  xiaobaicmd monitor cp                            # 启动剪贴板监控
  xiaobaicmd device 1                              # 监控设备 1
  xiaobaicmd tools dns github.com,raw.githubusercontent.com  # 更新 DNS
  xiaobaicmd tools install                         # 打开软件管理器界面
  xiaobaicmd tools curl2locust -f req.txt         # Curl 转 Locust 的 web 服务
  xiaobaicmd tools openclaw                         # Openclaw 工具
        """
    )

    subparsers = parser.add_subparsers(dest="command", help="可用命令")

    template_parser = subparsers.add_parser("template", aliases=["t"], help="创建项目模板")
    template_parser.add_argument("type", choices=["web", "api", "app"], help="模板类型")
    template_parser.add_argument("-d", "--dirname", default=".", help="目标目录")

    monitor_parser = subparsers.add_parser("monitor", aliases=["m"], help="监控功能")
    monitor_parser.add_argument("type", choices=["gui", "cli", "power", "memory", "cp"], help="监控类型")

    device_parser = subparsers.add_parser("device", aliases=["d"], help="设备监控")
    device_parser.add_argument("index", nargs="?", type=int, default=1, help="设备序号（从1开始）")

    tools_parser = subparsers.add_parser("tools", help="工具命令")
    tools_subparsers = tools_parser.add_subparsers(dest="tool", help="工具类型")

    dns_parser = tools_subparsers.add_parser("dns", help="更新 DNS")
    dns_parser.add_argument("domains", nargs="?", help="域名（用逗号分隔）")

    install_parser = tools_subparsers.add_parser("install", help="软件管理器")

    curl2locust_parser = tools_subparsers.add_parser("curl2locust", aliases=["c2l"], help="Curl 转 Locust 的 web 服务")
    curl2locust_parser.add_argument("-p", "--port", type=int, default=8899, help="服务器端口 (默认: 8899)")
    curl2locust_parser.add_argument("-i", "--host", default="0.0.0.0", help="服务器地址 (默认: 0.0.0.0)")
    curl2locust_parser.add_argument("-f", "--filename", nargs="+", help="curl 文件路径")
    curl2locust_parser.add_argument("-d", "--dir", help="目录路径")
    curl2locust_parser.add_argument("-c", "--curl", help="curl 字符串")
    curl2locust_parser.add_argument("-b", "--browser", choices=['chrome', 'firefox', 'edge', 'safari', 'none'], help="浏览器")

    ollama_parser = tools_subparsers.add_parser("openclaw", help="Openclaw 工具")

    args = parser.parse_args()

    if args.command is None:
        parser.print_help()
        sys.exit(1)

    if args.command in ("template", "t"):
        cmd_template(args)
    elif args.command in ("monitor", "m"):
        cmd_monitor(args)
    elif args.command in ("device", "d"):
        cmd_device(args)
    elif args.command == "tools":
        cmd_tools(args)
    else:
        parser.print_help()
        sys.exit(1)


if __name__ == "__main__":
    main()
