"""A3 Solution 슬라이드용 배경 이미지 생성 스크립트.

포토리얼리스틱 전략 회의실/코칭 세션 이미지를 생성합니다.
상단 딥네이비/차콜 → 하단 웜 크림/골드 색상 전환.
"""

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-v6/production/_bg_a3_solution.jpg")
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 = (
    "Photorealistic photograph of a modern premium executive strategy room or one-on-one coaching session. "
    "The scene features a high-end corporate interior with sleek dark walls and polished surfaces. "
    "Floor-to-ceiling windows on one side allow soft natural light to stream in diagonally, creating "
    "a sense of revelation and hope. A large curved monitor or presentation screen in the background "
    "displays a clean data dashboard with subtle blue glows. "
    "COMPOSITION: The upper two-thirds of the image is clean and uncluttered — deep navy/charcoal "
    "gradient at the top, transitioning gradually to warm cream and soft gold tones at the bottom. "
    "Minimal objects in the central area to allow text overlay. "
    "LIGHTING: Volumetric natural light from one side window, creating god-rays effect. "
    "Warm rim lighting from the bottom. Dark moody upper atmosphere with gradual brightening downward. "
    "COLOR PALETTE: Top — deep navy #1a1f3a, charcoal #2c2c3e. Bottom — warm cream #f5f0e8, "
    "soft gold #c8a96e. The overall gradient feels like dawn breaking in a premium space. "
    "MOOD: The moment of discovery — 'I didn't know this existed.' Hopeful turning point, "
    "strategic clarity, premium intelligence. "
    "CAMERA: Shot on Phase One IQ4 150MP, 35mm wide-angle lens, f/2.8. "
    "Shallow depth of field on background elements. "
    "STYLE: Apple product launch keynote stage aesthetic. No stock photo feel. "
    "No watermarks, no text, no icons, no circuit boards, no tech graphics, no HUD elements. "
    "Pure photorealistic interior photography. "
    "ASPECT: 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"])

    # .jpg로 저장
    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()
