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

# --------------------- CONFIGURATION lol ---------------------
photo_folder = r"C:\Users\Antoine\PycharmProjects\PHOTO\photo a organiser"
dossier_folder = r"C:\Users\Antoine\PycharmProjects\PHOTO\dossier"

genai.configure(api_key="AIzaSyDq2LmX_fwKGAwxGAtmBfX940vT2wDQzBU")
model = genai.GenerativeModel('models/gemini-2.5-flash') 

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

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

def analyze_group_photos(group_paths):
    """
    Envoie les images et demande de lier les valeurs aux noms de fichiers.
    """
    prompt = (
        "Analyze these images one by one. For each image, if you see a 6-character Barcode "
        "or a 5-character LCLC, identify it.\n"
        "Return the results in this exact format for each relevant file:\n"
        "FILENAME: [filename], TYPE: [BARCODE or LCLC], VALUE: [value]\n"
        "If a file has nothing, don't list it."
    )
    
    content = [prompt]
    
    # On ouvre les images (avec gestion de fermeture automatique)
    images_to_close = []
    for path in group_paths:
        img = PIL.Image.open(path)
        content.append(f"Filename: {os.path.basename(path)}")
        content.append(img)
        images_to_close.append(img)

    try:
        # Note: Utilisez 'gemini-1.5-flash' car 2.5 n'existe pas encore
        response = model.generate_content(content)
        res_text = response.text
        print(f"--- Gemini Analysis ---\n{res_text}\n-----------------------")
        
        # Fermeture des images pour libérer les fichiers
        for i in images_to_close: i.close()
        
        return res_text
    except Exception as e:
        print(f"Error calling Gemini: {e}")
        return ""

# --------------------- TRAITEMENT ---------------------
photos_raw = [f for f in os.listdir(photo_folder) if f.lower().endswith((".jpg", ".jpeg", ".png"))]
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:
    if not groups:
        groups.append({"photos": [photo], "reference_time": time_obj})
    else:
        current_group = groups[-1]
        difference = abs((time_obj - current_group["reference_time"]).total_seconds())
        if difference <= 60:
            current_group["photos"].append(photo)
            current_group["reference_time"] = time_obj
        else:
            groups.append({"photos": [photo], "reference_time": time_obj})

# --------------------- ANALYSE ET RENOMMAGE ---------------------
for i, group in enumerate(groups, start=1):
    print(f"Analyzing Group {i}...")
    group_paths = [os.path.join(photo_folder, p) for p in group["photos"]]
    analysis_result = analyze_group_photos(group_paths)
    
    group_folder_path = os.path.join(dossier_folder, str(i))
    os.makedirs(group_folder_path, exist_ok=True)

    # Créer un dictionnaire pour mapper Filename -> NouveauNom
    # Exemple: {"IMG_123.jpg": "ABC123.jpg"}
    filename_mapping = {}
    
    # Parsing de la réponse de Gemini
    for line in analysis_result.splitlines():
        if "FILENAME:" in line and "VALUE:" in line:
            try:
                fname = line.split("FILENAME:")[1].split(",")[0].strip()
                vtype = line.split("TYPE:")[1].split(",")[0].strip()
                val = line.split("VALUE:")[1].strip()
                
                # On vérifie la validité des données
                if (vtype == "BARCODE" and len(val) == 6) or (vtype == "LCLC" and len(val) == 5):
                    filename_mapping[fname] = val
            except:
                continue

    for photo_name in group["photos"]:
        src_path = os.path.join(photo_folder, photo_name)
        extension = os.path.splitext(photo_name)[1]
        
        # On vérifie si Gemini a trouvé une valeur spécifique pour CE fichier
        if photo_name in filename_mapping:
            new_name = f"{filename_mapping[photo_name]}{extension}"
        else:
            # Sinon on garde le nom original
            new_name = photo_name

        dst_path = os.path.join(group_folder_path, new_name)

        # Gestion des doublons (si deux photos ont le même code)
        counter = 1
        base_name = os.path.splitext(new_name)[0]
        while os.path.exists(dst_path):
            dst_path = os.path.join(group_folder_path, f"{base_name}_{counter}{extension}")
            counter += 1
            
        shutil.move(src_path, dst_path)