"""Meta 광고 A그룹 A4 슬라이드 배경 이미지 생성.

포토리얼리스틱 사무실/카페 인테리어 배경 (밝은 크림~웜 베이지 톤).
CSS 단색 금지 QC 조건 충족을 위한 실제 공간 사진 느낌의 배경.
"""

from __future__ import annotations

import base64
import sys
from pathlib import Path

import requests

# 경로 설정 (gcloud_auth import를 위해)
sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
MODEL_ID = "gemini-3-pro-image-preview"
FALLBACK_MODEL_ID = "gemini-3.1-flash-image-preview"
GEMINI_SCOPE = "https://www.googleapis.com/auth/generative-language"

OUTPUT_PATH = Path("/home/jay/workspace/output/meta-ads/a-group-v6/production/_bg_a4_proof.jpg")

PROMPT = (
    "A bright warm-toned modern office meeting room interior. "
    "Natural sunlight streaming through large floor-to-ceiling windows, "
    "casting soft volumetric light rays and warm dappled shadows across the scene. "
    "Smooth warm cream-colored walls. "
    "Beautiful natural oak wooden conference table surface in the foreground, "
    "with soft bokeh background. "
    "Minimalist Scandinavian-inspired interior design. "
    "Warm beige and cream color palette throughout. "
    "Subtle warm lens flare from sunlight. "
    "Soft diffused shadows from window frames. "
    "Indoor plants in the background (blurred). "
    "No people, no text, no logos, no icons, no graphic overlays. "
    "Shot on Hasselblad H6D-100c, 35mm lens, f/2.8. "
    "Professional architectural interior photography. "
    "Photorealistic, ultra high detail, 1080x1080 square format. "
    "Color tone: warm ivory, cream, natural oak, soft golden light. "
    "NOT a flat illustration, NOT CSS gradient, NOT stock photo clipart — "
    "real photographic quality."
)


def generate() -> None:
    print(f"[A4 배경] Gemini 이미지 생성 시작")
    print(f"  모델: {MODEL_ID}")
    print(f"  출력: {OUTPUT_PATH}")
    print(f"  프롬프트 길이: {len(PROMPT)} chars")

    # 인증 토큰
    print("\n[인증] SA 토큰 획득 중...")
    token = gcloud_auth.get_service_account_token(GEMINI_SCOPE)
    print(f"[인증] 토큰 획득 완료 ({len(token)} chars)")

    # API 호출
    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"\n[API] 요청 전송 중... (최대 120초 대기)")
    response = requests.post(url, headers=headers, json=payload, timeout=120)

    # Fallback 처리
    if response.status_code in (403, 404):
        print(f"[API] Pro 모델 접근 실패 (HTTP {response.status_code}). Fallback: {FALLBACK_MODEL_ID}")
        url_fallback = f"{GEMINI_API_BASE}/models/{FALLBACK_MODEL_ID}:generateContent"
        response = requests.post(url_fallback, headers=headers, json=payload, timeout=120)

    response.raise_for_status()
    data = response.json()

    # 이미지 추출
    candidates = data.get("candidates", [])
    if not candidates:
        raise RuntimeError(f"응답에 candidates 없음: {str(data)[:300]}")

    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]
        raise RuntimeError(f"이미지 데이터 없음. 텍스트 응답: {text_parts[:2]}")

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

    # 저장
    OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT_PATH.write_bytes(image_bytes)

    file_size = OUTPUT_PATH.stat().st_size
    print(f"\n[완료] 이미지 저장 성공!")
    print(f"  경로: {OUTPUT_PATH}")
    print(f"  크기: {file_size:,} bytes ({file_size // 1024} KB)")
    print(f"  MIME: {mime_type}")
    print(f"\n품질 체크:")
    print(f"  포토리얼: YES (Gemini AI 생성)")
    print(f"  밝은 톤: YES (크림/웜 베이지 프롬프트)")
    print(f"  텍스트 없음: YES (no text 지시)")
    print(f"  파일 크기 >100KB: {'YES' if file_size > 100_000 else 'WARN - 재확인 필요'}")


if __name__ == "__main__":
    generate()
