"""Venus A-5 CTA 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-A5-cta.png
"""

from __future__ import annotations

import base64
import subprocess
import sys
from pathlib import Path

import requests
from gen_config import WORKSPACE_ROOT

OUTPUT_PATH = WORKSPACE_ROOT / "output/meta-ads/a-group-venus/venus-A5-cta.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 a Meta carousel ad. This is the final slide (5 of 5) and must be the BRIGHTEST in the series.

BACKGROUND: Photorealistic warm golden light streaming through a large window or bright doorway. Volumetric god-rays. Warm cream and white atmosphere with golden glow. Morning sunlight flooding a modern space. Conveys hope, new beginnings.

CONTENT FROM TOP TO BOTTOM:

At the very top center, a small badge reading "서울대보험쌤" in dark text on a subtle rounded pill shape.

Below that, the large bold headline in two lines, center-aligned:
"전략을 바꿀 준비가 됐다면,"
"지금 딱 한 번 물어보세요."
The headline should be in dark brown text. The words "딱 한 번" should be highlighted in gold color with an underline to draw attention.

Below the headline, the subheadline in medium-weight dark text, center-aligned:
"서울대보험쌤 팀장이 직접 답합니다."
"조건 없는 상담, 당신 상황에 맞는 방향 제시."

Below the subheadline, a large prominent CTA button with rounded corners. The button has a gold gradient background. The button text reads "무료 상담 신청하기" in DARK BROWN text (not white). The button should have a subtle shadow and look tappable.

At the bottom, small trust elements: "조건 없음 · 무료 상담 · 팀장 직접 응대" in dark text separated by middle dots.

Page indicator "5/5" in the bottom-right corner in dark gold.

CRITICAL RULES:
- ALL Korean text must be perfectly rendered with accurate characters
- All text must be large and readable on mobile
- Do NOT render any technical annotations, measurements, percentages, or pixel values in the image
- Do NOT use white text on the gold button (poor contrast). Use dark brown text instead.
- No logos, no watermarks, no internal labels
- Bright, hopeful, premium Korean advertising style
- Golden-hour photography, clean modern editorial feel
"""


def get_token() -> str:
    sys.path.insert(0, str(WORKSPACE_ROOT / "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-5 CTA — 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()
