import os
import shutil
from datetime import datetime
import google.generativeai as genai
import PIL.Image

# --------------------- CONFIGURATION ---------------------
# Utilisation de r"" pour les chemins Windows
photo_folder = r"C:\Users\Antoine\PycharmProjects\PHOTO\photo a organiser"
dossier_folder = r"C:\Users\Antoine\PycharmProjects\PHOTO\dossier"

# REMPLACER PAR VOTRE NOUVELLE CLÉ
genai.configure(api_key="AIzaSyDq2LmX_fwKGAwxGAtmBfX940vT2wDQzBU")
for m in genai.list_models():
    if 'generateContent' in m.supported_generation_methods:
        print(m.name)
model = genai.GenerativeModel('models/gemini-2.5-flash') # 1.5 est plus stable pour l'OCR

if not os.path.exists(dossier_folder):
    os.makedirs(dossier_folder)

# --------------------- FONCTIONS ---------------------
def get_time_from_filename(filename):
    try:
        # Supposant un format : QuelqueChose_123045.jpg (HHMMSS)
        base = os.path.splitext(filename)[0]
        parts = base.split("_")
        time_part = parts[1] 
        return datetime.strptime(time_part, "%H%M%S")
    except Exception as e:
        return None

def read_barcode(photo_path):
    try:
        # Utiliser 'with' permet de fermer l'image AUTOMATIQUEMENT après la lecture
        with PIL.Image.open(photo_path) as img:
            response = model.generate_content([
                "Retourne uniquement le texte ou les chiffres du code-barre. "
                "Si aucun code-barre n'est visible, répond 'inconnu'.", 
                img
            ])
            return response.text.strip().replace(" ", "")
    except Exception as e:
        print(f"Erreur lors de la lecture : {e}")
        return "erreur_lecture"
# --------------------- TRAITEMENT ---------------------
photos_raw = [f for f in os.listdir(photo_folder) if f.lower().endswith(".jpg")]
photo_times = []

for photo in photos_raw:
    time_obj = get_time_from_filename(photo)
    if time_obj:
        photo_times.append((photo, time_obj))

photo_times.sort(key=lambda x: x[1])

groups = []
for photo, time_obj in photo_times:
    full_path = os.path.join(photo_folder, photo)
    
    if not groups:
        barcode = read_barcode(full_path)
        groups.append({"photos": [photo], "reference_time": time_obj, "barcode": barcode})
    else:
        current_group = groups[-1]
        # Comparaison avec la dernière photo ajoutée pour plus de souplesse
        difference = abs((time_obj - current_group["reference_time"]).total_seconds())
        
        if difference <= 60:
            current_group["photos"].append(photo)
        else:
            barcode = read_barcode(full_path)
            groups.append({"photos": [photo], "reference_time": time_obj, "barcode": barcode})

# --------------------- DÉPLACEMENT ---------------------
for i, group in enumerate(groups, start=1):
    barcode = group["barcode"]
    # Nettoyage pour nom de dossier Windows valide
    barcode_clean = "".join(c for c in barcode if c.isalnum() or c in "-_").strip()
    
    # Format demandé : 1_CodeBarre
    folder_name = f"{i}_{barcode_clean}" if barcode_clean else str(i)
    group_folder = os.path.join(dossier_folder, folder_name)
    
    os.makedirs(group_folder, exist_ok=True)
    
    for photo in group["photos"]:
        src = os.path.join(photo_folder, photo)
        dst = os.path.join(group_folder, photo)
        shutil.move(src, dst)

print("\nRegroupement et déplacement terminés !")