"""Venus A-2 Problem slide image generator.

Meta ad carousel slide — 1080x1080px
Save to: /home/jay/workspace/output/meta-ads/a-group-venus/venus-A2-problem.png
"""

from __future__ import annotations

import base64
import subprocess
import sys
from pathlib import Path

import requests

OUTPUT_PATH = Path("/home/jay/workspace/output/meta-ads/a-group-venus/venus-A2-problem.png")
MODEL_ID = "gemini-3-pro-image-preview"
FALLBACK_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"

PROMPT = """\
Create a 1080x1080 square Korean premium advertising image for Meta (Facebook/Instagram) ads.

BACKGROUND SCENE: Photorealistic cinematic photograph — rain streaming down a large dark window at night. Through the glass, blurred bokeh city lights (Seoul cityscape) glow amber and white in the distance. The scene conveys deep isolation, melancholy, and suppressed frustration. The overall background tone is dark gray (not pure black — slightly lighter, around #1A1A1F) with subtle cool undertones. The rain droplets on glass create a visual metaphor for tears, obstacles, burdens.

PHOTOGRAPHIC QUALITY: Shot on ARRI Alexa 65. f/1.8 wide aperture. Shallow depth of field. Rain droplets sharp in foreground, city lights softly bokeh'd behind. Cinematic 2.39:1 feel cropped to 1:1 square. No stock-photo look. No lens flares or clichéd effects.

TYPOGRAPHY LAYOUT — LEFT-ALIGNED, positioned in the lower-left to center-left area with generous left margin (about 80px from left edge):

LINE 1 (Headline part 1): "문제는 노력이 아니다."
— Bold Korean sans-serif, white (#FFFFFF), font size approximately 62px, bold weight (700+), left-aligned

LINE 2 (Headline part 2 — ACCENT): "방법이 없었던 거다."
— Bold Korean sans-serif, warm golden amber color (#D4A017 or #C8930A), same size ~62px, bold weight (700+), left-aligned. This line must clearly contrast against the dark background.

[small vertical spacer ~20px]

LINE 3 (Subheadline line 1): "지인 명단은 바닥났고, 알려줄 멘토도 없었다."
— Korean sans-serif, light gray-white (#C8C8CC), approximately 36px, weight 400-500, left-aligned

LINE 4 (Subheadline line 2 — slightly bolder): "혼자 버티는 건 미덕이 아니라 손실이다."
— Korean sans-serif, slightly brighter white (#E0E0E4), approximately 38px, weight 500-600, left-aligned. This line carries more emotional weight.

PAGE INDICATOR: "2/5" — small, right-aligned in bottom-right corner, approximately 28px, gray (#888894), clean minimal style.

DESIGN RULES:
- ALL Korean text must be perfectly rendered, accurate characters, no distortion
- Minimum 40px equivalent for all text elements
- Text must pass WCAG AAA contrast against the dark background
- No logos, no line-art icons, no glassmorphism effects, no geometric graphic elements
- No thin/light font weights (400+ only)
- The golden amber accent color (#D4A017) must contrast clearly — do NOT use orange if background has orange cast
- Professional advertising quality — not a stock photo aesthetic
- The emotional goal: viewer feels "yes, it wasn't my effort that was lacking — I just had no system/method" — suppressed frustration + righteous recognition

STYLE REFERENCE: Premium Korean financial/coaching advertisement. Christopher Nolan cinematic color grading. Dark, atmospheric, premium editorial feel.

IMPORTANT — large bold Korean text, easily readable on mobile, cinematic dark background, photorealistic rain on window scene, no watermark, no clipart, no icons.
"""


def get_token() -> str:
    """Get auth token via SA or gcloud CLI."""
    sys.path.insert(0, "/home/jay/workspace/tools/ai-image-gen")
    try:
        import gcloud_auth
        return gcloud_auth.get_service_account_token(GEMINI_SCOPE)
    except Exception as e:
        print(f"[AUTH] SA token failed: {e}, trying gcloud CLI...")

    result = subprocess.run(
        ["gcloud", "auth", "print-access-token",
         "--scopes=https://www.googleapis.com/auth/generative-language"],
        capture_output=True, text=True
    )
    token = result.stdout.strip()
    if not token:
        raise RuntimeError("gcloud auth print-access-token returned empty token")
    return token


def call_gemini(token: str, model_id: str) -> requests.Response:
    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"],
            "temperature": 1.0,
        },
    }
    print(f"[API] Calling model: {model_id}")
    return requests.post(url, headers=headers, json=payload, timeout=180)


def main() -> None:
    OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)

    print("=" * 60)
    print("Venus A-2 Problem — Gemini Image Generation")
    print(f"Output: {OUTPUT_PATH}")
    print("=" * 60)

    # Auth
    print("\n[AUTH] Obtaining token...")
    token = get_token()
    print(f"[AUTH] Token obtained ({len(token)} chars)")

    # Call API with fallback
    response = call_gemini(token, MODEL_ID)
    if response.status_code in (403, 404):
        print(f"[API] Pro model failed ({response.status_code}), falling back to {FALLBACK_MODEL_ID}")
        response = call_gemini(token, FALLBACK_MODEL_ID)

    if not response.ok:
        print(f"[ERROR] HTTP {response.status_code}: {response.text[:500]}")
        sys.exit(1)

    data = response.json()
    candidates = data.get("candidates", [])
    if not candidates:
        print(f"[ERROR] No candidates in response: {str(data)[:300]}")
        sys.exit(1)

    parts = candidates[0].get("content", {}).get("parts", [])
    image_part = None
    for part in parts:
        if "inlineData" in part:
            image_part = part
            break

    if image_part is None:
        text_parts = [p.get("text", "") for p in parts if "text" in p]
        print(f"[ERROR] No image in response. Text parts: {text_parts[:2]}")
        sys.exit(1)

    mime_type = image_part["inlineData"].get("mimeType", "image/jpeg")
    image_b64 = image_part["inlineData"]["data"]
    image_bytes = base64.b64decode(image_b64)

    # Determine extension from mime type
    ext = ".jpg" if "jpeg" in mime_type else ".png"
    save_path = OUTPUT_PATH if OUTPUT_PATH.suffix.lower() == ext else OUTPUT_PATH.with_suffix(ext)
    save_path.write_bytes(image_bytes)

    file_size = save_path.stat().st_size
    print(f"\n[SUCCESS] Saved: {save_path}")
    print(f"  Size: {file_size:,} bytes ({file_size / 1024:.1f} KB)")
    print(f"  MIME: {mime_type}")
    print(f"  Min quality check: {'PASS' if file_size > 100_000 else 'WARN: < 100KB'}")


if __name__ == "__main__":
    main()
