"""
xqcwechat CLI 命令行工具
"""

import sys
import shutil
import argparse
from pathlib import Path


def find_all_skills_dirs(start_dir: Path, max_depth: int = 3) -> list[Path]:
    """递归查找所有 skills 目录"""
    results = []

    def search(dir_path: Path, depth: int):
        if depth > max_depth:
            return

        skills_dir = dir_path / "skills"
        if skills_dir.exists() and skills_dir.is_dir():
            results.append(skills_dir)

        for item in dir_path.iterdir():
            if item.is_dir():
                search(item, depth + 1)

    search(start_dir, 0)
    return results


def get_installation_path() -> Path:
    """获取安装路径"""
    current_dir = Path.cwd()

    print("\n" + "=" * 50)
    print("xqcwechat-skill 安装")
    print("=" * 50)

    all_skills_dirs = find_all_skills_dirs(current_dir)

    if all_skills_dirs:
        print("\n发现可用的 skills 目录:")
        print("-" * 50)

        for idx, skills_dir in enumerate(all_skills_dirs, 1):
            print(f"[{idx}] {skills_dir}")

        print("\n[0] 自定义目录")
        print(f"[Enter] 当前目录 ({current_dir})")

        choice = input("\n请选择安装目录 (输入序号或路径): ").strip()

        if choice == "":
            return current_dir

        try:
            idx = int(choice)
            if idx == 0:
                custom_path = input("请输入自定义目录路径: ").strip()
                if custom_path:
                    return Path(custom_path).resolve()
                return current_dir
            elif 1 <= idx <= len(all_skills_dirs):
                return all_skills_dirs[idx - 1]
        except ValueError:
            if Path(choice).exists():
                return Path(choice).resolve()
            else:
                print(f"❌ 目录不存在: {choice}")

    return current_dir


def cmd_install(args):
    """安装命令"""
    skill_dir = Path(__file__).parent.parent / "xqcwechat-skill"
    target_dir = args.target if args.target else get_installation_path()
    target_dir = Path(target_dir).resolve()

    print("=" * 50)
    print("xqcwechat-skill 安装")
    print("=" * 50)
    print(f"目标目录: {target_dir}")

    target_dir.mkdir(parents=True, exist_ok=True)

    skill_dest = target_dir / "xqcwechat-skill"

    if skill_dest.exists():
        print("⚠️ 目标目录已存在 xqcwechat-skill，是否覆盖? (y/n): ", end="")
        if input().strip().lower() != "y":
            print("❌ 安装取消")
            sys.exit(1)
        shutil.rmtree(skill_dest)

    shutil.copytree(skill_dir, skill_dest)
    print(f"✅ 已安装 xqcwechat-skill 到: {skill_dest}")

    print("\n" + "=" * 50)
    print("🎉 安装完成!")
    print("=" * 50)
    print("\n📝 下一步:")
    print(f"   1. 复制 {skill_dest}/.env.example 为 .env")
    print("   2. 填入您的微信公众号配置")
    print("   3. 参考 account_manager.py 管理多账号")


def cmd_version(args):
    """版本命令"""
    from xqcwechat import __version__

    print(__version__)


def main():
    parser = argparse.ArgumentParser(
        description="xqcwechat - 微信公众号开发工具包",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("-v", "--version", action="store_true", help="显示版本信息")
    subparsers = parser.add_subparsers(dest="command", help="可用命令")

    install_parser = subparsers.add_parser(
        "skill", help="安装 xqcwechat-skill 到指定目录"
    )
    install_parser.add_argument(
        "-d", "--dir", dest="target", default=None, help="安装目标目录 (默认为当前目录)"
    )

    args = parser.parse_args()

    if args.version:
        cmd_version(args)
    elif args.command == "skill":
        cmd_install(args)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
