# -*- coding: utf-8 -*-
from setuphelpers import *
import json
def update_package():
    # Declaring local variables
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    os_dict = {
        "windows": ".exe",
        "mac": ".dmg",
        "debian_based": ".deb",
        "redhat_based": ".rpm",
        "opensuse": ".rpm",
        "arch": ".pkg.tar.zst",
    }

    arch_dict = {
        "x64": "amd64",
        "amd64": "amd64",
        "arm64": "arm64",
        "arm": "arm64",
    }
    api_url = "https://api.github.com/repos/Windscribe/Desktop-App/releases/latest"
    os_suffix = os_dict[control.target_os]  # Ex: ".exe", ".deb"
    arch_prefix = arch_dict[control.architecture]  # Ex: "amd64", "arm64"
    releases_dict = json.loads(wgets(api_url, proxies=proxies))

    for asset in releases_dict["assets"]:
        url = asset["browser_download_url"]
        # Vérifie que l'URL se termine par l'extension OS ET contient le préfixe arch
        if (url.endswith(os_suffix) and arch_prefix in url):
            url_download = url
            latest_bin = url.split("/")[-1]
            version = releases_dict["tag_name"].lstrip("v")
            exe_found = True
            break

    # Downloading latest binaries
    print("Download URL is: %s" % url_download)
    if isfile(latest_bin):
        remove_file(latest_bin)
    print("Downloading: %s" % latest_bin)
    wget(url_download, latest_bin, proxies=proxies)
    control.set_software_version(version)
    control.save_control_to_wapt()