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

# ============================================================
# CONFIGURACIÓN LOG
# ============================================================
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(texto):
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(texto + "\n")

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

# ============================================================
# DETECCIÓN DE CARPETAS OCULTAS / SISTEMA
# ============================================================
FILE_ATTRIBUTE_HIDDEN = 0x02
FILE_ATTRIBUTE_SYSTEM = 0x04

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

# ============================================================
# PROCESO PRINCIPAL
# ============================================================
def procesar_jpgs(carpeta):
    procesados = 0
    errores = 0
    omitidos = 0

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

    write_log("\n" + "=" * 70)
    write_log(f"INICIO PROCESO: {inicio}")
    write_log(f"CARPETA RAÍZ: {carpeta}")
    write_log("=" * 70)

    log(f"📂 Carpeta seleccionada: {carpeta}")
    log("-" * 70)

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

        # FILTRAR CARPETAS PROTEGIDAS / OCULTAS
        carpetas_originales = dirs[:]
        dirs[:] = []

        for d in carpetas_originales:
            ruta_completa = os.path.join(root_dir, d)

            if d.lower() == "[originals]":
                log(f"⏭ OMITIDA [Originals]: {ruta_completa}")
                omitidos += 1
                continue

            if es_carpeta_oculta(ruta_completa):
                log(f"⏭ OMITIDA (oculta/sistema): {ruta_completa}")
                omitidos += 1
                continue

            dirs.append(d)

        # PROCESAR ARCHIVOS
        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"⚠️ ARCHIVO NO EXISTE: {path}")
                errores += 1
                continue

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

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

            except PermissionError:
                log(f"⛔ BLOQUEADO (permisos/en uso): {path}")
                omitidos += 1

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

    log("-" * 70)
    log(f"✔ JPG procesados : {procesados}")
    log(f"⏭ Omitidos        : {omitidos}")
    log(f"❌ Errores        : {errores}")

    fin = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    write_log(f"FIN PROCESO: {fin}")
    write_log("=" * 70)

    messagebox.showinfo(
        "Proceso terminado",
        f"JPG procesados: {procesados}\n"
        f"Omitidos: {omitidos}\n"
        f"Errores: {errores}\n\n"
        f"Se ha creado log.txt"
    )

# ============================================================
# INTERFAZ GRÁFICA
# ============================================================
def seleccionar_carpeta():
    consola.delete(1.0, tk.END)
    carpeta = filedialog.askdirectory()
    if carpeta:
        procesar_jpgs(carpeta)

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

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

boton = tk.Button(
    root,
    text="Seleccionar carpeta y convertir",
    command=seleccionar_carpeta
)
boton.pack(pady=5)

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

root.mainloop()
