import os
import json
import time
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)

CHILD_REF_PATH = "enfant-tshirt-etoile.png"
PRENOM = "Leo"


def load_references():
    child = None
    if Path(CHILD_REF_PATH).exists():
        child = Path(CHILD_REF_PATH).read_bytes()
        print(f"Reference enfant chargee : {CHILD_REF_PATH}")
    else:
        print("Pas de reference enfant.")
    return child


def generate_page(page_data, style_master, child_bytes=None, output_dir="pages_habillage"):
    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 illustration 4724x2362 pixels, 2:1 ratio, safe center fold area, no spine line visible, fills entire frame."
    )

    full_prompt = (
        style_master
        + " " + format_instruction
        + " Scene: " + prompt
    )

    print(f"Page {page_num:02d} ({page_type})...")

    if child_bytes:
        text = (
            "Use the reference image to keep the child character EXACTLY consistent in every scene. "
            "Same boy: short dark brown messy hair, round face, brown-hazel eyes, rosy cheeks. "
            "At the start of the story the child wears pajamas, then progressively gets dressed across the pages. "
            "Keep exact same face, hair and proportions in every scene. "
            "Now generate this scene: " + full_prompt
        )
        parts = [types.Part(text=text)]
        parts.append(types.Part(
            inline_data=types.Blob(data=child_bytes, mime_type="image/png")
        ))
        contents = parts
    else:
        contents = [full_prompt]

    response = client.models.generate_content(
        model="gemini-3-pro-image-preview",
        contents=contents,
        config=types.GenerateContentConfig(
            response_modalities=["IMAGE", "TEXT"]
        )
    )

    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} : pas d'image generee")
    return None


def generate_book(prompts_file="prompts_habillage.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]

    child_bytes = load_references()

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

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

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

    with open("book_habillage_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_habillage.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)
