#!/usr/bin/env python
import os
import base64
from openai import OpenAI

# Load API key from environment or fallback file under creds/
if not os.getenv("OPENAI_API_KEY"):
    key_path = os.path.join(os.path.dirname(__file__), "creds", "openai.key")
    if os.path.exists(key_path):
        with open(key_path, "r", encoding="utf-8") as fh:
            os.environ["OPENAI_API_KEY"] = fh.read().strip()

client = OpenAI()  # käyttää OPENAI_API_KEY-ympäristömuuttujaa

# Varmista että hakemisto on olemassa
os.makedirs("sampleimages", exist_ok=True)

images = {
    "sampleimages/saimaa-lakeside-cabin-cover.jpg":
        "Finnish timber lakeside cabin on Lake Saimaa at golden hour, wooden deck with private dock, calm water, pine forest background, subtle sauna chimney smoke, summer green, cozy mood, wide hero photo, ultra realistic, high resolution.",
    "sampleimages/saimaa-lakeside-cabin-sauna.jpg":
        "Wood-fired lakeside sauna hut with small pier, steam drifting, lake reflections, dusk light, rustic wood, Finland, ultra realistic photo.",
    "sampleimages/saimaa-lakeside-cabin-lounge.jpg":
        "Cabin living area with stone fireplace, timber walls, soft textiles, lake view through large window, warm lighting, cozy Scandinavian interior, realistic photo.",
    "sampleimages/helsinki-design-loft-cover.jpg":
        "Modern Helsinki top-floor loft, Scandinavian design, airy living room, big windows over Katajanokka harbor, light wood floors, clean lines, hero interior photo, ultra realistic.",
    "sampleimages/helsinki-design-loft-balcony.jpg":
        "Balcony view toward Helsinki harbor and ferries from a design loft, glass railing, evening light, realistic photo.",
    "sampleimages/helsinki-design-loft-bedroom.jpg":
        "Minimalist loft bedroom, light wood, linen bedding, black accents, soft daylight, Scandinavian interior, realistic photo.",
    "sampleimages/turku-riverside-apartment-cover.jpg":
        "Cozy one-bedroom apartment living room near Aura river in Turku, window view to riverside trees, Nordic decor, warm neutrals, realistic interior photo.",
    "sampleimages/turku-riverside-apartment-kitchen.jpg":
        "Compact Scandinavian kitchen corner, white cabinets, wood countertop, small dining table by window, daylight, realistic photo.",
    "sampleimages/rovaniemi-aurora-cabin-cover.jpg":
        "Lapland riverside cabin under aurora borealis sky, snowy ground, glass lounge glowing warm, river nearby, pine trees, wide angle, ultra realistic night photo.",
    "sampleimages/rovaniemi-aurora-cabin-lounge.jpg":
        "Timber cabin lounge with fireplace, fur throws, window showing snowy riverbank, northern ambiance, cozy realistic interior photo.",
    "sampleimages/tampere-sauna-studio-cover.jpg":
        "Compact city studio in Tampere center, modern interior, small sofa, bed nook, visible private electric sauna door, AC unit, bright window, realistic interior photo.",
    "sampleimages/tampere-sauna-studio-sauna.jpg":
        "Small electric sauna cabin with glass door inside an apartment, clean light wood benches, Finnish style, realistic photo.",
    "sampleimages/vaasa-seaside-villa-cover.jpg":
        "Seaside villa deck in Vaasa, view to calm sea, big wooden terrace with seating, Nordic summer evening light, wide hero photo, realistic.",
    "sampleimages/vaasa-seaside-villa-lounge.jpg":
        "Spacious living room with fireplace, large windows to sea, light wood, cozy Scandinavian decor, realistic interior photo.",
    "sampleimages/kuopio-lakeside-apartment-cover.jpg":
        "Apartment balcony overlooking Lake Kallavesi in Kuopio, glass railing, morning mist on water, wide balcony shot, realistic photo.",
    "sampleimages/kuopio-lakeside-apartment-sauna.jpg":
        "Apartment electric sauna, clean tile and light wood, glass door, modern Finnish style, realistic photo.",
    "sampleimages/porvoo-river-loft-cover.jpg":
        "Porvoo old town loft interior, exposed brick, fireplace, window view toward riverside warehouses, warm lighting, cozy Scandinavian loft, interior photo.",
    "sampleimages/porvoo-river-loft-fireplace.jpg":
        "Cozy reading corner by brick fireplace, wood beams, vintage Nordic charm, realistic interior photo.",
    "sampleimages/oulu-tech-apartment-cover.jpg":
        "Modern one-bedroom near Technopolis Oulu, sleek interior, work desk, smart lock door visible, AC unit, daylight, minimalist Scandinavian style, interior photo.",
    "sampleimages/oulu-tech-apartment-desk.jpg":
        "Work-from-home desk setup in modern apartment, large monitor, ergonomic chair, fiber internet vibe, clean Scandinavian style, realistic photo.",
    "sampleimages/mariehamn-harbor-flat-cover.jpg":
        "Harbor-facing flat in Mariehamn, balcony overlooking ferries and sailboats, evening light, red wooden buildings in distance, wide balcony harbor view, realistic photo.",
    "sampleimages/mariehamn-harbor-flat-living.jpg":
        "Bright living room with large window to harbor, light wood floors, simple Nordic decor, airy feeling, realistic interior photo.",
}

for path, prompt in images.items():
    # Jos tiedosto on jo olemassa ja ei ole tyhjä, jätetään väliin
    if os.path.exists(path) and os.path.getsize(path) > 0:
        print(f"Skipping existing file: {path}")
        continue

    # Valitse koko: kansikuvat leveänä, muut neliönä
    if "cover" in path:
        size = "1536x1024"
    else:
        size = "1024x1024"

    print(f"Generating {path} ({size})...")

    try:
        result = client.images.generate(
            model="gpt-image-1",
            prompt=prompt,
            size=size,
            n=1,
        )

        image_b64 = result.data[0].b64_json
        image_bytes = base64.b64decode(image_b64)

        with open(path, "wb") as f:
            f.write(image_bytes)

        print(f"Saved {path}")

    except Exception as e:
        # Ei kaadeta koko skriptiä yhden virheen takia
        print(f"ERROR generating {path}: {e}")

print("Done.")
