#!/usr/bin/env python3
"""
Production A-5 (CTA) — Meta Carousel Slide (밝은 톤 재제작)
밝고 따뜻한 크림/골드 톤 — A-4와 연속되는 캐러셀 클라이맥스
Hybrid: Gemini background + Playwright HTML overlay
Output: /home/jay/workspace/output/meta-ads/a-group-v6/production/meta-A5-cta.png
"""

import base64
import sys
import time
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright

# ── paths ──────────────────────────────────────────────────────────────────────
OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/a-group-v6/production")
BG_PATH    = OUTPUT_DIR / "_bg_a5_cta.jpg"
HTML_PATH  = OUTPUT_DIR / "_a5_cta_template.html"
OUT_PATH   = OUTPUT_DIR / "meta-A5-cta.png"
FONT_DIR   = Path.home() / ".local/share/fonts/Pretendard"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

# ── Gemini config ──────────────────────────────────────────────────────────────
sys.path.insert(0, "/home/jay/workspace/tools/ai-image-gen")
import gcloud_auth  # noqa: E402

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
MODEL_PRIMARY   = "gemini-3-pro-image-preview"
MODEL_FALLBACK  = "gemini-3.1-flash-image-preview"
MODEL_FALLBACK2 = "gemini-2.5-flash-preview-04-17"
SCOPE           = "https://www.googleapis.com/auth/generative-language"

BG_PROMPT = """
Warm bright morning sunlight streaming through large modern windows into a premium consultancy office.
Soft golden light particles floating in the air. Warm cream and gold color palette dominant.
Bright, hopeful, professional atmosphere. Shallow depth of field, bokeh effect.
No people, no text, no furniture in focus. High-end commercial photography style. Square format 1:1.

COMPOSITION: 1:1 square, 1080x1080px. Full bleed. No text, no people, no faces.

VISUAL CONCEPT:
Luxurious bright morning scene — a premium consulting or financial advisory office space
bathed in warm golden morning sunlight. Light streams dramatically through floor-to-ceiling
windows, creating beautiful lens flares and golden bokeh particles. The space feels aspirational,
warm, and achievable — the "destination" at the end of a journey.

BACKGROUND ELEMENTS:
- Warm cream / ivory base (#F5F0E8 family) — bright and luminous
- Brilliant warm golden sunlight (#E8C870 / #C9A84C tones) streaming from upper-right or upper-center
- Soft bokeh circles — warm gold and cream tones, out-of-focus background elements
- Very subtle architectural lines (window frames, clean edges) just barely visible
- Golden light particles / dust motes floating in the air, catching light
- Top-center: brightest area — convergence of light rays
- Overall: luminous, airy, premium, "threshold of success" feeling

MOOD / ATMOSPHERE:
- Achievement. Clarity. Warmth. Forward momentum.
- The brightest, most hopeful moment in a journey
- Premium Korean financial advisory aesthetics
- "Just one more step" — action-ready, confident energy
- Continuation of a warm cream background series (matching slide 4)

COLOR PALETTE:
- Primary: Warm cream (#F5F0E8), golden ivory (#F0E8D0), bright off-white
- Golden accent glow: #C9A84C to #E8C870 — warm, rich, visible but not harsh
- No dark tones whatsoever — this is the bright payoff slide
- No cool tones — only warm cream/gold/ivory family
- Maximum warmth and luminosity

STYLE REQUIREMENTS:
- NO people, faces, hands, or figures
- NO text, numbers, labels, or UI elements
- NO dark zones — keep entire image bright and luminous
- Photorealistic commercial photography quality
- Premium advertising background — supportive of overlaid text
- The content overlay will use dark text (#1A202C), so background must remain bright
- Ensure center-bottom area has some texture/depth for CTA button visibility
"""

# ── Step 1: Generate Gemini background ────────────────────────────────────────

def generate_background() -> Path:
    if BG_PATH.exists():
        print(f"[BG] 기존 배경 이미지 재사용: {BG_PATH}")
        return BG_PATH

    print("[BG] Gemini API로 배경 이미지 생성 중...")
    token = gcloud_auth.get_service_account_token(SCOPE)

    def _call(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": BG_PROMPT}]}],
            "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
        }
        return requests.post(url, headers=headers, json=payload, timeout=300)

    t0 = time.time()
    for model_id in [MODEL_PRIMARY, MODEL_FALLBACK, MODEL_FALLBACK2]:
        print(f"  -> 모델 시도: {model_id}")
        try:
            resp = _call(model_id)
        except Exception as e:
            print(f"  [WARN] 요청 실패: {e}")
            continue

        if resp.status_code in (403, 404, 429):
            print(f"  [WARN] HTTP {resp.status_code} — 다음 모델 시도")
            continue

        try:
            resp.raise_for_status()
        except requests.HTTPError as e:
            print(f"  [ERROR] HTTP {e.response.status_code}: {e.response.text[:300]}")
            continue

        data = resp.json()
        candidates = data.get("candidates", [])
        if not candidates:
            print(f"  [WARN] candidates 없음: {str(data)[:200]}")
            continue

        parts = candidates[0].get("content", {}).get("parts", [])
        img_part = next((p for p in parts if "inlineData" in p), None)
        if img_part is None:
            texts = [p.get("text", "") for p in parts if "text" in p]
            print(f"  [WARN] 이미지 없음. 텍스트: {texts[:2]}")
            continue

        mime  = img_part["inlineData"].get("mimeType", "image/jpeg")
        b64   = img_part["inlineData"]["data"]
        ext   = ".jpg" if "jpeg" in mime else ".png"
        fpath = BG_PATH.with_suffix(ext)
        fpath.write_bytes(base64.b64decode(b64))
        print(f"[BG] 완료: {fpath.name} ({fpath.stat().st_size:,} bytes, {time.time()-t0:.1f}초)")
        return fpath

    raise RuntimeError("[BG] 모든 모델 시도 실패")


# ── Step 2: Build HTML overlay ──────────────────────────────────────────────────

def build_html(bg_path: Path) -> str:
    bg_url = f"file://{bg_path.resolve()}"
    font_dir = str(FONT_DIR)

    return f"""<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{font_dir}/PretendardVariable.ttf') format('truetype');
    font-weight: 100 900;
  }}
  @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; }}

  html, body {{
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background: #F5F0E8;
  }}

  /* ── Canvas: background image ── */
  .canvas {{
    width: 1080px;
    height: 1080px;
    position: relative;
    background-image: url('{bg_url}');
    background-size: cover;
    background-position: center center;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    overflow: hidden;
  }}

  /* ── Very light warm overlay — preserves bright background ── */
  .overlay {{
    position: absolute;
    inset: 0;
    background:
      radial-gradient(ellipse 80% 60% at 50% 42%, rgba(255, 252, 240, 0.35) 0%, transparent 70%),
      linear-gradient(
        180deg,
        rgba(255, 252, 245, 0.45) 0%,
        rgba(255, 250, 238, 0.25) 25%,
        rgba(245, 240, 228, 0.10) 55%,
        rgba(240, 234, 215, 0.35) 80%,
        rgba(235, 228, 210, 0.55) 100%
      );
    pointer-events: none;
  }}

  /* All content above overlay */
  .content {{
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 64px;
  }}

  /* ── PAGE INDICATOR (top-right absolute) ── */
  .page-indicator {{
    position: absolute;
    top: 52px;
    right: 58px;
    font-family: 'Pretendard', sans-serif;
    font-size: 22px;
    font-weight: 500;
    color: rgba(120, 100, 60, 0.55);
    letter-spacing: 0.06em;
    z-index: 10;
  }}

  /* ── BRAND LOGO — top center (10%) ── */
  .brand-logo {{
    margin-top: 54px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    flex-shrink: 0;
  }}

  .brand-emblem svg {{
    width: 56px;
    height: 56px;
    filter: drop-shadow(0 2px 10px rgba(201, 168, 76, 0.55));
  }}

  .brand-name {{
    font-family: 'Pretendard', sans-serif;
    font-size: 22px;
    font-weight: 700;
    color: #C9A84C;
    letter-spacing: 0.05em;
    text-shadow: 0 1px 4px rgba(255,255,255,0.7);
  }}

  /* ── HEADLINE SECTION — center ── */
  .headline-section {{
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 0 20px;
    margin-top: -10px;
  }}

  .headline {{
    font-family: 'Pretendard', sans-serif;
    font-size: 68px;
    font-weight: 900;
    line-height: 1.22;
    letter-spacing: -0.030em;
    color: #1A202C;
    word-break: keep-all;
    margin-bottom: 32px;
  }}

  .headline .accent {{
    color: #C9A84C;
    font-weight: 900;
    text-decoration: underline;
    text-decoration-color: rgba(201, 168, 76, 0.65);
    text-decoration-thickness: 3px;
    text-underline-offset: 7px;
  }}

  /* ── Gold divider: line-dot-line ── */
  .divider {{
    display: flex;
    align-items: center;
    gap: 14px;
    width: 100%;
    max-width: 520px;
    margin-bottom: 30px;
  }}

  .divider-line {{
    flex: 1;
    height: 1.5px;
    background: linear-gradient(90deg, transparent, rgba(201, 168, 76, 0.55), transparent);
  }}

  .divider-dot {{
    width: 7px;
    height: 7px;
    background: #C9A84C;
    border-radius: 50%;
    flex-shrink: 0;
    box-shadow: 0 0 6px rgba(201, 168, 76, 0.70);
  }}

  /* ── SUBCOPY ── */
  .subcopy {{
    font-family: 'Pretendard', sans-serif;
    font-size: 36px;
    font-weight: 400;
    line-height: 1.68;
    color: rgba(40, 40, 50, 0.80);
    text-align: center;
    word-break: keep-all;
    letter-spacing: -0.01em;
  }}

  /* ── BOTTOM SECTION ── */
  .bottom-section {{
    width: 100%;
    padding: 0 0 56px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 22px;
    flex-shrink: 0;
  }}

  /* ── CTA BUTTON ── */
  .cta-btn {{
    width: 100%;
    max-width: 860px;
    background: linear-gradient(
      135deg,
      #C9A84C 0%,
      #E8C870 40%,
      #D4AD52 70%,
      #B8922A 100%
    );
    color: #ffffff;
    font-family: 'Pretendard', sans-serif;
    font-size: 46px;
    font-weight: 900;
    letter-spacing: -0.02em;
    text-align: center;
    padding: 34px 48px;
    border-radius: 18px;
    word-break: keep-all;
    box-shadow:
      0 0 48px rgba(201, 168, 76, 0.50),
      0 8px 32px rgba(0, 0, 0, 0.20),
      inset 0 2px 0 rgba(255, 255, 255, 0.38),
      inset 0 -3px 0 rgba(0, 0, 0, 0.12);
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
    position: relative;
    overflow: hidden;
  }}

  .cta-btn::after {{
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 48%;
    background: linear-gradient(180deg, rgba(255,255,255,0.18) 0%, transparent 100%);
    border-radius: 18px 18px 0 0;
  }}

  /* ── TRUST ANCHOR ── */
  .trust-row {{
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
  }}

  .trust-item {{
    display: flex;
    align-items: center;
    gap: 7px;
    font-family: 'Pretendard', sans-serif;
    font-size: 26px;
    font-weight: 500;
    color: rgba(80, 80, 90, 0.60);
    letter-spacing: 0.01em;
  }}

  .trust-icon {{
    width: 20px;
    height: 20px;
    flex-shrink: 0;
  }}

  .trust-sep {{
    width: 4px;
    height: 4px;
    background: rgba(201, 168, 76, 0.45);
    border-radius: 50%;
    flex-shrink: 0;
  }}

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

  <!-- Warm overlay -->
  <div class="overlay"></div>

  <!-- Page indicator (absolute) -->
  <div class="page-indicator">5 / 5</div>

  <!-- Content layer -->
  <div class="content">

    <!-- BRAND LOGO: top center -->
    <div class="brand-logo">
      <div class="brand-emblem">
        <svg viewBox="0 0 54 54" fill="none" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="goldGrad" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" style="stop-color:#E8C870"/>
              <stop offset="50%" style="stop-color:#C9A84C"/>
              <stop offset="100%" style="stop-color:#B8922A"/>
            </linearGradient>
          </defs>
          <!-- Shield outline -->
          <path d="M27 4 L47 13.5 L47 31 C47 41.5 37 48.5 27 51.5 C17 48.5 7 41.5 7 31 L7 13.5 Z"
                fill="rgba(201,168,76,0.12)" stroke="url(#goldGrad)" stroke-width="1.8"/>
          <!-- Star -->
          <path d="M27 14.5 L29.6 22.2 L37.8 22.2 L31.2 27.0 L33.8 34.7 L27 29.9 L20.2 34.7 L22.8 27.0 L16.2 22.2 L24.4 22.2 Z"
                fill="url(#goldGrad)"/>
        </svg>
      </div>
      <div class="brand-name">서울대보험쌤</div>
    </div>

    <!-- HEADLINE SECTION: center -->
    <div class="headline-section">
      <h1 class="headline">
        전략을 바꿀 준비가 됐다면,<br>지금 <span class="accent">딱 한 번</span> 물어보세요.
      </h1>

      <!-- Divider: line-dot-line -->
      <div class="divider">
        <div class="divider-line"></div>
        <div class="divider-dot"></div>
        <div class="divider-line"></div>
      </div>

      <!-- Subcopy -->
      <p class="subcopy">
        서울대보험쌤 팀장이 직접 답합니다.<br>조건 없는 상담, 당신 상황에 맞는 방향 제시.
      </p>
    </div>

    <!-- BOTTOM: CTA + Trust -->
    <div class="bottom-section">

      <!-- CTA Button -->
      <div class="cta-btn">무료 상담 신청하기</div>

      <!-- Trust anchor -->
      <div class="trust-row">
        <div class="trust-item">
          <!-- Star icon -->
          <svg class="trust-icon" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M10 2.5L11.9 7.8L17.5 7.8L13.1 11.3L14.9 16.6L10 13.1L5.1 16.6L6.9 11.3L2.5 7.8L8.1 7.8Z"
                  fill="#C9A84C"/>
          </svg>
          조건 없음
        </div>
        <div class="trust-sep"></div>
        <div class="trust-item">
          <!-- Check circle icon -->
          <svg class="trust-icon" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="10" cy="10" r="8" stroke="#C9A84C" stroke-width="1.6"/>
            <circle cx="10" cy="10" r="3" fill="#C9A84C"/>
          </svg>
          무료 상담
        </div>
        <div class="trust-sep"></div>
        <div class="trust-item">
          <!-- Person icon -->
          <svg class="trust-icon" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="10" cy="7" r="3.5" stroke="#C9A84C" stroke-width="1.6"/>
            <path d="M3.5 18C3.5 14.9 6.4 12.5 10 12.5C13.6 12.5 16.5 14.9 16.5 18"
                  stroke="#C9A84C" stroke-width="1.6" stroke-linecap="round"/>
          </svg>
          팀장 직접 응대
        </div>
      </div>

    </div>

  </div><!-- /content -->
</div><!-- /canvas -->
</body>
</html>"""


def write_html(bg_path: Path) -> Path:
    html_content = build_html(bg_path)
    HTML_PATH.write_text(html_content, encoding="utf-8")
    print(f"[HTML] 오버레이 저장: {HTML_PATH}")
    return HTML_PATH


# ── Step 3: Playwright screenshot ─────────────────────────────────────────────

def capture(html_path: Path, out_path: Path) -> None:
    print("[RENDER] Playwright 캡처 시작...")
    with sync_playwright() as p:
        browser = p.chromium.launch(args=["--no-sandbox", "--disable-dev-shm-usage"])
        try:
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            page.goto(f"file://{html_path.resolve()}", wait_until="networkidle")
            # Wait for fonts and background image
            page.evaluate("async () => { await document.fonts.ready; }")
            page.wait_for_timeout(3000)
            out_path.parent.mkdir(parents=True, exist_ok=True)
            page.screenshot(
                path=str(out_path),
                type="png",
                clip={"x": 0, "y": 0, "width": 1080, "height": 1080},
            )
        finally:
            browser.close()
    size_kb = out_path.stat().st_size / 1024
    print(f"[RENDER] 완료: {out_path} ({size_kb:.0f} KB)")


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

if __name__ == "__main__":
    t_start = time.time()
    print("=" * 60)
    print("Production A-5 (CTA) — 밝은 톤 재제작")
    print(f"출력: {OUT_PATH}")
    print("=" * 60)

    bg = generate_background()
    html = write_html(bg)
    capture(html, OUT_PATH)

    elapsed = time.time() - t_start
    print(f"\n[완료] {OUT_PATH.name}  ({elapsed:.1f}초 총 소요)")
    if OUT_PATH.exists():
        print(f"       파일 크기: {OUT_PATH.stat().st_size / 1024:.0f} KB")
        print(f"       경로: {OUT_PATH}")
