# -*- coding: utf-8 -*-
from setuphelpers import *
import json
import re
import glob

def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    git_repo = "cloudquery/cloudquery"
    url_api = f"https://api.github.com/repos/{git_repo}/releases?per_page=10000"
    # Getting latest version information from official sources
    print(f"API used is: {url_api}")
    json_load = json.loads(wgets(url_api, proxies=proxies))

    url_dl = None
    filename = None
    version = None

    for release in json_load:
        for download in release["assets"]:
            if download["browser_download_url"].endswith(".exe"):
                if 'rc' in release["tag_name"]:
                    continue
                url_dl = download["browser_download_url"]
                version = release["tag_name"].split("-")[-1].replace("v", "")
                filename = download["name"]
                
                break
        if url_dl:
            break

    if not url_dl or not filename or not version:
        raise Exception("No .exe file found in the latest release")

    if not isfile(filename):
        package_updated = True
        wget(url_dl, filename, proxies=proxies)

    # Clean up old .exe files
    for f in glob.glob("*.exe"):
        if f != filename:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()