#!/usr/bin/env python3
"""Meta 캐러셀 광고 A-2 배경 이미지 재생성 (QC 개선판).

"문제 진단" 슬라이드용 배경: 비 오는 밤 빈 사무실에 혼자 앉아있는 뒷모습 실루엣.
감정: 분노, 좌절, 고립감 / 톤: 어두운 네이비/차콜
"""

from __future__ import annotations

import base64
import sys
import time
from pathlib import Path

import requests

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth  # noqa: E402

# ─────────────────────────────────────────────────────────────────────────────
# 경로 설정
# ─────────────────────────────────────────────────────────────────────────────

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

# ─────────────────────────────────────────────────────────────────────────────
# Gemini 배경 생성 프롬프트
# ─────────────────────────────────────────────────────────────────────────────

BG_PROMPT = (
    "A lone person sitting at a desk in a dark empty office at night, "
    "seen entirely from behind as a dark silhouette, "
    "cold harsh fluorescent ceiling light casting sharp shadows downward, "
    "heavy rain streaking down floor-to-ceiling window glass, "
    "city lights blurred through rain-covered glass in background, "
    "papers and documents scattered on the desk, "
    "single monitor glowing with cold blue-white light behind the person, "
    "completely empty abandoned office — all other desks empty and dark, "
    "claustrophobic and oppressive atmosphere, "
    "cinematic wide shot, rule of thirds composition, "
    "deep navy-charcoal color palette (#0F1220 to #1E2840), "
    "cold blue-grey tones, zero warm colors, "
    "film noir lighting, Arri Alexa cinematic grade, "
    "photorealistic photography, f/2.8 shallow depth of field, "
    "1080x1080 square format, "
    "no visible face, no text, no logos, no icons, no graphics, "
    "mood: isolation, despair, exhaustion, loneliness"
)

# ─────────────────────────────────────────────────────────────────────────────
# API 설정
# ─────────────────────────────────────────────────────────────────────────────

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


def generate_background() -> None:
    """Gemini API로 배경 이미지를 생성하고 PNG로 저장합니다."""
    print("[배경] Gemini API 토큰 획득 중...")
    token = gcloud_auth.get_access_token()
    print(f"[배경] 토큰 획득 완료 ({len(token)} chars)")

    url = f"{GEMINI_API_BASE}/models/{MODEL_ID}:generateContent"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }
    payload = {
        "contents": [{"parts": [{"text": BG_PROMPT}]}],
        "generationConfig": {
            "responseModalities": ["IMAGE", "TEXT"],
            "temperature": 1.0,
        },
    }

    print(f"[배경] 이미지 생성 요청 중... (모델: {MODEL_ID})")
    start = time.time()
    resp = requests.post(url, headers=headers, json=payload, timeout=300)

    # fallback
    if resp.status_code in (403, 404):
        print(f"[배경] 모델 접근 불가 (HTTP {resp.status_code}). Fallback: {FALLBACK_MODEL_ID}")
        url = f"{GEMINI_API_BASE}/models/{FALLBACK_MODEL_ID}:generateContent"
        resp = requests.post(url, headers=headers, json=payload, timeout=300)

    if not resp.ok:
        print(f"[오류] HTTP {resp.status_code}: {resp.text[:500]}")
        resp.raise_for_status()

    elapsed = time.time() - start
    data = resp.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:
        texts = [p.get("text", "") for p in parts if "text" in p]
        raise RuntimeError(f"이미지 데이터 없음. 텍스트 응답: {texts[:2]}")

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

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

    size = OUTPUT_PATH.stat().st_size
    print(f"[배경] 완료: {OUTPUT_PATH}")
    print(f"[배경] 파일 크기: {size:,} bytes ({size / 1024:.1f} KB)")
    print(f"[배경] 생성 시간: {elapsed:.1f}초")
    print(f"[배경] MIME 타입: {mime}")


def main() -> None:
    print("=" * 60)
    print("Meta 캐러셀 A-2 배경 이미지 재생성 (QC 개선판)")
    print(f"출력: {OUTPUT_PATH}")
    print("=" * 60)
    generate_background()
    print("=" * 60)
    print("완료")
    print("=" * 60)


if __name__ == "__main__":
    main()
