#!/usr/bin/env python3
"""컨셉 #49 Spikes Asia Trust & Protection Modern Asia
T.O.P 리크루팅 Meta Ad — 매출 1,863% 성장 데이터 앵글
Inspired by Spikes Asia finance/insurance category award winners:
  - ACKO Insurance "Acko Tailor" (personalised insurance)
  - Suncorp "Haven" (market disruption)
"""

import base64
import shutil
import sys
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth

# ── 경로 설정 ──────────────────────────────────────────────────────────────
OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/concept-catalog/49-spikes-trust-protection")
BG_PATH = OUTPUT_DIR / "bg.jpg"
SAMPLE_PATH = OUTPUT_DIR / "sample.png"
COPY_PATH = OUTPUT_DIR / "49-spikes-trust-protection.png"

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"

# ── Gemini 배경 프롬프트 ─────────────────────────────────────────────────
BG_PROMPT = (
    "Professional financial data visualization background, "
    "deep navy blue (#003366) and forest green (#2D7A6E) color palette, "
    "abstract upward-trending chart lines and data graph elements, "
    "subtle glowing grid lines forming a financial dashboard aesthetic, "
    "very thin luminous lines showing exponential growth curves rising from bottom-left to upper-right, "
    "warm amber/gold (#FFB81C) accent lines for key trend indicators, "
    "dark deep blue background (90% darkness, very deep navy), "
    "green geometric shapes and data points scattered elegantly, "
    "cinematic lighting, professional financial services editorial photography aesthetic, "
    "inspired by Spikes Asia award-winning insurance campaign visuals, "
    "modern Asia trust and protection theme, "
    "clean minimalist data-driven composition, "
    "no text, no numbers, no watermarks, "
    "square 1:1 format 1080x1080px"
)

# ── HTML 오버레이 템플릿 ──────────────────────────────────────────────────
HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;500;700;900&family=Noto+Serif+KR:wght@700;900&display=swap" rel="stylesheet">
<style>
  @font-face {
    font-family: 'Pretendard';
    src: local('Pretendard-Black');
    font-weight: 900;
  }
  @font-face {
    font-family: 'Pretendard';
    src: local('Pretendard-Bold');
    font-weight: 700;
  }
  @font-face {
    font-family: 'Pretendard';
    src: local('Pretendard-Medium');
    font-weight: 500;
  }
  @font-face {
    font-family: 'Pretendard';
    src: local('Pretendard-Regular');
    font-weight: 400;
  }

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

  body {
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background-color: #001A33;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }

  .container {
    position: relative;
    width: 1080px;
    height: 1080px;
    background-image: url('__BG_PATH__');
    background-size: cover;
    background-position: center;
  }

  /* 전체 오버레이 — 가독성 보장 */
  .overlay-gradient {
    position: absolute;
    inset: 0;
    background: linear-gradient(
      160deg,
      rgba(0, 20, 51, 0.88) 0%,
      rgba(0, 30, 60, 0.75) 30%,
      rgba(0, 40, 60, 0.65) 55%,
      rgba(0, 20, 40, 0.90) 80%,
      rgba(0, 10, 30, 0.96) 100%
    );
  }

  /* 상단 amber 강조 바 */
  .top-bar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 8px;
    background: linear-gradient(90deg, #FFB81C 0%, #FF8C00 50%, #2D7A6E 100%);
  }

  /* 좌측 상단 — 브랜드 태그 */
  .brand-tag {
    position: absolute;
    top: 48px;
    left: 64px;
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .brand-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #FFB81C;
    flex-shrink: 0;
  }

  .brand-name {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 32px;
    font-weight: 700;
    color: rgba(255, 184, 28, 0.90);
    letter-spacing: 0.12em;
    text-transform: uppercase;
  }

  /* 우측 상단 — 카테고리 레이블 */
  .category-label {
    position: absolute;
    top: 50px;
    right: 64px;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 26px;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.38);
    letter-spacing: 0.08em;
  }

  /* ── 상단 섹션 — 헤드라인 ───────────────────────────────── */
  .top-section {
    position: absolute;
    top: 120px;
    left: 64px;
    right: 64px;
  }

  /* 서브 카피 (헤드라인 위) */
  .sub-eyebrow {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 36px;
    font-weight: 500;
    color: #2D7A6E;
    letter-spacing: 0.06em;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .sub-eyebrow::before {
    content: '';
    display: inline-block;
    width: 40px;
    height: 3px;
    background: #2D7A6E;
    flex-shrink: 0;
  }

  /* 메인 헤드라인 */
  .headline {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 88px;
    font-weight: 900;
    color: #FFFFFF;
    line-height: 1.15;
    letter-spacing: -0.02em;
  }

  .headline .accent {
    color: #FFB81C;
  }

  /* ── 중앙 섹션 — 핵심 데이터 카드 ──────────────────────── */
  .data-card-section {
    position: absolute;
    top: 400px;
    left: 64px;
    right: 64px;
  }

  /* 성장 수치 히어로 */
  .hero-stat {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 128px;
    font-weight: 900;
    color: #FFB81C;
    line-height: 1.0;
    letter-spacing: -0.03em;
    display: flex;
    align-items: flex-end;
    gap: 16px;
  }

  .hero-stat .stat-label {
    font-size: 42px;
    font-weight: 700;
    color: rgba(255, 184, 28, 0.75);
    padding-bottom: 16px;
    letter-spacing: -0.01em;
  }

  /* 서브 카피 라인 */
  .sub-copy {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 64px;
    font-weight: 700;
    color: rgba(255, 255, 255, 0.88);
    line-height: 1.25;
    letter-spacing: -0.02em;
    margin-top: 16px;
  }

  /* 구분선 */
  .divider {
    width: 100%;
    height: 1px;
    background: linear-gradient(90deg, rgba(45, 122, 110, 0.8) 0%, rgba(255, 184, 28, 0.4) 50%, transparent 100%);
    margin: 32px 0;
  }

  /* 조직 성장 데이터 라인 */
  .org-data {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 42px;
    font-weight: 700;
    color: rgba(255, 255, 255, 0.82);
    letter-spacing: -0.01em;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .org-data .arrow-up {
    color: #2D7A6E;
    font-size: 36px;
  }

  .org-data .highlight {
    color: #FFB81C;
  }

  /* ── 하단 CTA 섹션 ───────────────────────────────────────── */
  .cta-section {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 160px;
    background: linear-gradient(135deg, #2D7A6E 0%, #1E5F54 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 64px;
  }

  .cta-text-block {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .cta-label {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 30px;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.65);
    letter-spacing: 0.04em;
  }

  .cta-button-text {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 52px;
    font-weight: 900;
    color: #FFFFFF;
    letter-spacing: -0.01em;
  }

  /* CTA 오른쪽 — 화살표 버튼 */
  .cta-arrow-btn {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: #FFB81C;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .cta-arrow-btn span {
    font-size: 40px;
    color: #003366;
    font-weight: 900;
    line-height: 1;
  }

  /* 우측 — 트러스트 배지 */
  .trust-badge {
    position: absolute;
    top: 48px;
    right: 64px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 4px;
  }
</style>
</head>
<body>
<div class="container">
  <div class="overlay-gradient"></div>

  <!-- 상단 amber 강조 바 -->
  <div class="top-bar"></div>

  <!-- 브랜드 태그 -->
  <div class="brand-tag">
    <div class="brand-dot"></div>
    <div class="brand-name">T.O.P 사업단</div>
  </div>

  <!-- 카테고리 레이블 -->
  <div class="category-label">META AD</div>

  <!-- 상단: 헤드라인 섹션 -->
  <div class="top-section">
    <div class="sub-eyebrow">성장의 이유가 있습니다</div>
    <div class="headline">매출 <span class="accent">1,863%</span><br>성장의 비결</div>
  </div>

  <!-- 중앙: 데이터 카드 섹션 -->
  <div class="data-card-section">
    <div class="sub-copy">정체된 곳에서<br>시간을 낭비하지 마세요</div>

    <div class="divider"></div>

    <div class="org-data">
      <span class="arrow-up">▲</span>
      T.O.P 사업단&nbsp;
      <span class="highlight">482명 → 5,500명</span>
      &nbsp;폭발적 성장 조직
    </div>
  </div>

  <!-- 하단: CTA -->
  <div class="cta-section">
    <div class="cta-text-block">
      <div class="cta-label">지금 바로 확인하세요</div>
      <div class="cta-button-text">조건 확인하기</div>
    </div>
    <div class="cta-arrow-btn">
      <span>→</span>
    </div>
  </div>

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


def generate_background() -> bool:
    """Gemini SA 토큰으로 배경 이미지를 생성합니다."""
    print("  SA 토큰 획득 중...")
    sa_token = gcloud_auth.get_service_account_token("https://www.googleapis.com/auth/generative-language")
    if not sa_token:
        print("  [오류] SA 토큰 없음")
        return False
    headers = {"Authorization": f"Bearer {sa_token}", "Content-Type": "application/json"}
    models_to_try = [
        "gemini-2.0-flash-preview-image-generation",
        "gemini-3.1-flash-image-preview",
        "gemini-3-pro-image-preview",
    ]
    for model in models_to_try:
        url = f"{GEMINI_API_BASE}/models/{model}:generateContent"
        payload = {
            "contents": [{"parts": [{"text": BG_PROMPT}]}],
            "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]},
        }
        print(f"  배경 생성 요청 중... (모델: {model})")
        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=120)
        except Exception as e:
            print(f"  [오류] 연결 실패: {e}")
            continue
        if resp.status_code == 200:
            data = resp.json()
            for part in data.get("candidates", [{}])[0].get("content", {}).get("parts", []):
                if "inlineData" in part:
                    img_bytes = base64.b64decode(part["inlineData"]["data"])
                    BG_PATH.write_bytes(img_bytes)
                    print(f"  배경 저장 완료: {BG_PATH} ({len(img_bytes):,} bytes)")
                    return True
            reason = data.get("candidates", [{}])[0].get("finishReason", "?")
            print(f"  [오류] 이미지 파트 없음 (finishReason: {reason})")
            print(f"  응답: {str(data)[:300]}")
        else:
            print(f"  [HTTP {resp.status_code}] {resp.text[:200]}")
    return False


def render_html(html_content: str) -> bool:
    """Playwright로 HTML을 PNG로 캡처합니다."""
    html_file = OUTPUT_DIR / "overlay49.html"
    html_file.write_text(html_content, encoding="utf-8")
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": 1080, "height": 1080})
        page.goto(f"file://{html_file}")
        # 웹폰트 로딩 및 렌더링 대기
        page.wait_for_timeout(3500)
        page.screenshot(path=str(SAMPLE_PATH), type="png")
        browser.close()
    print(f"  PNG 저장 완료: {SAMPLE_PATH}")
    return True


def main():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    print("=" * 65)
    print("컨셉 #49 Spikes Asia Trust & Protection Modern Asia 생성")
    print("T.O.P 리크루팅 Meta Ad — 매출 1,863% 성장 데이터 앵글")
    print("=" * 65)

    print("\n[1/3] 배경 이미지 생성 (Gemini AI)...")
    ok = generate_background()
    if not ok:
        print("  [경고] 배경 생성 실패. 순수 딥네이비 배경으로 대체합니다.")

    print("\n[2/3] HTML 오버레이 렌더링 (Playwright)...")
    if BG_PATH.exists() and BG_PATH.stat().st_size > 0:
        bg_url = f"file://{BG_PATH}"
    else:
        bg_url = ""
    html = HTML_TEMPLATE.replace("__BG_PATH__", bg_url)
    render_html(html)

    print("\n[3/3] 복사본 생성...")
    shutil.copy2(SAMPLE_PATH, COPY_PATH)
    print(f"  복사 완료: {COPY_PATH}")

    print(f"\n완료!")
    print(f"  sample.png : {SAMPLE_PATH}")
    print(f"  named copy : {COPY_PATH}")


if __name__ == "__main__":
    main()
