import os
import shutil
from pathlib import Path

from mower import __system__
from mower.utils import config

if __system__ == "windows":
    import winreg


def get_mumu12_install_path_from_registry() -> str:
    """
    从注册表中获取 MuMuPlayer-12.0 安装路径

    Returns:
        str: MuMuPlayer-12.0 的安装路径，如果未找到则返回相应提示
    """
    try:
        # 打开注册表项来查找 MuMuPlayer-12.0 的安装路径
        key_path = r"SOFTWARE\Classes\MuMuPlayer-12.0.apk\DefaultIcon"
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as reg:
            # 获取注册表中存储的路径字符串
            icon_path, _ = winreg.QueryValueEx(reg, None)

            # 解析出文件夹的路径
            install_path = os.path.dirname(icon_path)
            return install_path

    except FileNotFoundError:
        return "未找到 MuMuPlayer-12.0 的注册表项。"
    except PermissionError:
        return "没有权限访问注册表。请尝试以管理员身份运行脚本。"


def get_leidian_install_path() -> str:
    """
    从注册表中获取雷电模拟器的 playerDir9 安装路径，并去掉最后的反斜杠

    Returns:
        str: 雷电模拟器的 playerDir9 安装路径，如果未找到则返回相应提示
    """
    try:
        key_path = r"Software\leidian\ldplayer9"
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as reg:
            player_dir9, _ = winreg.QueryValueEx(reg, "InstallDir")
            return player_dir9.rstrip("\\/")
    except FileNotFoundError:
        return "未找到雷电模拟器的注册表项。"
    except PermissionError:
        return "没有权限访问注册表。请尝试以管理员身份运行脚本。"


def get_adb_path(emulator_folder: str):
    return emulator_folder + ("\\adb.exe" if __system__ == "windows" else "/adb")


def auto_get_path() -> str:
    if config.conf.emulator.name == "MuMu12":
        config.conf.emulator.emulator_folder = get_mumu12_install_path_from_registry()
    elif config.conf.emulator.name == "雷电9":
        config.conf.emulator.emulator_folder = get_leidian_install_path()
    elif config.conf.emulator.name == "ReDroid":
        config.conf.emulator.emulator_folder = str(Path(shutil.which("docker")).parent)
    elif config.conf.emulator.name == "Waydroid":
        config.conf.emulator.emulator_folder = str(
            Path(shutil.which("waydroid")).parent
        )
    else:
        return
    config.conf.maa_adb_path = get_adb_path(config.conf.emulator.emulator_folder)


def get_adb_serial() -> str:
    if not isinstance(config.conf.emulator.index, (int, str)):
        raise TypeError("请填写正确的多开编号")
    host = "127.0.0.1"
    try:
        index = int(config.conf.emulator.index)
    except ValueError:
        return
    if config.conf.emulator.name == "MuMu12":
        base_port = 16384
        cycle_offset = (index // 32) * 4  # 每 32 个编号端口回滚，增加 4
        port = str(base_port + (index % 32) * 32 + cycle_offset)
    elif config.conf.emulator.name == "雷电9":
        port = str(5555 + index * 2)
    elif config.conf.emulator.name == "夜神":
        port = str(62025 + index) if index >= 0 else "62001"
    else:
        return
    config.conf.adb = host + ":" + port


if __name__ == "__main__":
    mumu_path = get_mumu12_install_path_from_registry()
    print(f"MuMu 12 安装路径: {mumu_path}")
    print(f"MuMu 12 ADB路径: {get_adb_path(mumu_path)}")
    leidian_path = get_leidian_install_path()
    print(f"雷电模拟器安装路径: {leidian_path}")
    print(f"雷电模拟器 ADB路径: {get_adb_path(leidian_path)}")
