import os
import ctypes
import sys
from datetime import datetime
from PIL import Image
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter.scrolledtext import ScrolledText

# ============================================================
# LOG CONFIGURATION
# ============================================================
if getattr(sys, 'frozen', False):
    BASE_DIR = os.path.dirname(sys.executable)
else:
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))

LOG_FILE = os.path.join(BASE_DIR, "log.txt")

def write_log(text):
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(text + "\n")

def log(text):
    console.insert(tk.END, text + "\n")
    console.see(tk.END)
    root.update_idletasks()
    write_log(text)

# ============================================================
# HIDDEN / SYSTEM FOLDER DETECTION
# ============================================================
FILE_ATTRIBUTE_HIDDEN = 0x02
FILE_ATTRIBUTE_SYSTEM = 0x04

def is_hidden_folder(path):
    try:
        attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
        if attrs == -1:
            return False
        return bool(attrs & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM))
    except:
        return False

# ============================================================
# MAIN PROCESS
# ============================================================
def process_jpgs(folder):
    processed = 0
    errors = 0
    skipped = 0

    start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    write_log("\n" + "=" * 70)
    write_log(f"PROCESS START: {start_time}")
    write_log(f"ROOT FOLDER: {folder}")
    write_log("=" * 70)

    log(f"📂 Selected folder: {folder}")
    log("-" * 70)

    for root_dir, dirs, files in os.walk(folder):

        # FILTER PROTECTED / HIDDEN FOLDERS
        original_dirs = dirs[:]
        dirs[:] = []

        for d in original_dirs:
            full_path = os.path.join(root_dir, d)

            if d.lower() == "[originals]":
                log(f"⏭ SKIPPED [Originals]: {full_path}")
                skipped += 1
                continue

            if is_hidden_folder(full_path):
                log(f"⏭ SKIPPED (hidden/system): {full_path}")
                skipped += 1
                continue

            dirs.append(d)

        # PROCESS FILES
        for file in files:
            if not file.lower().endswith((".jpg", ".jpeg")):
                continue

            path = os.path.normpath(os.path.join(root_dir, file))

            if not os.path.isfile(path):
                log(f"⚠️ FILE DOES NOT EXIST: {path}")
                errors += 1
                continue

            try:
                with Image.open(path) as img:
                    img = img.convert("RGB")
                    img.save(
                        path,
                        format="JPEG",
                        quality=100,
                        subsampling=0,
                        optimize=False
                    )

                processed += 1
                log(f"✔ OK : {path}")

            except PermissionError:
                log(f"⛔ BLOCKED (permissions/in use): {path}")
                skipped += 1

            except Exception as e:
                log(f"❌ ERROR: {path} -> {e}")
                errors += 1

    log("-" * 70)
    log(f"✔ JPG processed : {processed}")
    log(f"⏭ Skipped       : {skipped}")
    log(f"❌ Errors        : {errors}")

    end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    write_log(f"PROCESS END: {end_time}")
    write_log("=" * 70)

    messagebox.showinfo(
        "Process finished",
        f"JPG processed: {processed}\n"
        f"Skipped: {skipped}\n"
        f"Errors: {errors}\n\n"
        f"log.txt has been created"
    )

# ============================================================
# GRAPHICAL INTERFACE
# ============================================================
def select_folder():
    console.delete(1.0, tk.END)
    folder = filedialog.askdirectory()
    if folder:
        process_jpgs(folder)

root = tk.Tk()
root.title("Reprocess JPG (Omnibussimulator 2)")
root.geometry("900x500")
root.resizable(True, True)

title_label = tk.Label(
    root,
    text="Reprocess JPG (Omnibussimulator 2) - by Rafaelkaiz",
    font=("Segoe UI", 12)
)
title_label.pack(pady=5)

button = tk.Button(
    root,
    text="Select folder and convert",
    command=select_folder
)
button.pack(pady=5)

console = ScrolledText(
    root,
    font=("Consolas", 9)
)
console.pack(expand=True, fill="both", padx=10, pady=5)

root.mainloop()