import os, time, replicate, urllib.request
from pathlib import Path

for env_path in [Path("/home/syesor/.env"), Path("/home/syesor/claude_home/.env")]:
    if env_path.exists():
        for line in open(env_path):
            line = line.strip()
            if '=' in line and not line.startswith('#'):
                k, v = line.split('=', 1)
                os.environ.setdefault(k.strip(), v.strip())

MODEL = "google/nano-banana-pro"
OLLIE_REF = "/home/syesor/claude_home/projects/olly-and-dot/public/character-top-picks/d10-mm-p3-v1.jpg"
STYLE_REF = "/home/syesor/ctrlcompany.bak/agata-book/ai-book/styles-v1/styles/d10-mixed-media-p3/v2.jpg"
OUT_DIR = Path("/home/syesor/claude_home/projects/olly-and-dot/public/images/nbp-v23")
OUT_DIR.mkdir(parents=True, exist_ok=True)

def generate(prompt, output_path):
    try:
        output = replicate.run(MODEL, input={
            "prompt": prompt,
            "image_1": open(OLLIE_REF, "rb"),
            "image_2": open(STYLE_REF, "rb"),
            "aspect_ratio": "16:9",
        })
        url = str(output[0]) if isinstance(output, list) else str(output)
        urllib.request.urlretrieve(url, str(output_path))
        print(f"SUCCESS: {output_path.name}")
        return True
    except Exception as e:
        print(f"FAILED {output_path.name}: {e}")
        return False

PAGES = [
    ("page07_v1.jpg", """The first reference shows the octopus character. The second shows the mixed media style.

A vast dark underwater abyss. Two VERY TINY characters huddle together in enormous darkness — they are small specks in an immense deep ocean. A baby octopus curled up tight — his golden-amber stipple brush skin has turned dark brown from depth color loss, only faint warmth remains. He is squinting with visible fear, small mouth showing vulnerability. Arms pulled in tight. Beside him floats a tiny solid natural Tahitian pearl, golf-ball sized, with soft warm yellow light glowing from rounded squint eyes projected from inside. The pearl's gentle glow creates a tiny circle of visibility — revealing dark sea floor texture with stipple brush dots. Everything beyond is deep flat ink wash darkness. Far above, an enormous whale shadow passes — vast, mysterious, suggested by the faintest shift in darkness. Watercolor ink wash surrounding their tiny pool of pearl-light. Full bleed 16:9."""),

    ("page17_v1.jpg", """The first reference shows the octopus character. The second shows the mixed media style.

An underwater celebration bathed in warm sunset-gold light filtering from above. A cartoon baby octopus with fine stipple brush dots in gold, orange, yellow, white — arms spread WIDE in triumph and joy. Face shows pure happiness: big dark pill-shaped eyes with golden star catchlights perfectly ALIGNED and level, wide excited smile, rosy cheeks glowing. THREE subtle glowing hearts float on his chest, soft and luminous. Beside him, a solid natural Tahitian pearl with soft warm-yellow rounded squint eyes glowing from inside, oriented toward the octopus celebrating together. Pearl reflects warm golden tones. Abundant realistic bubbles and light caustics throughout. Warm coral reef with stipple brush texture on coral and rocks. Mixed media collage: torn paper coral, gouache creatures, watercolor wash, submerged in underwater photography. Full bleed 16:9."""),

    ("page18_v1.jpg", """The first reference shows the octopus character. The second shows the mixed media style.

A dramatic DOWNWARD dive composition. Two characters swimming boldly deeper together. Full page vertical color gradient from rich teal-green at top through deepening blue to dark indigo at bottom. A cartoon baby octopus with fine stipple brush dots in gold, orange, yellow, white, arms flowing behind in dynamic swimming motion, expression determined and brave. Dark pill-shaped eyes with golden star catchlights, small set mouth showing focus. Beside him a solid natural Tahitian pearl with soft warm-yellow rounded squint eyes glowing from inside, oriented DOWNWARD in direction of travel, engaged and excited. Both side by side swimming DOWN along a reef wall. Bioluminescent breadcrumb path of tiny glowing creatures below showing the way deeper. Stipple brush texture on reef wall rocks and coral. Real underwater bubbles streaming upward. Mixed media: torn paper reef at top, watercolor wash deepening below. Full bleed 16:9."""),

    ("page05_v1.jpg", """The first reference shows the octopus character. The second shows the mixed media style.

A WIDE-ANGLE underwater bioluminescent creature parade — the WOW page. An expansive canyon view teeming with abundant glowing sea life. Two small characters float in the middle of this vast scene, both looking UP with pure wonder and amazement. The baby octopus's golden-amber stipple brush skin shows obvious color loss from depth — muted, washed out, blending into watercolor. The solid natural Tahitian pearl glows warmly with rounded squint eyes from inside. Characters are illuminated by the bioluminescent animals around them — jellyfish, comb jellies, deep sea fish, tube worms, all glowing scientifically accurate blues, greens, magentas. The canyon walls are collage melting into watercolor — torn paper structures fading to painted washes. Real underwater photography: bubbles, particle haze, volumetric scattered light. Abundant, wild, natural — a creature parade of wonder. Full bleed 16:9."""),

    ("front_cover_v1.jpg", """The first reference shows the octopus character. The second shows the mixed media style.

A close-up cliff edge underwater dive scene. Two characters near the edge of a vibrant reef cliff about to descend into the deep. The baby octopus with fine gold stipple brush dots, smooth round head, big excited dark eyes with golden star catchlights, happy adventurous expression, body angled downward. A solid natural Tahitian pearl with rounded squint eyes glowing warmly from inside, oriented downward with the octopus. Fish are BIGGER and prominent — painted paper-craft style tropical fish like a collage illustration. Real ocean coral reef blended with painted collage elements. Blue ocean sunlight streaming through water from above. The cliff drops away below them — rainbow iridescent bio glow at the bottom of the cliff, detailed and shimmering. Iridescent foil airbrush lighting on the cliff face. Dark areas below still have beautiful ink line work showing underwater environment. Stipple brush texture on coral and rocks. Full bleed 16:9."""),

    ("page02_v1.jpg", """The first reference shows the octopus character. The second shows the mixed media style.

MASSIVE Monterey kelp forest — kelp towers like redwood trees with IRIDESCENT RAINBOW shimmer on kelp surfaces. A TINY cartoon baby octopus with fine gold stipple brush dots, happy eyes with golden star catchlights, one arm clutching a shiny seashell, looking at his companion — the size of ONE kelp bladder. A tiny solid natural Tahitian pearl with warm-yellow rounded squint eyes glowing from inside, racing beside him, engaged and active. Both characters are MINUSCULE against the giant forest cathedral. A painted pink seahorse companion nearby. A painted harbor seal watches from between kelp stalks. Vibrant green happy colors — dappled golden-green light filtering through the enormous kelp canopy. Stipple brush texture on kelp holdfasts and rocky substrate. Mixed media: real photographic kelp blended with watercolor wash and torn paper elements. Full bleed 16:9."""),
]

results = {}
for i, (filename, prompt) in enumerate(PAGES):
    output_path = OUT_DIR / filename
    print(f"\n[{i+1}/6] Generating {filename}...")
    success = generate(prompt, output_path)
    results[filename] = success
    if i < len(PAGES) - 1:
        time.sleep(2)

print("\n=== RESULTS ===")
for filename, success in results.items():
    status = "OK" if success else "FAIL"
    print(f"  {status}: {filename}")
print(f"\nTotal: {sum(results.values())}/6 succeeded")
