import os
import shutil
import ctypes
import subprocess
import sys
import time

def is_system_account():
    """
    Check if the script is running as the SYSTEM account.
    """
    return os.environ.get("USERNAME") == "SYSTEM"

def stop_processes():
    """
    Stops processes that might lock files (Edge and OneDrive).
    """
    processes_to_kill = ["msedge.exe", "OneDrive.exe"]
    for process in processes_to_kill:
        try:
            subprocess.call(["taskkill", "/f", "/im", process], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            print("Stopped process: {0}".format(process))
        except Exception as e:
            print("Failed to stop process: {0}: {1}".format(process, e))

def delete_folder_contents(folder_path):
    """
    Delete files and subdirectories in the folder, handling locked files.
    """
    for root, dirs, files in os.walk(folder_path, topdown=False):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                os.remove(file_path)
            except Exception as e:
                print("Failed to delete file: {0}: {1}".format(file_path, e))
        for dir in dirs:
            dir_path = os.path.join(root, dir)
            try:
                os.rmdir(dir_path)
            except Exception as e:
                print("Failed to delete directory: {0}: {1}".format(dir_path, e))

def retry_delete_folder(folder_path, retries=3, delay=5):
    """
    Tries to delete the folder and its contents with retries on failure.
    :param folder_path: Path to the folder to delete
    :param retries: Number of retries
    :param delay: Delay between retries (in seconds)
    """
    attempt = 0
    while attempt < retries:
        try:
            delete_folder_contents(folder_path)
            print("Deleted folder: {0}".format(folder_path))
            return  # Exit if deletion is successful
        except Exception as e:
            print("Attempt {0} failed to delete {1}: {2}".format(attempt + 1, folder_path, e))
            attempt += 1
            if attempt < retries:
                print("Retrying in {0} seconds...".format(delay))
                time.sleep(delay)  # Wait before retrying
            else:
                print("Exceeded maximum retries. Moving on to the next folder.")

def delete_folders():
    """
    Deletes the 'Edge' and 'OneDrive' folders for all users under C:\Users\<user>\AppData\Local\Microsoft.
    """
    # Path to the Users directory
    users_path = "C:\\Users"
    folders_to_delete = ["Edge", "OneDrive"]
    base_path = "AppData\\Local\\Microsoft"

    # Iterate through all user directories in C:\Users
    for user in os.listdir(users_path):
        user_path = os.path.join(users_path, user)
        if os.path.isdir(user_path):
            for folder in folders_to_delete:
                folder_path = os.path.join(user_path, base_path, folder)
                if os.path.exists(folder_path):
                    retry_delete_folder(folder_path)

if __name__ == "__main__":
    # Check for elevated privileges
    try:
        is_admin = ctypes.windll.shell32.IsUserAnAdmin()
    except:
        is_admin = False

    if not is_admin:
        print("This script must be run with Administrator privileges.")
        sys.exit(1)

    # Stop any processes that might lock the files (Edge, OneDrive)
    print("Stopping processes...")
    stop_processes()

    # Give the system a moment to release file locks after stopping processes
    time.sleep(5)

    # Run the folder deletion
    print("Deleting folders...")
    delete_folders()
