#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import libcalamares
import subprocess
import time

def run():
    # Get the list of snaps from the global settings
    global_storage = libcalamares.globalstorage
    snaps = global_storage.value("install_snaps")

    if not snaps or not isinstance(snaps, dict) or "snaps" not in snaps:
        libcalamares.utils.debug("No snaps specified in the configuration.")
        return None

    snaps = snaps["snaps"]

    if not snaps or not isinstance(snaps, list):
        libcalamares.utils.debug("Invalid snap configuration.")
        return None

    total_snaps = len(snaps)
    installed_snaps = 0

    def update_progress():
        progress = (installed_snaps / total_snaps) * 100
        libcalamares.job.setprogress(progress)

    def install_snap(snap):
        nonlocal installed_snaps
        try:
            # Update step information
            step_description = f"Installing {snap}..."
            libcalamares.job.setprogress(step_description)

            subprocess.run(['snap', 'install', snap], check=True)

            # Wait for the installation to complete
            while True:
                result = subprocess.run(['snap', 'list'], capture_output=True, text=True)
                if f"^{snap} " in result.stdout:
                    break
                time.sleep(5)

            libcalamares.utils.debug(f"{snap} installed successfully.")
            installed_snaps += 1
            update_progress()
        except subprocess.CalledProcessError as e:
            libcalamares.utils.warning(f"Failed to install {snap}: {e}")
            return False
        return True

    # Set job title and initial progress
    libcalamares.job.setprogress("Installing Snaps")
    update_progress()

    success = all(install_snap(snap) for snap in snaps)

    if success:
        libcalamares.utils.debug("All snaps installed successfully.")
        return None
    else:
        return "Failed to install one or more snaps."
