import os
import logging
import shutil
import zipfile
import subprocess
import sys

# Obtient le chemin complet du répertoire utilisateur sur un environnement Windows
user_directory = os.path.expanduser('~')

# Chemin vers le répertoire des journaux
log_directory = os.path.join(user_directory, '.atsmobilestation', 'logs')

# Vérifie si le répertoire des journaux existe, sinon le crée
if not os.path.exists(log_directory):
    os.makedirs(log_directory)

# Chemin vers le fichier journal en remplaçant la partie fixe par le répertoire utilisateur
log_file_path = os.path.join(log_directory, 'update_log.txt')

# Configuration du logger
logging.basicConfig(filename=log_file_path, level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

def extract_bundle(zip_path, extract_to):
    try:
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(extract_to)
        logging.info(f"Extracted {zip_path} to {extract_to}")
    except Exception as e:
        logging.error(f"Error while extracting bundle: {e}")

def replace_application(downloaded_bundle_path, application_directory, app_executable):
    try:
        # Get the parent directory of the application directory
        parent_directory = os.path.dirname(application_directory)

        # Create a temporary directory for extraction next to the application directory
        temp_extract_path = os.path.join(parent_directory, "temp_extract")
        if os.path.exists(temp_extract_path):
            shutil.rmtree(temp_extract_path)
        os.makedirs(temp_extract_path)

        # Extract the bundle to the temporary location
        extract_bundle(downloaded_bundle_path, temp_extract_path)

        # Clean up the application directory
        if os.path.exists(application_directory):
            shutil.rmtree(application_directory)

        # Move the new files to the application directory
        shutil.move(temp_extract_path, application_directory)

        # Clean up
        os.remove(downloaded_bundle_path)
        logging.info("Update completed.")

        # Restart the application
        subprocess.Popen([app_executable])
        logging.info("Application restarted.")
    except Exception as e:
        logging.error(f"Error during update process: {e}", exc_info=True)  # Enregistre également la trace complète de l'exception

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python update_script.py <downloaded_bundle_path> <application_directory> <app_executable>")
        sys.exit(1)

    downloaded_bundle_path = sys.argv[1]
    application_directory = sys.argv[2]
    app_executable = sys.argv[3]

    replace_application(downloaded_bundle_path, application_directory, app_executable)