"""Venus A-1 Hook slide — PURE Gemini native image generation.

No HTML/Playwright. Korean text rendered by Gemini Pro directly.
Output: 1080x1080 PNG → /home/jay/workspace/output/meta-ads/a-group-venus/venus-A1-hook.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-A1-hook.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 — a dimly lit workspace at night. A single warm desk lamp illuminates scattered papers and a closed laptop on a dark wooden desk. A person's silhouette is barely visible, slumped over the desk in exhaustion. The scene conveys the crushing weight of a numb daily grind — loneliness, burnout, silent desperation. Deep charcoal and navy tones dominate.

PHOTOGRAPHIC QUALITY: Shot on ARRI Alexa 65. f/1.4 wide aperture. Warm desk lamp creates a small pool of golden light contrasting with the surrounding darkness. Shallow depth of field. Cinematic color grading — desaturated cool shadows, warm single light source. No stock-photo look. No clichéd effects.

TYPOGRAPHY LAYOUT — CENTER-ALIGNED, positioned in the center of the image:

LINE 1 (Headline): "열심히 했다."
— Bold Korean sans-serif (like Pretendard or Noto Sans KR), pure white (#FFFFFF), font size approximately 72px, bold weight (800+), center-aligned. Tight letter-spacing for a pressured, compressed feeling.

LINE 2 (Headline continued): "근데 왜 나만 안 되지?"
— Same style as line 1, bold white, ~72px, center-aligned. This is the emotional punch line.

[vertical spacer ~30px]

LINE 3 (Subheadline): "방문 횟수, 전화 통화, 상담 건수—"
— Korean sans-serif, dimmer grayish-white (#B8B8BC), approximately 40px, weight 400-500, center-aligned.

LINE 4 (Subheadline continued): "숫자는 쌓이는데 통장은 그대로다."
— Same style as line 3, grayish-white, ~40px, center-aligned. Generous line spacing to slow reading pace.

BOTTOM AREA: A black gradient overlay covers the lower 30% of the image, ensuring text readability over the background.

PAGE INDICATOR: "1/5" — bottom-right corner, approximately 40px, light gray (#888894).

DESIGN RULES:
- ALL Korean text must be perfectly rendered with accurate characters, no distortion, no garbled text
- Every text element must be at minimum 40px equivalent
- Text must pass WCAG AAA contrast (7:1 for body, 4.5:1 for large text) against background
- No logos, no icons, no glassmorphism, no geometric shapes
- No internal labels like "A-1" or "HOOK"
- Font weights 400+ only (no thin/light fonts)
- The emotional goal: insurance agent (1-5 years) feels "this is exactly my story" — recognition shock
- Professional premium advertising quality, NOT a PowerPoint slide

STYLE REFERENCE: Premium Korean financial/coaching advertisement. Christopher Nolan cinematic color grading. Dark, heavy, atmospheric, emotionally resonant.

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


def get_token() -> str:
    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-1 Hook — PURE Gemini Native Image Generation")
    print(f"Output: {OUTPUT_PATH}")
    print("=" * 60)

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

    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: {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: {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)

    # Save — Gemini may return JPEG; save with correct extension, then rename
    raw_path = OUTPUT_PATH.with_suffix(".jpg" if "jpeg" in mime_type else ".png")
    raw_path.write_bytes(image_bytes)

    # If JPEG, convert to PNG for consistency
    if "jpeg" in mime_type:
        from PIL import Image
        img = Image.open(raw_path)
        img.save(OUTPUT_PATH, "PNG")
        print(f"[CONVERT] JPEG → PNG")
    else:
        if raw_path != OUTPUT_PATH:
            raw_path.rename(OUTPUT_PATH)

    file_size = OUTPUT_PATH.stat().st_size
    print(f"\n[SUCCESS] Saved: {OUTPUT_PATH}")
    print(f"  Size: {file_size:,} bytes ({file_size / 1024:.1f} KB)")
    print(f"  MIME source: {mime_type}")

    # Check dimensions
    from PIL import Image
    img = Image.open(OUTPUT_PATH)
    print(f"  Dimensions: {img.size[0]}x{img.size[1]}")


if __name__ == "__main__":
    main()
