# -*- coding: utf-8 -*-
from setuphelpers import *
from setupdevhelpers import *
import re

def update_package():
    package_updated = False
    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()

    app_name = control.name
    target_os = control.target_os.lower()

    # IDs de téléchargement selon l'OS https://salesapi.thebrain.com/?a=doDirectDownload&id=()
    if target_os in ['windows']:
        download_id = '14001'
        os_name = 'Windows'

    elif target_os in ['mac']:
        download_id = '14000'
        os_name = 'mac'
    else:
        error(f"Unsupported OS: {target_os}")

    # URL de l'API qui redirige vers le téléchargement
    api_url = f"https://salesapi.thebrain.com/?a=doDirectDownload&id={download_id}"

    # Suivre la redirection pour obtenir l'URL réelle
    print(f"Download URL for {os_name}...")
    download_url = requests.head(api_url, proxies=proxies, allow_redirects=True).url

    # Nom du fichier
    latest_bin = download_url.rsplit('/', 1)[-1].replace("%20", "_")
    latest_bin_extension = latest_bin.rsplit('.', 1)[-1]

    # Extraire la version (ex: TheBrain_14_0_113_0_Windows.exe -> 14.0.113.0)
    version_match = re.search(r'(\d+)', latest_bin)
    if version_match:
        version = '.'.join(version_match.groups())
    else:
        error("Could not extract version from filename")

    print(f"Latest {app_name} version is: {version}")
    print(f"Download URL is: {download_url}")

    # Télécharger si nécessaire
    if not isfile(latest_bin):
        print(f"Downloading: {latest_bin}")
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print(f"Binary already present: {latest_bin}")

    # Mettre à jour la version du package
    if Version(version) > Version(control.get_software_version()):
        print(f"Version updated: {control.get_software_version()} -> {version}")
        package_updated = True
    else:
        print(f"Version up-to-date: {version}")

    # Supprimer les anciens binaires
    for f in glob.glob(f'*.{latest_bin_extension}'):
        if f != latest_bin:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated