import subprocess
import os
import time
import _winreg as winreg

UNINSTALL_ARGS = "/S"
TARGET_NAME = "Avast Secure Browser"

def get_installed_version():
    key_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
    hives = [
        (winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_64KEY),
        (winreg.HKEY_LOCAL_MACHINE, winreg.KEY_WOW64_32KEY),
        (winreg.HKEY_CURRENT_USER, winreg.KEY_WOW64_64KEY),
        (winreg.HKEY_CURRENT_USER, winreg.KEY_WOW64_32KEY),
    ]

    for hive, flag in hives:
        try:
            reg = winreg.ConnectRegistry(None, hive)
            key = winreg.OpenKey(reg, key_path, 0, winreg.KEY_READ | flag)

            index = 0
            while True:
                try:
                    subkey_name = winreg.EnumKey(key, index)
                    subkey_path = key_path + "\\" + subkey_name
                    subkey = winreg.OpenKey(reg, subkey_path, 0, winreg.KEY_READ | flag)

                    try:
                        display_name, _ = winreg.QueryValueEx(subkey, "DisplayName")
                        if TARGET_NAME.lower() in display_name.lower():
                            version, _ = winreg.QueryValueEx(subkey, "DisplayVersion")
                            return display_name, version
                    except:
                        pass
                    index += 1
                except WindowsError:
                    break
        except:
            continue

    return None, None

def get_uninstall_path():
    paths = [
        r"C:\Program Files\AVAST Software\Browser\AvastBrowserUninstall.exe",
        r"C:\Program Files (x86)\AVAST Software\Browser\AvastBrowserUninstall.exe"
    ]
    for path in paths:
        if os.path.exists(path):
            return path
    return None

def perform_uninstall(cmd):
    print("starting operation")
    start_time = time.time()

    try:
        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()

        if process.returncode == 0:
            print("operation completed")
        else:
            print("Uninstall failed with exit code:", process.returncode)
            if stderr:
                print("Error output:\n", stderr)
    except Exception as e:
        print("Uninstall failed due to exception:", str(e))

    duration = time.time() - start_time
    print("duration: %.2f seconds" % duration)

def main():
    print("starting uninstall operations")
    print("---------------------------------------------------------------")

    display_name, version = get_installed_version()

    if display_name:
        print("Avast secure browser found")
        print("installed version: %s %s" % (display_name, version))
    else:
        print("Avast secure browser not found")
        print("---------------------------------------------------------------")
        return

    uninstall_path = get_uninstall_path()

    if not uninstall_path:
        print("Uninstaller not found in Program Files or Program Files (x86)")
        print("---------------------------------------------------------------")
        return

    print("using direct uninstaller path (silent mode)")
    cmd = '"' + uninstall_path + '" ' + UNINSTALL_ARGS
    perform_uninstall(cmd)

    print("---------------------------------------------------------------")

if __name__ == "__main__":
    main()
