"""Venus A-4 Proof 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-A4-proof.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-A4-proof.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. This is slide 4 of 5 in a carousel — the "social proof / testimonials" slide.

BACKGROUND: Clean, bright, elegant. Light cream (#F8F5F0) or warm off-white background. Minimal texture — perhaps subtle paper grain or soft warm light from the top. This slide should feel open, trustworthy, transparent. It is one of the brightest slides in the series (transition from dark themes in previous slides to bright here).

LAYOUT:

TOP SECTION (15% height):
- Headline: "방법을 바꾼 사람들이 말하는 실제 변화."
- Dark text (#1A0E00 or dark brown), bold Korean sans-serif, approximately 52px
- The words "실제 변화" should be rendered in dark gold (#A07828) color for accent
- Center-aligned

MIDDLE SECTION (60% height) — TWO TESTIMONIAL QUOTE CARDS stacked vertically:

CARD 1:
- Left border: 4px gold (#C9A84C) vertical accent bar
- Large Korean quotation mark at top-left of card in gold
- Quote text: "거절이 두려웠는데, 이제는 고객을 선택합니다."
- Dark text (#2A1A0A), approximately 44px, Korean sans-serif, weight 500
- Attribution: "— 이○○" in bold, right-aligned below quote, dark brown
- Card background: white (#FFFFFF) with subtle shadow

CARD 2:
- Same style as Card 1
- Quote text: "자동 유입 시스템으로 걱정 없는 영업이 됐습니다."
- Attribution: "— 김○○" in bold

Cards should have subtle drop shadow, clean white background, and gold left accent bar.

BOTTOM SECTION (25% height):
- Attribution line: "서울대보험쌤 팀의 5가지 시스템 안에서 시작한 이야기입니다."
- Gray (#888888) text, approximately 40px, italic or lighter weight, center-aligned

PAGE INDICATOR: "4/5" — bottom-right corner, approximately 40px, dark gold (#A07828).

DESIGN RULES:
- ALL Korean text must be perfectly rendered — accurate characters, no distortion
- Every text element at minimum 40px
- On bright background: use DARK text colors for WCAG AAA contrast
- Gold accent (#A07828 for dark gold on light bg) must contrast clearly
- No logos, no photos of people, no group images, no trophies, no company charts
- No internal labels ("A-4", "PROOF")
- Clean, premium, trustworthy feel — like a luxury brand testimonial page
- Professional advertising quality

STYLE REFERENCE: Premium Korean coaching/consulting advertisement. Clean editorial design. Bright, trust-building, elegant typography.

IMPORTANT — clear Korean text, testimonial card layout, bright clean background, gold accent elements, no watermark, easily readable on mobile.
"""


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-4 Proof — 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)

    raw_path = OUTPUT_PATH.with_suffix(".jpg" if "jpeg" in mime_type else ".png")
    raw_path.write_bytes(image_bytes)

    if "jpeg" in mime_type:
        from PIL import Image
        img = Image.open(raw_path)
        img.save(OUTPUT_PATH, "PNG")
        print("[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}")

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


if __name__ == "__main__":
    main()
