"""
PATCH DE COHÉRENCE — À appliquer à tous les generate_book_X.py existants
=========================================================================
3 modifications seulement dans chaque script :
  1. Réorganiser le dict REFS  → personnages EN PREMIER
  2. Ajouter CHARACTER_MAPPING + LOCK_PHRASES en constantes
  3. Modifier le bloc `text = (...)` dans generate_page()

=========================================================================
EXEMPLE COMPLET : generate_book_koko.py (avant / après)
=========================================================================
"""

# ─────────────────────────────────────────────────────────────────────────────
# 1. RÉORGANISER REFS — personnages toujours en tête du dict
# ─────────────────────────────────────────────────────────────────────────────

# AVANT (generate_book_koko.py)
REFS_AVANT = {
    "koko":   "Koko.png",
    "tree":   "arbre_argenté.png",
    "valley": "vallee_fleur.png",
}

# APRÈS ✅
REFS_APRES_KOKO = {
    # --- PERSONNAGE (Image 0) en premier ---
    "koko":   "Koko.png",           # Image 0 -> Character 1
    # --- DÉCORS (Images 1, 2) ---
    "tree":   "arbre_argenté.png",  # Image 1 -> Background A
    "valley": "vallee_fleur.png",   # Image 2 -> Background B
}

# ─────────────────────────────────────────────────────────────────────────────
# 2. AJOUTER CES DEUX CONSTANTES sous PRENOM = "..."
# ─────────────────────────────────────────────────────────────────────────────

CHARACTER_MAPPING_KOKO = (
    "STRICT IDENTITY MAPPING — follow exactly: "
    "Character 1 (KOKO THE KOALA) = Image 0. "
    "Background references = Images 1 and 2. "
)

LOCK_PHRASES = (
    "Maintain strict facial likeness of every character as shown in their reference image. "
    "Ensure character structure, clothing colors, and hair style remain 100% identical to the reference sheet. "
    "Do not alter character proportions or anatomy. "
)

# ─────────────────────────────────────────────────────────────────────────────
# 3. REMPLACER LE BLOC text = (...) dans generate_page()
# ─────────────────────────────────────────────────────────────────────────────

# AVANT (generate_book_koko.py) — supprimer ce bloc :
TEXT_AVANT = (
    "Use ALL reference images to maintain EXACT visual consistency across every scene. "
    "Ref 1 - KOKO THE KOALA: ..."
    # ...
)

# APRÈS ✅ — remplacer par :
TEXT_APRES_KOKO = (
    CHARACTER_MAPPING_KOKO
    + LOCK_PHRASES
    + "Reference descriptions for extra clarity — "
    + "Image 0 = KOKO THE KOALA: small fluffy grey koala, big round ears with soft white fur inside, "
      "big dark expressive eyes, small black nose, wearing a teal-turquoise explorer vest with brown "
      "leather pockets and pencils sticking out, friendly and wise expression. "
    + "Image 1 = L'ARBRE DES CONFIDENCES: enormous ancient tree with shimmering silver metallic leaves, "
      "hanging light strands, mossy roots, gentle stream nearby, peaceful magical atmosphere. "
    + "Image 2 = LA VALLEE DES ECHOS: magical canyon with swirling red-brown rock walls, glowing "
      "bell-shaped flowers in purple orange blue and green, shimmering stream, light rays from above. "
    # + f"CHILD CHARACTER {PRENOM}: ..."  <- garder la description du child perso
    # + "Now generate: " + full_prompt    <- garder la fin
)

# ─────────────────────────────────────────────────────────────────────────────
# MAPPINGS POUR CHAQUE SCRIPT EXISTANT
# ─────────────────────────────────────────────────────────────────────────────

MAPPINGS = {

    "generate_book_fifi.py": {
        "refs_order": ["fifi", "island", "lagoon"],
        "mapping": (
            "STRICT IDENTITY MAPPING — follow exactly: "
            "Character 1 (FIFI THE FLAMINGO) = Image 0. "
            "Background A (L'ILE DE LA VITALITE) = Image 1. "
            "Background B (LE LAGON DES BULLES) = Image 2. "
        ),
        "descriptions": {
            "Image 0": "FIFI THE FLAMINGO: bright pink fluffy feathers, white wing tips, curved orange-brown beak, big expressive green eyes with long lashes, small yellow floral headband, elegant long pink legs.",
            "Image 1": "L'ILE DE LA VITALITE: vibrant magical tropical island, colorful glowing gemstone fruits on trees, crystal clear turquoise water, white sandy beach, lush palm trees, blue sky.",
            "Image 2": "LE LAGON DES BULLES: warm magical pool, mossy rocks, tropical plants, giant iridescent soap bubbles floating, rainbow visible, warm mist.",
        }
    },

    "generate_book_plumi.py": {
        "refs_order": ["plumi", "valley", "cave"],
        "mapping": (
            "STRICT IDENTITY MAPPING — follow exactly: "
            "Character 1 (PLUMI THE FEATHERED DINOSAUR) = Image 0. "
            "Background A (LA VALLEE DES GEANTS) = Image 1. "
            "Background B (LA GROTTE DE CRISTAL) = Image 2. "
        ),
        "descriptions": {
            "Image 0": "PLUMI THE DINOSAUR: small round chubby body covered entirely in soft fluffy orange and blue feathers, cream-white belly feathers, big golden-amber eyes, small yellow beak, blue feather crest on head, tiny clawed feet, NO scales — all feathers.",
            "Image 1": "LA VALLEE DES GEANTS: lush prehistoric jungle valley, giant ferns, tropical flowers, volcanic mountain in background, golden sunbeams, prehistoric blue dragonflies.",
            "Image 2": "LA GROTTE DE CRISTAL: magical cave with glowing blue crystals, cave paintings of prehistoric animals on warm golden-orange walls, central campfire glow, purple-blue sparkles.",
        }
    },

    "generate_book_pipo.py": {
        "refs_order": ["pipo", "parent", "palace", "plaza"],
        "mapping": (
            "STRICT IDENTITY MAPPING — follow exactly: "
            "Character 1 (PIPO THE PARROT) = Image 0. "
            "Character 2 (THE PARENT WOMAN) = Image 1. "
            "Background A (LE PALAIS DES ECHOS) = Image 2. "
            "Background B (LA PLACE DES SOURIRES) = Image 3. "
        ),
        "descriptions": {
            "Image 0": "PIPO THE PARROT: small round chubby body, bright green head and crest, yellow face with orange beak, rainbow-colored wings from green to blue to purple, red bow-tie at neck, big warm brown eyes.",
            "Image 1": "THE PARENT WOMAN: brown hair in an updo bun, warm kind eyes, sage green knitted sweater over white shirt, blue jeans, brown ankle boots, gold necklace with heart pendant.",
            "Image 2": "LE PALAIS DES ECHOS: magical purple palace interior, grand staircases with golden railings, floating glowing letters and words, chandeliers, blue starry atmosphere.",
            "Image 3": "LA PLACE DES SOURIRES: cheerful colorful village square, flower-shaped fountains in pink orange and purple, colorful paving stones, bunting flags, cozy shops, blue sky.",
        }
    },

    "generate_book_koko.py": {
        "refs_order": ["koko", "tree", "valley"],
        "mapping": (
            "STRICT IDENTITY MAPPING — follow exactly: "
            "Character 1 (KOKO THE KOALA) = Image 0. "
            "Background A (L'ARBRE DES CONFIDENCES) = Image 1. "
            "Background B (LA VALLEE DES ECHOS) = Image 2. "
        ),
        "descriptions": {
            "Image 0": "KOKO THE KOALA: small fluffy grey koala, big round ears with white fur inside, big dark expressive eyes, small black nose, teal-turquoise explorer vest with brown leather pockets and pencils sticking out.",
            "Image 1": "L'ARBRE DES CONFIDENCES: enormous ancient tree with shimmering silver metallic leaves, hanging light strands, mossy roots, gentle stream nearby, peaceful magical atmosphere.",
            "Image 2": "LA VALLEE DES ECHOS: magical canyon with swirling red-brown rock walls, glowing bell-shaped flowers in purple orange blue and green, shimmering stream, light rays from above.",
        }
    },

    "generate_book_lulu.py": {
        "refs_order": ["lulu", "cave", "garden"],
        "mapping": (
            "STRICT IDENTITY MAPPING — follow exactly: "
            "Character 1 (LULU THE FIREFLY) = Image 0. "
            "Background A (LA GROTTE AUX ETOILES) = Image 1. "
            "Background B (LE JARDIN DE NUIT) = Image 2. "
        ),
        "descriptions": {
            "Image 0": "LULU THE FIREFLY: small round dark brown body with a glowing warm golden-yellow belly, iridescent lavender-pink wings, big expressive amber-green eyes, tiny beige explorer hat with a small green leaf.",
            "Image 1": "LA GROTTE AUX ETOILES: magical crystal cave with glowing purple pink and blue crystals, deep indigo darkness, sparkling reflections on rock walls.",
            "Image 2": "LE JARDIN DE NUIT: magical nighttime garden, giant glowing blue and purple flowers, moonlight, twinkling firefly lights, stone path.",
        }
    },
}

# ─────────────────────────────────────────────────────────────────────────────
# TEMPLATE generate_page() UNIVERSEL
# Copier-coller ce pattern dans chaque script en adaptant CHARACTER_MAPPING
# et les descriptions d'images.
# ─────────────────────────────────────────────────────────────────────────────

TEMPLATE_GENERATE_PAGE = '''
def generate_page(page_data, style_master, refs, output_dir="pages_X"):
    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}...")

    text = (
        CHARACTER_MAPPING          # <- mapping Image 0, 1, 2...
        + LOCK_PHRASES             # <- verrouillage visage/corps/vetements
        + IMAGE_DESCRIPTIONS       # <- "Image 0 = ..., Image 1 = ..."
        + f"CHILD CHARACTER {PRENOM}: short slightly wavy brown hair, big round brown eyes, "
          f"rosy cheeks, blue denim overalls, yellow t-shirt, white sneakers. Same face every scene. "
        + "Now generate: " + full_prompt
    )

    # Personnages en premier, decors ensuite
    parts = [types.Part(text=text)]
    for key in REFS_ORDER:                      # <- ordre du dict REFS
        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}")
    return None
'''

print("Patch pret. Appliquer les modifications decrites dans MAPPINGS a chaque script.")
print("Ordre d'application recommande : pipo -> koko -> fifi -> plumi -> lulu")
