#!/usr/bin/env python3
"""Meta 캐러셀 광고 A-2 (Problem 슬라이드) 하이브리드 이미지 생성.

Gemini API로 배경(어두운 추상 배경 + 미니멀 아이콘 실루엣) 생성 →
Playwright HTML 오버레이로 한글 카피 합성.
출력: 1080x1080 PNG
"""

from __future__ import annotations

import base64
import sys
import time
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright
from gen_config import WORKSPACE_ROOT, FONT_DIR, CTA_MIN_PX

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth  # noqa: E402
_SIZE_26PX = 26
_CTA_PX = CTA_MIN_PX
_SIZE_88PX = 88
_LH_1_18 = 1.18
_LH_1_65 = 1.65

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

OUTPUT_DIR = WORKSPACE_ROOT / "output/meta-ads/a-group-v6/production"
BG_JPEG = OUTPUT_DIR / "_bg_a2_problem.jpg"
OUTPUT_PNG = OUTPUT_DIR / "meta-A2-problem.png"
HTML_TEMP = OUTPUT_DIR / "_a2_problem_template.html"

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

BG_PROMPT = (
    "Dark moody abstract background for a Meta carousel advertisement. "
    "Color palette: deep charcoal (#2D3748) transitioning to near-black — "
    "slightly lighter than pure black but very dark and oppressive. "
    "Subtle faint line-art icons barely visible in the darkness: "
    "(1) an empty contacts / address-book icon at the top — hollow, no entries inside; "
    "(2) a speech bubble filled with question marks in the middle; "
    "(3) a declining line graph / downward trend arrow at the bottom. "
    "All three icons are very faint, ghost-like, almost invisible — just visible enough "
    "to feel their presence without distracting from overlaid text. "
    "Film grain texture across the entire surface for depth and tactile feel. "
    "No people, no hands, no faces, no bright elements, no warm colors. "
    "No text, no watermarks, no numbers. "
    "Slightly lighter than pure black — a heavy, claustrophobic charcoal. "
    "Mood: isolation, dead ends, oppression, silence. "
    "Minimal contrast — nearly monochrome dark charcoal throughout. "
    "Square 1:1 composition 1080x1080. "
    "Cinematic, high quality, minimal digital art."
)

# ─────────────────────────────────────────────────────────────────────────────
# Step 1: Gemini 배경 이미지 생성
# ─────────────────────────────────────────────────────────────────────────────

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


def generate_background() -> Path:
    """Gemini API로 배경 이미지를 생성하고 JPEG로 저장합니다."""
    if BG_JPEG.exists():
        print(f"[배경] 캐시된 배경 이미지 사용: {BG_JPEG}")
        return BG_JPEG

    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"]},
    }

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

    # fallback to pro image model if flash preview unavailable
    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)

    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/jpeg")
    image_bytes = base64.b64decode(image_part["inlineData"]["data"])

    ext = ".jpg" if "jpeg" in mime else ".png"
    save_path = BG_JPEG.with_suffix(ext)
    save_path.write_bytes(image_bytes)
    print(f"[배경] 완료: {save_path.name} ({len(image_bytes):,} bytes, {elapsed:.1f}초)")
    return save_path


# ─────────────────────────────────────────────────────────────────────────────
# Step 2: HTML 오버레이 템플릿 생성
# ─────────────────────────────────────────────────────────────────────────────


def build_html(bg_path: str) -> str:
    """A-2 Problem 슬라이드 HTML 오버레이를 빌드합니다."""
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Black.otf') format('opentype');
    font-weight: 900;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-ExtraBold.otf') format('opentype');
    font-weight: 800;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Medium.otf') format('opentype');
    font-weight: 500;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Regular.otf') format('opentype');
    font-weight: 400;
  }}

  * {{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }}

  body {{
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background: #1A202C;
  }}

  .canvas {{
    width: 1080px;
    height: 1080px;
    position: relative;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    overflow: hidden;
  }}

  /* ─── 배경 이미지 ─── */
  .bg {{
    position: absolute;
    inset: 0;
    background: url('file://{bg_path}') center center / cover no-repeat;
  }}

  /* ─── 전체 어둠 오버레이 — A-1보다 더 무겁게 ─── */
  .overlay-dark {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to bottom,
      rgba(15, 18, 28, 0.88) 0%,
      rgba(15, 18, 28, 0.60) 20%,
      rgba(15, 18, 28, 0.50) 45%,
      rgba(10, 12, 20, 0.72) 72%,
      rgba(6, 8, 14, 0.97) 100%
    );
  }}

  /* ─── 상단 미니멀 공간 (Top 15%) — 전환 강조 ─── */
  /* 아이콘 영역: 1080 * 0.15 = 162px */
  .top-icons {{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 162px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding-left: 64px;
    gap: 48px;
  }}

  /* SVG 아이콘 — line-art 스타일 */
  .icon-svg {{
    opacity: 0.28;
    flex-shrink: 0;
  }}

  /* ─── 헤드라인 영역 (Center 50%) — LEFT 정렬 ─── */
  /* Top 15% ~ 65%: y=162 ~ y=702 */
  .headline-wrap {{
    position: absolute;
    top: 162px;
    left: 64px;
    right: 64px;
    height: 540px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
  }}

  .headline {{
    font-size: {_SIZE_88PX}px;
    font-weight: 900;
    color: #F7F8FA;
    line-height: {_LH_1_18};
    letter-spacing: -3.5px;
    word-break: keep-all;
    text-align: left;
    text-shadow: 0 2px 28px rgba(0,0,0,0.7);
  }}

  /* "방법이 없었던 거다." — 포인트 컬러 강조 */
  .headline .accent {{
    color: #D97706;
    text-shadow:
      0 0 40px rgba(217, 119, 6, 0.40),
      0 2px 24px rgba(0,0,0,0.6);
    font-weight: 900;
  }}

  /* ─── 하단 서브카피 영역 (Bottom 35%) ─── */
  /* y=702 ~ y=1080 */
  .bottom-zone {{
    position: absolute;
    top: 702px;
    left: 0;
    right: 0;
    bottom: 0;
  }}

  /* 하단 어둠 강화 — 텍스트 가독성 보강 */
  .bottom-gradient {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to bottom,
      rgba(6, 8, 14, 0.0) 0%,
      rgba(6, 8, 14, 0.75) 35%,
      rgba(6, 8, 14, 0.95) 100%
    );
  }}

  .subcopy-wrap {{
    position: absolute;
    bottom: 80px;
    left: 64px;
    right: 72px;
  }}

  /* 1번 서브카피 문장 */
  .subcopy-line1 {{
    font-size: {_CTA_PX}px;
    font-weight: 400;
    color: rgba(200, 205, 216, 0.72);
    line-height: {_LH_1_65};
    letter-spacing: -0.8px;
    word-break: keep-all;
    margin-bottom: 20px;
  }}

  /* 2번 서브카피 문장 — 여운을 위한 분리 */
  .subcopy-line2 {{
    font-size: {_CTA_PX}px;
    font-weight: 500;
    color: rgba(218, 220, 230, 0.82);
    line-height: {_LH_1_65};
    letter-spacing: -0.8px;
    word-break: keep-all;
  }}

  /* 페이지 인디케이터 2/5 */
  .page-indicator {{
    position: absolute;
    bottom: 32px;
    right: 52px;
    font-size: {_SIZE_26PX}px;
    font-weight: 500;
    color: rgba(180, 185, 200, 0.45);
    letter-spacing: 2px;
  }}

</style>
</head>
<body>
<div class="canvas">

  <!-- 배경 이미지 -->
  <div class="bg"></div>

  <!-- 전체 어둠 오버레이 -->
  <div class="overlay-dark"></div>

  <!-- 상단 미니멀 아이콘 영역 (Top 15%) -->
  <div class="top-icons">
    <!-- 빈 연락처 아이콘 -->
    <svg class="icon-svg" width="56" height="56" viewBox="0 0 56 56" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect x="4" y="8" width="40" height="40" rx="4" stroke="#C0C8D8" stroke-width="2.5"/>
      <circle cx="24" cy="22" r="6" stroke="#C0C8D8" stroke-width="2.5"/>
      <path d="M12 40c0-6.627 5.373-12 12-12h0c6.627 0 12 5.373 12 12" stroke="#C0C8D8" stroke-width="2.5" stroke-linecap="round"/>
      <line x1="46" y1="14" x2="52" y2="14" stroke="#C0C8D8" stroke-width="2.5" stroke-linecap="round"/>
      <line x1="46" y1="22" x2="52" y2="22" stroke="#C0C8D8" stroke-width="2.5" stroke-linecap="round"/>
      <line x1="46" y1="30" x2="52" y2="30" stroke="#C0C8D8" stroke-width="2.5" stroke-linecap="round"/>
    </svg>

    <!-- 물음표 가득한 말풍선 아이콘 -->
    <svg class="icon-svg" width="56" height="56" viewBox="0 0 56 56" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M6 8h44a2 2 0 0 1 2 2v26a2 2 0 0 1-2 2H20L8 50V38H6a2 2 0 0 1-2-2V10a2 2 0 0 1 2-2z" stroke="#C0C8D8" stroke-width="2.5" stroke-linejoin="round"/>
      <text x="15" y="31" font-family="sans-serif" font-size="18" fill="#C0C8D8" opacity="0.9">???</text>
    </svg>

    <!-- 하락 그래프 아이콘 -->
    <svg class="icon-svg" width="56" height="56" viewBox="0 0 56 56" fill="none" xmlns="http://www.w3.org/2000/svg">
      <polyline points="6,12 6,50 50,50" stroke="#C0C8D8" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
      <polyline points="10,18 22,28 32,24 46,44" stroke="#C0C8D8" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
      <polyline points="40,44 46,44 46,38" stroke="#C0C8D8" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
  </div>

  <!-- 헤드라인 (Center 50%) — LEFT 정렬, 16px 마진 느낌 -->
  <div class="headline-wrap">
    <div class="headline">
      문제는 노력이 아니다.<br>
      <span class="accent">방법이 없었던 거다.</span>
    </div>
  </div>

  <!-- 하단 서브카피 영역 -->
  <div class="bottom-zone">
    <div class="bottom-gradient"></div>
    <div class="subcopy-wrap">
      <p class="subcopy-line1">지인 명단은 바닥났고, 알려줄 멘토도 없었다.</p>
      <p class="subcopy-line2">혼자 버티는 건 미덕이 아니라 손실이다.</p>
    </div>
  </div>

  <!-- 페이지 인디케이터 -->
  <div class="page-indicator">2 / 5</div>

</div>
</body>
</html>"""


# ─────────────────────────────────────────────────────────────────────────────
# Step 3: Playwright 합성
# ─────────────────────────────────────────────────────────────────────────────


def capture_overlay(bg_path: Path) -> None:
    """HTML 오버레이를 Playwright로 캡처하여 최종 PNG를 저장합니다."""
    html_content = build_html(str(bg_path.resolve()))
    HTML_TEMP.write_text(html_content, encoding="utf-8")
    print(f"[오버레이] HTML 템플릿 저장: {HTML_TEMP}")

    print("[오버레이] Playwright 캡처 시작...")
    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            page.goto(f"file://{HTML_TEMP.resolve()}", wait_until="networkidle")
            # 폰트 렌더링 + 이미지 로드 대기
            page.wait_for_timeout(2500)
            OUTPUT_PNG.parent.mkdir(parents=True, exist_ok=True)
            page.screenshot(path=str(OUTPUT_PNG), type="png")
        finally:
            browser.close()

    size = OUTPUT_PNG.stat().st_size
    print(f"[오버레이] 완료: {OUTPUT_PNG} ({size:,} bytes)")


# ─────────────────────────────────────────────────────────────────────────────
# Main
# ─────────────────────────────────────────────────────────────────────────────


def main() -> None:
    print("=" * 60)
    print("Meta 캐러셀 A-2 Problem 이미지 생성 시작")
    print(f"출력: {OUTPUT_PNG}")
    print("=" * 60)

    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    # Step 1: 배경 이미지 생성
    bg_path = generate_background()

    # Step 2 & 3: HTML 오버레이 합성
    capture_overlay(bg_path)

    print("\n" + "=" * 60)
    print(f"완료: {OUTPUT_PNG}")
    print("=" * 60)


if __name__ == "__main__":
    main()
