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

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

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

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

OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/a-group-v6/pilot")
BG_JPEG = OUTPUT_DIR / "_bg_a1_hook.jpg"
OUTPUT_PNG = OUTPUT_DIR / "pilot-A1-hook.png"
HTML_TEMP = OUTPUT_DIR / "_a1_hook_template.html"

FONT_DIR = Path.home() / ".local/share/fonts/Pretendard"

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

BG_PROMPT = (
    "Cinematic still photograph for a Meta ad. "
    "Scene: A densely written paper planner lying open on a dark desk surface, "
    "viewed from slightly above at a low 20-degree angle. "
    "The planner pages are packed with handwritten Korean-style schedule entries, "
    "strikethroughs, question marks, and circled items — conveying exhausting daily grind. "
    "A lone ballpoint pen rests diagonally across the planner. "
    "Faint ink smudges and indentations visible on the paper surface. "
    "NO people, NO hands, NO faces — objects only. "
    "Late-evening atmosphere: fluorescent overhead lights already off, "
    "only faint ambient blue-grey light seeping from an unseen monitor. "
    "Color palette: deep charcoal, cold blue-grey, muted navy. "
    "Zero warmth — no yellows, no oranges in the light. "
    "The bottom 35% of the frame is darkest — fading into near-black. "
    "Shallow depth of field, pen in focus, planner edges softly blurred. "
    "Shot on Sony A7RV, 50mm f/1.8, ISO 3200 — slight film grain visible. "
    "Mood: silent exhaustion, invisible labor, numbness. "
    "1:1 square composition 1080x1080. No text, no watermark."
)

# ─────────────────────────────────────────────────────────────────────────────
# 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-1 Hook 슬라이드 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: #111820;
  }}

  .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;
    /* 상단으로 갈수록 어두워지는 그라디언트 */
    /* 별도 overlay 레이어로 처리 */
  }}

  /* ─── 전체 어둠 오버레이 (분위기) ─── */
  .overlay-dark {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to bottom,
      rgba(8, 11, 20, 0.80) 0%,
      rgba(8, 11, 20, 0.45) 30%,
      rgba(8, 11, 20, 0.25) 50%,
      rgba(8, 11, 20, 0.55) 68%,
      rgba(4, 6, 14, 0.94) 100%
    );
  }}

  /* ─── 상단 숨쉬기 영역 (Top 20%) ─── */
  /* 브랜드 로고 자리 — 현재는 빈 공간 */
  .top-space {{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 216px; /* 1080 * 0.20 */
  }}

  /* ─── 헤드라인 (Center 45%) ─── */
  /* Top 20% ~ 65% 사이: y=216 ~ y=702, 중심 y=459 */
  /* 약간 위로 당겨 시각적 무게중심을 황금비율 위치에 */
  .headline-wrap {{
    position: absolute;
    top: 200px;
    left: 64px;
    right: 64px;
    height: 502px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
  }}

  .headline {{
    font-size: 92px;
    font-weight: 900;
    color: #F0F0F4;
    line-height: 1.15;
    letter-spacing: -4px;
    word-break: keep-all;
    text-shadow: 0 2px 24px rgba(0,0,0,0.6);
  }}

  .headline .accent {{
    color: #D4A843;
    text-shadow: 0 2px 20px rgba(212, 168, 67, 0.35);
  }}

  /* ─── 하단 서브카피 영역 (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(4, 6, 12, 0.0) 0%,
      rgba(4, 6, 12, 0.85) 40%,
      rgba(4, 6, 12, 0.97) 100%
    );
  }}

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

  .subcopy {{
    font-size: 42px;
    font-weight: 400;
    color: rgba(210, 212, 222, 0.68);
    line-height: 1.75;
    letter-spacing: -1px;
    word-break: keep-all;
  }}

  /* 대시 강조 — 목록 단어들 */
  .subcopy .em {{
    color: rgba(225, 226, 234, 0.88);
    font-weight: 500;
  }}

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

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

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

  <!-- 상단 숨쉬기 공간 (브랜드 로고 자리) -->
  <div class="top-space"></div>

  <!-- 헤드라인 (중앙 45%) -->
  <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">
        <span class="em">방문 횟수, 전화 통화, 상담 건수</span>—<br>
        숫자는 쌓이는데 통장은 그대로다.
      </p>
    </div>
  </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-1 Hook 이미지 생성 시작")
    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()
