#!/usr/bin/env python3
"""Generate microalgae microscope images for PHAT Foods Slide 12."""

import os
import sys
from pathlib import Path
from google import genai
from google.genai import types

API_KEY = "AIzaSyDXqYZInk83iVV4mD29pSuHQKbgkiI1x9Q"
OUTPUT_DIR = Path("/root/.openclaw/workspace/phat-deck-images")

client = genai.Client(api_key=API_KEY)

# --- Variation 1: flash-image, primary prompt ---
prompt_v1 = (
    "Photorealistic darkfield microscopy photograph of Arthrospira platensis (spirulina) microalgae. "
    "Vivid emerald green helical filaments coiling against a pure black background. "
    "Darkfield illumination catching translucent cell walls and trichome segmentation. "
    "Central filaments razor-sharp, surrounding ones in natural optical bokeh. "
    "Scientific photography aesthetic, Nature magazine quality. 16:9 landscape composition. "
    "No text, no labels, no watermarks, no annotations."
)

# --- Variation 2: flash-image, tweaked prompt (warmer tones, more filaments) ---
prompt_v2 = (
    "Photorealistic darkfield microscopy image of spirulina (Arthrospira platensis) microalgae culture. "
    "Dense field of luminous emerald-to-teal helical trichomes spiraling against deep black void. "
    "Darkfield lighting reveals intricate cell wall striations and internal chloroplast granules. "
    "Shallow depth of field — two central filaments in crystal-clear focus, others drifting into soft bokeh. "
    "Shot on research-grade inverted microscope at 400x magnification. "
    "National Geographic scientific photography. Wide 16:9 frame. "
    "No text, no overlays, no scale bars, no watermarks."
)

# --- Variation 3: imagen, comparison ---
prompt_v3 = (
    "Photorealistic darkfield microscopy photograph of Arthrospira platensis spirulina microalgae. "
    "Brilliant green helical filaments coiling through the frame against pure black background. "
    "Darkfield illumination highlights translucent cell walls and segmented trichome structure. "
    "Central filaments in sharp focus with surrounding ones in natural optical bokeh. "
    "Scientific photography quality suitable for Nature or National Geographic. "
    "Landscape 16:9 aspect ratio. No text, labels, or watermarks."
)

def generate_flash_image(prompt, output_path, label):
    """Generate image using gemini-2.5-flash-preview-04-17 with image output."""
    print(f"\n{'='*60}")
    print(f"Generating {label} with gemini-2.5-flash-preview-04-17...")
    print(f"{'='*60}")
    
    response = client.models.generate_content(
        model="gemini-2.5-flash-image",
        contents=prompt,
        config=types.GenerateContentConfig(
            response_modalities=["IMAGE"],
        ),
    )
    
    # Extract image from response
    for part in response.candidates[0].content.parts:
        if part.inline_data and part.inline_data.mime_type.startswith("image/"):
            with open(output_path, "wb") as f:
                f.write(part.inline_data.data)
            size = os.path.getsize(output_path)
            print(f"✅ Saved: {output_path} ({size:,} bytes)")
            return True
    
    print(f"❌ No image in response for {label}")
    return False


def generate_imagen(prompt, output_path, label):
    """Generate image using imagen-3.0-generate-002."""
    print(f"\n{'='*60}")
    print(f"Generating {label} with imagen-3.0-generate-002...")
    print(f"{'='*60}")
    
    response = client.models.generate_images(
        model="imagen-4.0-generate-001",
        prompt=prompt,
        config=types.GenerateImagesConfig(
            number_of_images=1,
            aspect_ratio="16:9",
        ),
    )
    
    if response.generated_images:
        img = response.generated_images[0]
        img.image.save(str(output_path))
        size = os.path.getsize(output_path)
        print(f"✅ Saved: {output_path} ({size:,} bytes)")
        return True
    
    print(f"❌ No image generated for {label}")
    return False


if __name__ == "__main__":
    results = []
    
    # V1: flash-image
    ok1 = generate_flash_image(prompt_v1, OUTPUT_DIR / "slide12_microalgae_tatiana_v1.png", "V1")
    results.append(("v1", ok1))
    
    # V2: flash-image with tweaked prompt
    ok2 = generate_flash_image(prompt_v2, OUTPUT_DIR / "slide12_microalgae_tatiana_v2.png", "V2")
    results.append(("v2", ok2))
    
    # V3: imagen
    ok3 = generate_imagen(prompt_v3, OUTPUT_DIR / "slide12_microalgae_tatiana_v3.png", "V3")
    results.append(("v3", ok3))
    
    print(f"\n{'='*60}")
    print("SUMMARY")
    print(f"{'='*60}")
    for name, ok in results:
        status = "✅" if ok else "❌"
        path = OUTPUT_DIR / f"slide12_microalgae_tatiana_{name}.png"
        if ok and path.exists():
            print(f"{status} {path} — {os.path.getsize(path):,} bytes")
        else:
            print(f"{status} {path} — FAILED")
