"""C26 v2 배경 이미지 생성 — aspirational office backgrounds."""

import base64
import subprocess
import time
from pathlib import Path

import requests

OUTPUT_DIR = Path("/home/jay/workspace/tools/ai-image-gen/output/v4-hybrid")
MODEL_ID = "gemini-3.1-flash-image-preview"
GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
GEMINI_SCOPE = "https://www.googleapis.com/auth/generative-language"

LANDSCAPE_PROMPT = (
    "Modern Korean corporate office with floor-to-ceiling windows showing city skyline at golden hour, "
    "warm professional atmosphere, leather chair and wooden desk, premium executive feel, "
    "no people, no text, no logos, photorealistic, cinematic lighting, warm amber tones"
)

SQUARE_PROMPT = (
    "Modern Korean corporate office with floor-to-ceiling windows showing city skyline at golden hour, "
    "warm professional atmosphere, leather chair and wooden desk, premium executive feel, "
    "no people, no text, no logos, photorealistic, cinematic lighting, warm amber tones, square format"
)


def get_token() -> str:
    result = subprocess.run(
        ["gcloud", "auth", "print-access-token", f"--scopes={GEMINI_SCOPE}"],
        capture_output=True, text=True, check=True,
    )
    return result.stdout.strip()


def generate(token: str, name: str, prompt: str) -> str:
    url = f"{GEMINI_API_BASE}/models/{MODEL_ID}:generateContent"
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
    }
    print(f"[{name}] 요청 중...")
    start = time.time()
    resp = requests.post(url, headers=headers, json=payload, timeout=180)
    resp.raise_for_status()
    elapsed = time.time() - start

    data = resp.json()
    candidates = data.get("candidates", [])
    if not candidates:
        raise RuntimeError(f"No candidates. Response: {str(data)[:300]}")

    parts = candidates[0].get("content", {}).get("parts", [])
    image_part = next((p for p in parts if "inlineData" in p), None)
    if image_part is None:
        text_parts = [p.get("text", "") for p in parts if "text" in p]
        raise RuntimeError(f"No image data. Text parts: {text_parts[:2]}")

    mime_type = image_part["inlineData"].get("mimeType", "image/jpeg")
    image_bytes = base64.b64decode(image_part["inlineData"]["data"])
    ext = ".jpg" if "jpeg" in mime_type else ".png"
    out_path = OUTPUT_DIR / f"bg_c26_{name}_v2{ext}"
    out_path.write_bytes(image_bytes)
    size = out_path.stat().st_size
    print(f"[{name}] 완료: {out_path.name} ({size:,} bytes, {elapsed:.1f}초)")
    return str(out_path)


if __name__ == "__main__":
    token = get_token()
    print(f"Token acquired ({len(token)} chars)")
    lp = generate(token, "landscape", LANDSCAPE_PROMPT)
    sq = generate(token, "square", SQUARE_PROMPT)
    print(f"\nLandscape: {lp}")
    print(f"Square:    {sq}")
