"""Venus A-3 Solution 슬라이드 이미지 생성 스크립트.

Meta 광고 캐러셀 A-3 슬라이드: "전환점" 솔루션 공개.
어두운 배경에서 밝은 배경으로 전환되는 중간 지점.
"""

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-A3-solution.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 Meta advertising image for an insurance sales coaching brand.

BACKGROUND SCENE: Photorealistic transitional atmosphere — dawn light breaking through a modern premium office window. The overall tone is NEITHER fully dark nor fully bright — it is a deliberate turning point. Think: 6am golden hour light streaming through floor-to-ceiling glass, warm golden rays cutting across a minimalist dark room, data visualization elements softly glowing in the background.

LIGHTING: Volumetric god-rays from upper-right. Warm golden-amber light (#C9A84C family) transitioning the scene from deep navy/charcoal at the top to warm cream/gold at the lower half. The gradient should feel natural — like dawn arriving mid-scene. Cinematic depth with slight bokeh on background.

COLOR PALETTE: Upper portion: deep navy #1a1f3a to dark charcoal #2c2c3e. Lower portion: warm gold #C9A84C fading to cream #f5f0e8. The emotional shift from despair to discovery.

KOREAN TEXT OVERLAY (critical — must be large, bold, and accurately rendered):

TOP-LEFT (small brand badge, white text on semi-transparent dark pill background):
"서울대보험쌤"

CENTER-LEFT AREA (large bold headline, white text, 2 lines):
Line 1: "서울대 출신 팀장이"
Line 2: "보험 영업을 다시 설계했다."

BELOW HEADLINE (subheadline, 2 lines):
Line 1: "감각이 아닌 데이터로, 경험이 아닌 시스템으로."
  — the words "데이터" and "시스템" must be in gold color #C9A84C, visually bolder
Line 2: "혼자 뛰지 않아도 되는 구조를 만들었다."
  — this line in slightly lighter white, italic or slightly smaller

BOTTOM-RIGHT corner: "3/5" in small white text

TYPOGRAPHY REQUIREMENTS:
- ALL Korean text must be LARGE and EASILY READABLE on mobile screens
- Brand badge: minimum 40px, white text on dark semi-transparent background
- Headline: minimum 70px, bold white, clear drop shadow for contrast
- Subheadline: minimum 50px, white with gold accent on "데이터" and "시스템"
- Page indicator "3/5": minimum 40px white
- WCAG AAA contrast — all text must be clearly legible

LAYOUT: Left-aligned text composition. The right half of the image shows the background scene (dawn light, data visualization glow). Clean visual hierarchy with generous padding.

MOOD: "This system actually exists?" — the moment of revelation. A turning point from darkness to light. Strategic clarity meeting emotional surprise.

STYLE: Premium Korean advertising. Apple keynote meets Korean financial brand. No stock photo feel. No logos. No icons overlapping text. No watermarks. Photorealistic background with clean text overlay.

IMPORTANT: This is slide 3 of 5 in a carousel. The tone should be noticeably BRIGHTER than slides 1-2 (which were dark/problem-focused) but not as bright as slides 4-5. Transitional dawn.

CAMERA: Phase One IQ4 150MP aesthetic. Cinematic composition. 1:1 square 1080x1080px."""


def get_token() -> str:
    result = subprocess.run(
        ["gcloud", "auth", "print-access-token",
         "--scopes=https://www.googleapis.com/auth/generative-language"],
        capture_output=True, text=True, check=True
    )
    return result.stdout.strip()


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
        },
    }
    return requests.post(url, headers=headers, json=payload, timeout=180)


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

    print("gcloud 토큰 획득 중...")
    try:
        token = get_token()
        print(f"토큰 획득 성공 (길이: {len(token)})")
    except Exception as e:
        print(f"토큰 획득 실패: {e}", file=sys.stderr)
        sys.exit(1)

    print(f"이미지 생성 요청 중... (모델: {MODEL_ID})")
    response = call_gemini(token, MODEL_ID)

    if response.status_code in (403, 404):
        print(f"Pro 모델 접근 실패 (HTTP {response.status_code}). Fallback: {FALLBACK_MODEL_ID}")
        response = call_gemini(token, FALLBACK_MODEL_ID)

    if not response.ok:
        print(f"API 오류: {response.status_code} - {response.text[:500]}", file=sys.stderr)
        sys.exit(1)

    data = response.json()
    candidates = data.get("candidates", [])
    if not candidates:
        print(f"candidates 없음: {str(data)[:300]}", file=sys.stderr)
        sys.exit(1)

    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]
        print(f"이미지 데이터 없음. 텍스트: {text_parts[:2]}", file=sys.stderr)
        sys.exit(1)

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

    # Save as PNG regardless of mime type
    output_path = OUTPUT_PATH
    output_path.write_bytes(image_bytes)
    file_size = output_path.stat().st_size

    print(f"저장 완료: {output_path}")
    print(f"파일 크기: {file_size:,} bytes")
    print(f"MIME: {mime_type}")


if __name__ == "__main__":
    main()
