#!/usr/bin/env python3
"""Generate 3 variations of golden microalgae microscopy for Slide 12."""
import os, base64, sys
from pathlib import Path
from google import genai
from google.genai import types

API_KEY = os.environ["GEMINI_API_KEY"]
OUT = Path("/root/.openclaw/workspace/phat-deck-images")
OUT.mkdir(parents=True, exist_ok=True)

client = genai.Client(api_key=API_KEY)

BASE_PROMPT = (
    "Warm golden food photography, bright abundant warm light flooding the scene like golden afternoon sun. "
    "Monochromatic warm palette — everything in gold, cream, amber family. Warm shadows (amber/brown, never cool). "
    "High luminosity, airy, lifted shadows. Clean warm background. Tight hero framing, shallow depth of field. "
    "Subtle warm sheen on all surfaces. Rich saturated warm yellow tones. Quiet luxury, minimal, no decoration. "
    "Vertical 3:4 composition, tight crop. "
    "{subject} "
    "3/4 angle. No cool tones, no blue, no green, no gray shadows, no dark zones, no dark backgrounds. "
    "Warm throughout. No text, no labels."
)

SUBJECT_V1 = (
    "Microalgae cells under fluorescence microscopy, golden lipid droplets visible inside translucent cell walls, "
    "warm amber fluorescence glow, scientific but beautiful — Nikon Small World photomicrography aesthetic "
    "rendered entirely in warm gold palette."
)

SUBJECT_V2 = (
    "Spirulina helical coils and algae filaments under fluorescence microscopy, golden twisting filaments "
    "glowing with warm amber fluorescence, delicate helical structures catching golden light, "
    "scientific but beautiful — Nikon Small World photomicrography aesthetic rendered entirely in warm gold palette."
)

SUBJECT_V3 = SUBJECT_V1  # Same subject, different model

def generate_gemini_flash(prompt: str, output_path: str):
    """Generate with gemini-2.5-flash for image generation."""
    print(f"  Generating with gemini-2.5-flash-image...")
    response = client.models.generate_content(
        model="gemini-2.5-flash-image",
        contents=prompt,
        config=types.GenerateContentConfig(
            response_modalities=["IMAGE", "TEXT"],
        ),
    )
    for part in response.candidates[0].content.parts:
        if part.inline_data and part.inline_data.mime_type.startswith("image/"):
            img_bytes = part.inline_data.data
            Path(output_path).write_bytes(img_bytes)
            print(f"  Saved {output_path} ({len(img_bytes):,} bytes)")
            return True
    print("  No image in response!")
    for part in response.candidates[0].content.parts:
        if part.text:
            print(f"  Text: {part.text[:300]}")
    return False

def generate_imagen(prompt: str, output_path: str):
    """Generate with imagen-4.0-generate-001."""
    print(f"  Generating with imagen-4.0-generate-001...")
    response = client.models.generate_images(
        model="imagen-4.0-generate-001",
        prompt=prompt,
        config=types.GenerateImagesConfig(
            number_of_images=1,
            aspect_ratio="3:4",
            output_mime_type="image/png",
        ),
    )
    if response.generated_images:
        img = response.generated_images[0]
        img_bytes = img.image.image_bytes
        Path(output_path).write_bytes(img_bytes)
        print(f"  Saved {output_path} ({len(img_bytes):,} bytes)")
        return True
    print("  No image generated!")
    return False

# --- V1: Gemini Flash, cell close-up ---
print("=== V1: Gemini Flash - Cell Close-up ===")
p1 = BASE_PROMPT.format(subject=SUBJECT_V1)
ok1 = generate_gemini_flash(p1, str(OUT / "slide12_gold_v1.png"))

# --- V2: Gemini Flash, spirulina filaments ---
print("\n=== V2: Gemini Flash - Spirulina Filaments ===")
p2 = BASE_PROMPT.format(subject=SUBJECT_V2)
ok2 = generate_gemini_flash(p2, str(OUT / "slide12_gold_v2.png"))

# --- V3: Imagen 4.0, cell close-up ---
print("\n=== V3: Imagen 4.0 - Cell Close-up ===")
p3 = BASE_PROMPT.format(subject=SUBJECT_V3)
ok3 = generate_imagen(p3, str(OUT / "slide12_gold_v3.png"))

print(f"\n{'='*40}")
print(f"Results: V1={'✓' if ok1 else '✗'} V2={'✓' if ok2 else '✗'} V3={'✓' if ok3 else '✗'}")

# Verify files
for v in ["slide12_gold_v1.png", "slide12_gold_v2.png", "slide12_gold_v3.png"]:
    p = OUT / v
    if p.exists():
        print(f"  {v}: {p.stat().st_size:,} bytes")
    else:
        print(f"  {v}: MISSING")
