import subprocess
import hashlib
import click
import os

def compute_md5(file_path):
    hash_md5 = hashlib.md5()
    try:
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()
    except FileNotFoundError:
        return None

def verify_appimage(appimage_path, expected_md5):
    if not expected_md5:
        click.echo("Warning: No MD5 checksum provided in config. Skipping verification.")
        return True
    current_md5 = compute_md5(appimage_path)
    if not current_md5:
        click.echo(f"Error: AppImage '{appimage_path}' not found.")
        return False
    if current_md5 != expected_md5:
        click.echo(f"Error: AppImage checksum mismatch. Expected: {expected_md5}, Got: {current_md5}")
        return False
    click.echo("AppImage checksum verified successfully.")
    return True

def execute_commands(commands, description="Executing commands"):
    if not commands:
        return
    click.echo(f"{description}...")
    for cmd in commands:
        click.echo(f"Running: {cmd}")
        try:
            subprocess.run(cmd, shell=True, check=True)
        except subprocess.CalledProcessError as e:
            click.echo(f"Error running command '{cmd}': {e}")

def manage_services(config, persistent=False):
    service_enable_commands = {
        "ethernet": ["sudo systemctl enable networking", "sudo systemctl start networking"],
        "serial": ["sudo systemctl enable getty@ttyAMA0", "sudo systemctl start getty@ttyAMA0"],
        "i2c": ["sudo modprobe i2c-dev"],
        "vnc": ["sudo systemctl enable vncserver-x11-serviced", "sudo systemctl start vncserver-x11-serviced"],
        "rtc": ["sudo modprobe i2c-rtc", "sudo hwclock --systohc --rtc=/dev/rtc0"],
        "bluetooth": ["sudo systemctl enable bluetooth", "sudo systemctl start bluetooth"],
        "wifi": ["sudo systemctl enable wpa_supplicant", "sudo systemctl start wpa_supplicant"]
    }
    service_disable_commands = {
        "ethernet": ["sudo systemctl disable networking", "sudo systemctl stop networking"],
        "serial": ["sudo systemctl disable getty@ttyAMA0", "sudo systemctl stop getty@ttyAMA0"],
        "i2c": ["sudo modprobe -r i2c-dev"],
        "vnc": ["sudo systemctl disable vncserver-x11-serviced", "sudo systemctl stop vncserver-x11-serviced"],
        "rtc": ["sudo modprobe -r i2c-rtc"],
        "bluetooth": ["sudo systemctl disable bluetooth", "sudo systemctl stop bluetooth"],
        "wifi": ["sudo systemctl disable wpa_supplicant", "sudo systemctl stop wpa_supplicant"]
    }

    if config["kiosk_mode"]:
        click.echo("Configuring services for kiosk mode...")
        for service, enabled in config["services"].items():
            commands = service_enable_commands[service] if enabled else service_disable_commands[service]
            if persistent:
                commands = [cmd.replace("start", "enable" if enabled else "disable").replace("stop", "disable" if enabled else "enable") for cmd in commands]
            execute_commands(commands, f"{'Enabling' if enabled else 'Disabling'} {service}")
    else:
        click.echo("Restoring services to default state...")
        # When disabling kiosk mode, restore all services to their default state
        # This ensures a clean desktop environment
        default_services = {
            "ethernet": True,
            "serial": False,
            "i2c": True,
            "vnc": False,
            "rtc": True,
            "bluetooth": False,
            "wifi": False
        }
        
        for service, enabled in default_services.items():
            commands = service_enable_commands[service] if enabled else service_disable_commands[service]
            if persistent:
                commands = [cmd.replace("start", "enable" if enabled else "disable").replace("stop", "disable" if enabled else "enable") for cmd in commands]
            execute_commands(commands, f"{'Enabling' if enabled else 'Disabling'} {service} (default state)")

def hide_mouse():
    try:
        subprocess.run("unclutter -idle 0 &", shell=True, check=True)
        click.echo("Mouse pointer hidden.")
    except subprocess.CalledProcessError as e:
        click.echo(f"Error hiding mouse pointer: {e}")

def execute_pre_launch(config):
    execute_commands(config["pre_launch_commands"], "Running pre-launch commands")

def launch_appimage(appimage_path, kiosk_mode):
    cmd = [appimage_path]
    # Always add --no-sandbox for kiosk mode on Raspberry Pi
    cmd.append("--no-sandbox")
    if kiosk_mode:
        # Force full-screen kiosk mode
        cmd.extend(["--kiosk", "--start-fullscreen", "--fullscreen"])
    try:
        click.echo(f"Launching: {' '.join(cmd)}")
        subprocess.run(cmd, check=True)
    except subprocess.CalledProcessError as e:
        click.echo(f"Error launching AppImage: {e}")