import os
import json
import time
import random
from pathlib import Path
from google import genai
from google.genai import types

GEMINI_API_KEY = os.environ["GEMINI_API_KEY"]
client = genai.Client(api_key=GEMINI_API_KEY)

# ─────────────────────────────────────────────────────────────────────────────
# ORDRE CRITIQUE : décor principal EN PREMIER (Image 0).
# Léo le renard n'a pas de référence image — cohérence assurée par description.
# ─────────────────────────────────────────────────────────────────────────────
REFS = {
    # --- DÉCOR PRINCIPAL (Image 0) ---
    "garage":  "garage_idee.png",   # Image 0 -> Le Garage à Idées
}

CHARACTER_MAPPING = (
    "STRICT IDENTITY MAPPING — follow exactly: "
    "Background A (LE GARAGE A IDEES) = Image 0. "
    "Use Image 0 as the reference for all workshop interior scenes. "
)

LOCK_PHRASES = (
    "Maintain strict visual consistency of Léo the fox character as described in every scene. "
    "Maintain strict visual consistency of {prenom}'s child character as described in every scene. "
    "Ensure character structure, clothing colors, and expressions remain 100% identical to descriptions. "
    "Do not alter character proportions or anatomy. "
)

IMAGE_DESCRIPTIONS = (
    "Image 0 = LE GARAGE A IDEES: magical inventor's workshop interior, warm wooden walls and floors, "
    "large heavy wooden workbench covered in blueprints and scattered tools, colorful metal gears and cogs "
    "mounted on the blue walls, a round porthole window showing green garden outside, hanging amber "
    "pendant lamp casting warm light, shelves of gadgets and inventions, cozy and creative atmosphere. "
    "Use for all workshop interior scenes (pages 3-9). "
)

PRENOM = "Leo"


def load_references():
    loaded = {}
    for name, path in REFS.items():
        if Path(path).exists():
            loaded[name] = Path(path).read_bytes()
            print(f"Reference chargee : {path}")
        else:
            loaded[name] = None
            print(f"Pas de reference : {path}")
    return loaded


def call_with_retry(parts, max_retries=5):
    for attempt in range(max_retries):
        try:
            return client.models.generate_content(
                model="gemini-3-pro-image-preview",
                contents=parts,
                config=types.GenerateContentConfig(
                    response_modalities=["IMAGE", "TEXT"]
                )
            )
        except Exception as e:
            wait = (2 ** attempt) + random.uniform(0, 2)
            print(f"Tentative {attempt + 1}/{max_retries} echouee : {e}")
            if attempt < max_retries - 1:
                print(f"Attente {wait:.1f}s avant retry...")
                time.sleep(wait)
            else:
                raise


def generate_page(page_data, style_master, refs, output_dir="pages_leo"):
    Path(output_dir).mkdir(exist_ok=True)
    page_num = page_data["page"]
    page_type = page_data["type"]
    prompt = page_data["prompt"].replace("{prenom}", PRENOM)
    output_path = f"{output_dir}/page_{page_num:02d}.png"

    format_instruction = (
        "IMPORTANT: single full square illustration 2362x2362 pixels, no spread, no border, fills entire frame."
        if page_type == "simple"
        else "IMPORTANT: double page spread 4724x2362 pixels, 2:1 ratio, safe center fold, no spine line, fills entire frame."
    )

    full_prompt = style_master + " " + format_instruction + " Scene: " + prompt
    print(f"Page {page_num:02d}...")

    lock = LOCK_PHRASES.replace("{prenom}", PRENOM)

    text = (
        CHARACTER_MAPPING
        + lock
        + IMAGE_DESCRIPTIONS
        + f"CHILD CHARACTER {PRENOM}: short slightly wavy brown hair, big round brown eyes, rosy cheeks, "
          f"blue denim overalls over a yellow t-shirt, white sneakers. Same face and outfit every scene. "
        + "LEO THE FOX: bright vivid orange fur, white muzzle and cream belly, big amber eyes, black nose, "
          "fluffy bushy tail with white tip, round brown leather aviator goggles on forehead (or over eyes "
          "when working), small brown leather tool belt with wrench screwdriver and hammer hanging from it. "
          "Friendly enthusiastic inventor expression. Same design every scene. "
        + "LA PERSEVERANTE FLYING MACHINE: hand-built glider of warm golden wood and brass fittings, "
          "large blue silk wings, spinning wooden rear propeller, open pilot seat with leather headrest, "
          "wooden control levers, elegant and whimsical. Same design every scene from page 9 onward. "
        + "PARENT CHARACTER (page 16 only): sage green knitted sweater, warm kind eyes, loving expression. "
        + "Now generate: " + full_prompt
    )

    # Garage en premier et unique référence image
    parts = [types.Part(text=text)]
    for key in ["garage"]:
        if refs.get(key):
            parts.append(types.Part(
                inline_data=types.Blob(data=refs[key], mime_type="image/png")
            ))

    response = call_with_retry(parts)

    for part in response.candidates[0].content.parts:
        if part.inline_data:
            with open(output_path, "wb") as f:
                f.write(part.inline_data.data)
            print(f"OK : {output_path}")
            return output_path

    print(f"ERREUR page {page_num} : aucune image dans la reponse")
    return None


def generate_book(prompts_file="prompts_leo.json", start_page=1, end_page=None):
    with open(prompts_file, "r", encoding="utf-8") as f:
        data = json.load(f)

    style_master = data["style_master"]
    pages = data["pages"]

    if end_page:
        pages = [p for p in pages if start_page <= p["page"] <= end_page]
    else:
        pages = [p for p in pages if p["page"] >= start_page]

    refs = load_references()

    print(f"Generation : {len(pages)} pages — prenom : {PRENOM}")
    results = []

    for page_data in pages:
        path = generate_page(page_data, style_master, refs)
        results.append({
            "page": page_data["page"],
            "path": path,
            "success": path is not None
        })
        time.sleep(5)

    success = sum(1 for r in results if r["success"])
    print(f"\nTermine : {success}/{len(pages)} pages generees")

    with open("book_leo_results.json", "w") as f:
        json.dump(results, f, indent=2)

    return results


if __name__ == "__main__":
    import sys
    prompts_file = sys.argv[1] if len(sys.argv) > 1 else "prompts_leo.json"
    start = int(sys.argv[2]) if len(sys.argv) > 2 else 1
    end = int(sys.argv[3]) if len(sys.argv) > 3 else None
    generate_book(prompts_file, start, end)
