#!/usr/bin/env python3
"""컨셉 #48 MAD Stars Digital Interactive — T.O.P Recruiting Meta Ad.

Inspired by MAD Stars (Busan International Ad Festival) Digital Category winners:
- Dentsu "My Japan Railway"
- McDonald's "Fries Beat"
- Apple "Shot on iPhone"

Style: Electric blue + coral on dark navy, tech-forward, AI era messaging.
"""

import base64
import shutil
import sys
from pathlib import Path

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

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth
_SIZE_22PX = 22
_SIZE_26PX = 26
_SIZE_32PX = 32
_CTA_PX = CTA_MIN_PX
_SIZE_42PX = 42
_SIZE_46PX = 46
_SIZE_52PX = 52
_SIZE_68PX = 68
_METRIC_PX = CORE_METRIC_MIN_PX
_LH_1_1 = 1.1
_LH_1_2 = 1.2
_LH_1_4 = 1.4

# ── 경로 설정 ──────────────────────────────────────────────────────────────
OUTPUT_DIR = WORKSPACE_ROOT / "output/meta-ads/concept-catalog/48-madstars-digital-interactive"
BG_PATH = OUTPUT_DIR / "bg.jpg"
SAMPLE_PATH = OUTPUT_DIR / "sample.png"
COPY_PATH = OUTPUT_DIR / "48-madstars-digital-interactive.png"

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

# ── Gemini 배경 프롬프트 ────────────────────────────────────────────────────
BG_PROMPT = (
    "Abstract futuristic digital network visualization, dark navy blue background (#1A1A2E), "
    "glowing cyan and electric blue (#0099FF) node connection lines forming an interconnected network graph, "
    "bright luminous data nodes at intersection points with a soft cyan glow, "
    "diagonal light streak from top-right to bottom-left in electric blue with motion blur, "
    "subtle floating particles of light scattered across the frame, "
    "large semi-transparent circular gradient orb in bottom-right corner in deep blue, "
    "abstract circuit board micro-patterns faintly visible in the bottom-left corner, "
    "deep space atmosphere with depth layers — foreground nodes bright, background nodes dim, "
    "cinematic wide bokeh, volumetric light rays, "
    "overall mood: premium tech startup, AI-powered, futuristic fintech, "
    "color palette: #1A1A2E background, #0099FF cyan glows, no orange elements in background, "
    "square 1:1 format, no text, no watermarks, ultra high definition"
)

# ── HTML 오버레이 ───────────────────────────────────────────────────────────
HTML_TEMPLATE = """<!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-SemiBold.otf') format('opentype');
    font-weight: 600;
  }
  @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: #1A1A2E;
  }

  .canvas {
    position: relative;
    width: 1080px;
    height: 1080px;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    background-color: #1A1A2E;
    background-image: url('__BG_PATH__');
    background-size: cover;
    background-position: center;
    overflow: hidden;
  }

  /* 다크 오버레이 그라디언트 — 왼쪽 텍스트 영역 가독성 확보 */
  .dark-overlay {
    position: absolute;
    inset: 0;
    background: linear-gradient(
      105deg,
      rgba(10, 10, 30, 0.82) 0%,
      rgba(15, 15, 40, 0.72) 50%,
      rgba(10, 10, 30, 0.45) 100%
    );
  }

  /* 왼쪽 강조 바 — coral/orange accent */
  .left-accent-bar {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 10px;
    background: linear-gradient(
      to bottom,
      #FF6B35 0%,
      #FF8C5A 50%,
      #FF6B35 100%
    );
    box-shadow: 0 0 20px rgba(255, 107, 53, 0.6);
  }

  /* 상단 레이블 */
  .top-label {
    position: absolute;
    top: 72px;
    left: 72px;
    font-size: {_SIZE_26PX}px;
    font-weight: 500;
    color: #0099FF;
    letter-spacing: 0.18em;
    text-transform: uppercase;
  }

  /* 레이블 하단 구분선 */
  .label-rule {
    position: absolute;
    top: 116px;
    left: 72px;
    width: 160px;
    height: 2px;
    background: linear-gradient(to right, #0099FF, rgba(0,153,255,0));
  }

  /* 헤드라인 블록 */
  .headline-block {
    position: absolute;
    top: 148px;
    left: 72px;
    right: 80px;
  }

  .headline {
    font-size: {_METRIC_PX}px;
    font-weight: 900;
    color: #FFFFFF;
    line-height: {_LH_1_1};
    letter-spacing: -0.03em;
    text-shadow:
      0 0 40px rgba(0, 153, 255, 0.4),
      0 2px 12px rgba(0, 0, 0, 0.6);
  }

  /* 서브 헤드라인 */
  .sub-block {
    position: absolute;
    top: 374px;
    left: 72px;
    right: 80px;
  }

  .sub-line-1 {
    font-size: {_SIZE_68PX}px;
    font-weight: 700;
    color: #FFFFFF;
    line-height: {_LH_1_2};
    letter-spacing: -0.02em;
  }

  .sub-line-2 {
    font-size: {_SIZE_68PX}px;
    font-weight: 700;
    color: #0099FF;
    line-height: {_LH_1_2};
    letter-spacing: -0.02em;
    margin-top: 4px;
    text-shadow: 0 0 24px rgba(0, 153, 255, 0.55);
  }

  /* 구분 장식 */
  .dot-row {
    position: absolute;
    top: 566px;
    left: 72px;
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #0099FF;
    box-shadow: 0 0 8px rgba(0, 153, 255, 0.8);
  }

  .dot-line {
    width: 80px;
    height: 2px;
    background: linear-gradient(to right, #0099FF, rgba(0,153,255,0.2));
  }

  /* 본문 텍스트 */
  .body-text {
    position: absolute;
    top: 606px;
    left: 72px;
    right: 80px;
    font-size: {_SIZE_42PX}px;
    font-weight: 500;
    color: #B0C4DE;
    letter-spacing: -0.01em;
    line-height: {_LH_1_4};
  }

  /* CTA 버튼 */
  .cta-wrapper {
    position: absolute;
    top: 716px;
    left: 72px;
  }

  .cta-btn {
    display: inline-flex;
    align-items: center;
    gap: 16px;
    font-size: {_SIZE_46PX}px;
    font-weight: 800;
    color: #FFFFFF;
    background: #FF6B35;
    padding: 22px 52px;
    border-radius: 8px;
    letter-spacing: -0.01em;
    box-shadow:
      0 4px 24px rgba(255, 107, 53, 0.5),
      0 0 40px rgba(255, 107, 53, 0.25);
  }

  .cta-arrow {
    font-size: {_SIZE_46PX}px;
    font-weight: 900;
  }

  /* 하단 브랜드 영역 */
  .bottom-brand {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 180px;
    background: linear-gradient(
      to top,
      rgba(10, 10, 30, 0.95) 0%,
      rgba(10, 10, 30, 0.85) 60%,
      rgba(10, 10, 30, 0) 100%
    );
  }

  .brand-row {
    position: absolute;
    bottom: 68px;
    left: 72px;
    right: 72px;
    display: flex;
    align-items: baseline;
    justify-content: space-between;
  }

  .brand-name {
    font-size: {_SIZE_52PX}px;
    font-weight: 900;
    color: #FFFFFF;
    letter-spacing: -0.02em;
  }

  .brand-name span {
    color: #0099FF;
    margin-left: 8px;
  }

  .brand-tagline {
    font-size: {_SIZE_32PX}px;
    font-weight: 400;
    color: rgba(176, 196, 222, 0.65);
    letter-spacing: 0.02em;
  }

  /* 우상단 장식 — T mark */
  .top-right-mark {
    position: absolute;
    top: 56px;
    right: 64px;
    width: 72px;
    height: 72px;
    border: 2.5px solid rgba(0, 153, 255, 0.45);
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: {_CTA_PX}px;
    font-weight: 900;
    color: rgba(0, 153, 255, 0.65);
    letter-spacing: -0.02em;
  }

  /* 수직 서브 레이블 */
  .vertical-label {
    position: absolute;
    top: 200px;
    right: 52px;
    font-size: {_SIZE_22PX}px;
    font-weight: 400;
    color: rgba(0, 153, 255, 0.35);
    letter-spacing: 0.2em;
    text-transform: uppercase;
    writing-mode: vertical-rl;
    text-orientation: mixed;
  }
</style>
</head>
<body>
<div class="canvas">

  <!-- 다크 오버레이 -->
  <div class="dark-overlay"></div>

  <!-- 왼쪽 강조 바 -->
  <div class="left-accent-bar"></div>

  <!-- 상단 레이블 -->
  <div class="top-label">MAD STARS INSPIRED · META AD</div>
  <div class="label-rule"></div>

  <!-- 우상단 T 마크 -->
  <div class="top-right-mark">T</div>

  <!-- 수직 레이블 -->
  <div class="vertical-label">AI · SALES · 2025</div>

  <!-- 메인 헤드라인 -->
  <div class="headline-block">
    <div class="headline">AI가<br>일하게 하세요</div>
  </div>

  <!-- 서브 헤드라인 -->
  <div class="sub-block">
    <div class="sub-line-1">보험영업, 기술이</div>
    <div class="sub-line-2">판을 바꿉니다</div>
  </div>

  <!-- 구분 점 -->
  <div class="dot-row">
    <div class="dot"></div>
    <div class="dot"></div>
    <div class="dot"></div>
    <div class="dot-line"></div>
  </div>

  <!-- 본문 텍스트 -->
  <div class="body-text">T.O.P 사업단 &nbsp;|&nbsp; AI 기반 영업 자동화 시스템</div>

  <!-- CTA 버튼 -->
  <div class="cta-wrapper">
    <div class="cta-btn">팀에 합류하기 <span class="cta-arrow">→</span></div>
  </div>

  <!-- 하단 그라디언트 -->
  <div class="bottom-brand"></div>

  <!-- 브랜드 로우 -->
  <div class="brand-row">
    <div class="brand-name">T.O.P<span>사업단</span></div>
    <div class="brand-tagline">Powered by AI · 새로운 영업의 시작</div>
  </div>

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


def generate_background() -> bool:
    """Gemini SA 토큰으로 배경 이미지를 생성합니다."""
    try:
        sa_token = gcloud_auth.get_service_account_token(
            "https://www.googleapis.com/auth/generative-language"
        )
    except RuntimeError as e:
        print(f"  [오류] SA 토큰 획득 실패: {e}")
        return False

    headers = {
        "Authorization": f"Bearer {sa_token}",
        "Content-Type": "application/json",
    }

    models_to_try = [
        "gemini-2.5-flash-image",
        "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)[:400]}")
        else:
            print(f"  [HTTP {resp.status_code}] {resp.text[:300]}")

    return False


def render_html(bg_path: str) -> None:
    """Playwright로 HTML을 1080x1080 PNG로 캡처합니다."""
    html = (
        HTML_TEMPLATE
        .replace("__BG_PATH__", bg_path)
        .replace("__FONT_DIR__", str(FONT_DIR))
    )
    html_file = OUTPUT_DIR / "_concept48_overlay.html"
    html_file.write_text(html, encoding="utf-8")
    print(f"  HTML 저장: {html_file}")

    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            page.goto(f"file://{html_file.resolve()}", wait_until="networkidle")
            # 폰트 및 배경 렌더링 완료 대기
            page.wait_for_timeout(2500)
            page.screenshot(path=str(SAMPLE_PATH), type="png")
        finally:
            browser.close()

    size_kb = SAMPLE_PATH.stat().st_size / 1024
    print(f"  PNG 캡처 완료: {SAMPLE_PATH} ({size_kb:.0f} KB)")


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

    print("=" * 60)
    print("컨셉 #48 MAD Stars Digital Interactive")
    print("T.O.P Recruiting Meta Ad — AI Era")
    print("Inspired by Dentsu 'My Japan Railway', McDonald's 'Fries Beat'")
    print("=" * 60)

    print("\n[1/3] 배경 이미지 생성 (Gemini AI)...")
    ok = generate_background()
    if not ok:
        print("  [경고] 배경 생성 실패. CSS 그라디언트 순수 배경으로 계속합니다.")
        bg_url = ""
    else:
        bg_url = f"file://{BG_PATH.resolve()}"

    print("\n[2/3] HTML 오버레이 렌더링 (Playwright)...")
    render_html(bg_url)

    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()
