import os
from tkinter import Tk, filedialog, Button, Label
from PIL import Image
import pillow_heif

# Enable HEIF support in Pillow
pillow_heif.register_heif_opener()

def convert_heif_to_jpg_gui(input_folder, output_folder):
    os.makedirs(output_folder, exist_ok=True)

    for filename in os.listdir(input_folder):
        if filename.lower().endswith(('.heic', '.heif')):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, os.path.splitext(filename)[0] + '.jpg')
            try:
                with Image.open(input_path) as img:
                    rgb_img = img.convert("RGB")
                    rgb_img.save(output_path, "JPEG")
                print(f"Converted: {filename}")
            except Exception as e:
                print(f"Failed to convert {filename}: {e}")

def browse_input():
    folder = filedialog.askdirectory(title="Select Input Folder (HEIF images)")
    if folder:
        input_label.config(text=folder)
        app.input_folder = folder

def browse_output():
    folder = filedialog.askdirectory(title="Select Output Folder (JPG images)")
    if folder:
        output_label.config(text=folder)
        app.output_folder = folder

def convert():
    if hasattr(app, "input_folder") and hasattr(app, "output_folder"):
        convert_heif_to_jpg_gui(app.input_folder, app.output_folder)
        status_label.config(text="✅ Conversion complete!")
    else:
        status_label.config(text="❗ Please select both folders first.")

# GUI Setup
app = Tk()
app.title("HEIF to JPG Converter")
app.geometry("500x200")

Button(app, text="Select HEIF Input Folder", command=browse_input).pack(pady=5)
input_label = Label(app, text="No input folder selected")
input_label.pack()

Button(app, text="Select JPG Output Folder", command=browse_output).pack(pady=5)
output_label = Label(app, text="No output folder selected")
output_label.pack()

Button(app, text="Convert HEIF to JPG", command=convert).pack(pady=10)
status_label = Label(app, text="")
status_label.pack()

app.mainloop()
