Fix this output path is used prior to global acceleration  here is code import ttkbootstrap as tb
from ttkbootstrap.constants import *
from tkinter import filedialog, messagebox
import os
import threading
import psutil
import sys

# Initialize the main window
root = tb.Window(themename="cosmo")  # You can choose any ttkbootstrap theme you like
root.title("DeepAscension Video2Image+")
root.geometry("800x600")  # Set the desired window size

# Define any global variables you might be using
input_folders = []
input_videos = []
output_folder = ""
disk_space_threshold_mb = 500  # Example default value
DISK_CHECK_INTERVAL = 5000  # in milliseconds
stop_all_event = threading.Event()
errors = []
is_paused = False
output_folder_var = tb.StringVar()

# Define your UI components here
# Example placeholders for UI components like treeview, progress bar, etc.
# Replace these with your actual UI setup code
frame = tb.Frame(root)
frame.pack(fill=BOTH, expand=True)

# Example Treeview (you may already have one)
from ttkbootstrap import Treeview

tree = Treeview(frame, columns=("Path", "Type", "Status"), show='headings')
tree.heading("Path", text="Path")
tree.heading("Type", text="Type")
tree.heading("Status", text="Status")
tree.pack(fill=BOTH, expand=True, padx=10, pady=10)

# Example Progress Bar and Status Label
progress_bar = tb.Progressbar(root, mode='indeterminate')
progress_bar.pack(fill=X, padx=10, pady=5)

status_label = tb.Label(root, text="Ready")
status_label.pack(fill=X, padx=10, pady=5)

def on_closing():
    """Handle window closing to ensure all threads are properly terminated."""
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        stop_all_event.set()
        root.destroy()

def select_input_folders():
    """Allow user to select multiple input folders."""
    while True:
        folder = filedialog.askdirectory(title="Select Input Folder (Cancel to finish)")
        if folder:
            if folder not in input_folders and folder not in input_videos:
                input_folders.append(folder)
                tree.insert('', 'end', iid=folder, values=(folder, "Folder", "Pending"))
            else:
                messagebox.showwarning("Duplicate Entry", f"The entry '{folder}' is already selected.")
        else:
            break

def select_input_videos():
    """Allow user to select multiple video files."""
    files = filedialog.askopenfilenames(
        title="Select Video Files",
        filetypes=[("Video Files", "*.mp4 *.avi *.mov *.mkv *.flv *.wmv")]
    )
    for file in files:
        if file not in input_videos and file not in input_folders:
            input_videos.append(file)
            tree.insert('', 'end', iid=file, values=(file, "Video File", "Pending"))
        else:
            messagebox.showwarning("Duplicate Entry", f"The file '{file}' is already selected.")

def select_output_folder():
    """Allow user to select an output folder and set the output_folder_var."""
    folder = filedialog.askdirectory(title="Select Output Folder")
    if folder:
        output_folder_var.set(folder)
        global output_folder
        output_folder = folder
        # Update UI elements that display the output folder
        if 'output_label' in globals():
            output_label.config(text=folder)
        else:
            global output_label
            output_label = tb.Label(root, text=f"Output Folder: {folder}")
            output_label.pack(pady=5)

def process_videos():
    """Main function to process videos and folders."""
    if not input_folders and not input_videos:
        messagebox.showerror("Error", "Please select at least one input folder or video file.")
        set_buttons_state(NORMAL)
        return
    if not output_folder_var.get():
        messagebox.showerror("Error", "Please select an output folder.")
        set_buttons_state(NORMAL)
        return
    # Start processing in a separate thread to avoid blocking the UI
    processing_thread = threading.Thread(target=run_processing)
    processing_thread.start()

def run_processing():
    """Run the actual video processing."""
    set_buttons_state(DISABLED)
    progress_bar.start()
    status_label.config(text="Processing...")
    
    # Placeholder for processing logic
    # Replace this with your actual processing code
    try:
        # Simulate processing with sleep
        import time
        for i in range(5):
            if stop_all_event.is_set():
                raise Exception("Processing stopped by user.")
            time.sleep(1)
            status_label.config(text=f"Processing... {int((i+1)/5*100)}%")
        # Simulate completion
        finalize_processing()
    except Exception as e:
        errors.append(str(e))
        finalize_processing()

def set_disk_threshold():
    """Set the disk space threshold for auto-pausing."""
    try:
        value = int(disk_threshold_entry.get())
        if value <= 0:
            raise ValueError
        global disk_space_threshold_mb
        disk_space_threshold_mb = value
        messagebox.showinfo("Threshold Set", f"Auto-pause threshold set to {value} MB.")
    except ValueError:
        messagebox.showerror("Invalid Input", "Please enter a valid positive integer for the disk space threshold.")

def finalize_processing():
    """Finalize the processing by updating the UI and displaying any errors."""
    set_buttons_state(NORMAL)
    progress_bar.stop()
    if errors:
        error_message = "\n\n".join(errors)
        messagebox.showerror("Processing Completed with Errors", error_message)
    else:
        messagebox.showinfo("Success", "All videos have been successfully processed.")
    progress_bar['value'] = 0
    status_label.config(text="Processing completed.")

def monitor_disk_space():
    """Monitor disk space and auto-pause if below threshold."""
    if stop_all_event.is_set():
        return

    output_path = output_folder_var.get()
    if not output_path:
        # If output path is not set, skip checking
        root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
        return

    try:
        usage = psutil.disk_usage(output_path)
        total = usage.total
        used = usage.used
        free = usage.free
        percent = usage.percent

        # Debugging: Print disk usage details
        # print(f"Disk Usage for '{output_path}': Total={total}, Used={used}, Free={free}, Percent={percent}")

        if free < disk_space_threshold_mb * 1024 * 1024:
            global is_paused
            if not is_paused:
                on_pause()
                is_paused = True
                messagebox.showwarning("Auto-Pause", "Disk space below threshold. Processing has been paused.")
    except Exception as e:
        messagebox.showerror("Disk Space Error", f"Unable to determine disk space for '{output_path}'.\nError: {e}")
    if not stop_all_event.is_set():
        root.after(DISK_CHECK_INTERVAL, monitor_disk_space)

def on_pause():
    """Handle pause action."""
    global is_paused
    # Implement your pause functionality here
    is_paused = True
    # Example: Update status
    status_label.config(text="Processing paused due to low disk space.")

def on_resume():
    """Handle resume action."""
    global is_paused
    # Implement your resume functionality here
    is_paused = False
    # Example: Update status
    status_label.config(text="Processing resumed.")
    # Restart disk monitoring if paused
    monitor_disk_space()

def set_buttons_state(state):
    """Enable or disable buttons during processing."""
    for widget in frame.winfo_children():
        if isinstance(widget, tb.Button):
            widget.config(state=state)
    # Also control other buttons if necessary

# Register the on_closing function to handle window close event
root.protocol("WM_DELETE_WINDOW", on_closing)

# Optionally, start monitoring disk space after the main loop starts
root.after(1000, monitor_disk_space)  # Start after 1 second

# Add UI Components for selecting input folders, videos, output folder, and setting disk threshold
controls_frame = tb.Frame(root)
controls_frame.pack(pady=10)

select_folders_button = tb.Button(controls_frame, text="Select Input Folders", command=select_input_folders)
select_folders_button.grid(row=0, column=0, padx=5)

select_videos_button = tb.Button(controls_frame, text="Select Input Videos", command=select_input_videos)
select_videos_button.grid(row=0, column=1, padx=5)

output_button = tb.Button(controls_frame, text="Select Output Folder", command=select_output_folder)
output_button.grid(row=0, column=2, padx=5)

process_button = tb.Button(root, text="Process", command=process_videos)
process_button.pack(pady=10)

disk_threshold_label = tb.Label(root, text="Disk Space Threshold (MB):")
disk_threshold_label.pack(pady=5)

disk_threshold_entry = tb.Entry(root, textvariable=tb.StringVar(value=str(disk_space_threshold_mb)))
disk_threshold_entry.pack(pady=5)

set_threshold_button = tb.Button(root, text="Set Threshold", command=set_disk_threshold)
set_threshold_button.pack(pady=10)

# Run the GUI loop
root.mainloop()