import ctypes
import winreg
import sys
import os
import logging

# 设置日志等级（注释掉可完全静默）


def add_context_menu(name: str, exe_path: str, icon_path: str = None):
    """添加右键菜单"""
    key_path = fr"*\\shell\\{name}"
    try:
        key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, key_path)
        winreg.SetValueEx(key, "", 0, winreg.REG_SZ, name)
        if icon_path:
            winreg.SetValueEx(key, "Icon", 0, winreg.REG_SZ, icon_path)

        command_key = winreg.CreateKey(key, "command")
        winreg.SetValueEx(command_key, "", 0, winreg.REG_SZ, f'"{exe_path}" "%1"')

        winreg.CloseKey(key)

    except Exception as e:
        pass


def remove_context_menu(name: str):
    """删除右键菜单"""
    key_path = fr"*\\shell\\{name}"
    try:
        winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, key_path + r"\command")
        winreg.DeleteKey(winreg.HKEY_CLASSES_ROOT, key_path)
    except Exception as e:
        pass


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


def relaunch_as_admin():
    """尝试以管理员权限重新运行当前脚本"""
    params = ' '.join(f'"{arg}"' for arg in sys.argv)
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, params, None, 0)


def main():
    if len(sys.argv) < 3:
        return

    command = sys.argv[1].lower()
    name = sys.argv[2]

    if command == "install":
        if len(sys.argv) < 4:
            return
        exe_path = os.path.abspath(sys.argv[3])
        icon_path = os.path.abspath(sys.argv[4]) if len(sys.argv) >= 5 else exe_path
        add_context_menu(name, exe_path, icon_path)
    elif command == "uninstall":
        remove_context_menu(name)


if __name__ == "__main__":
    if not is_admin():
        relaunch_as_admin()
        sys.exit()
    main()
