#!/usr/bin/env python3
"""인카다이렉트 M1-1 '정당한 대우' Google 배너 생성기
컨셉 #49 Spikes Trust Protection 스타일 — 기업 로비 배경
- 1200x628 (가로형)
- 1080x1080 (정사각형)
"""

import base64
import sys
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright

sys.path.insert(0, "/home/jay/workspace/tools/ai-image-gen")
import gcloud_auth

OUTPUT_DIR = Path("/home/jay/workspace/output/google-ads/banners")
BG_PATH = OUTPUT_DIR / "bg_incar_fair.jpg"
OUT_1200 = OUTPUT_DIR / "incar-fair-1200x628.png"
OUT_1080 = OUTPUT_DIR / "incar-fair-1080x1080.png"

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

BG_PROMPT = (
    "Modern corporate headquarters lobby interior, "
    "wide floor-to-ceiling glass windows overlooking city skyline, "
    "clean polished marble floor with subtle reflections, "
    "elegant indirect lighting from ceiling and walls, "
    "one professional Korean businessman walking confidently away from camera, "
    "business suit, confident upright posture, back view, "
    "bright morning natural light streaming through glass, "
    "warm golden hour light creating depth and atmosphere, "
    "premium corporate aesthetic, photorealistic, "
    "high-end Samsung Fire & Marine Insurance level advertisement quality, "
    "deep navy and warm gold color tones, "
    "spacious modern architecture, "
    "no text, no watermarks, no graphics, no charts, no graphs, "
    "no handshakes, no meeting rooms, no multiple people, "
    "no icons, no illustrations, photo quality"
)


def generate_background() -> bool:
    """Gemini SA 토큰으로 배경 이미지를 생성합니다."""
    print("  SA 토큰 획득 중...")
    try:
        sa_token = gcloud_auth.get_service_account_token(
            "https://www.googleapis.com/auth/generative-language"
        )
    except Exception as e:
        print(f"  [오류] SA 토큰 획득 실패: {e}")
        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()
            parts = data.get("candidates", [{}])[0].get("content", {}).get("parts", [])
            for part in 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})")
        else:
            print(f"  [HTTP {resp.status_code}] {resp.text[:300]}")
    return False


# ─── 1200x628 가로형 HTML ──────────────────────────────────────────────────
HTML_1200 = """<!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@500;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;
  }

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

  body {
    width: 1200px;
    height: 628px;
    overflow: hidden;
    background-color: #0D1E35;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }

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

  /* 우측 이미지 영역 — 오버레이 없음 (배경 주인공 보호) */
  /* 좌측 60% 네이비→투명 그라데이션 오버레이 */
  .overlay-left {
    position: absolute;
    inset: 0;
    background: linear-gradient(
      90deg,
      rgba(27, 54, 93, 0.96) 0%,
      rgba(27, 54, 93, 0.94) 30%,
      rgba(27, 54, 93, 0.85) 50%,
      rgba(27, 54, 93, 0.40) 68%,
      transparent 80%
    );
  }

  /* 상단 미세 강조 바 */
  .top-accent {
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 5px;
    background: linear-gradient(90deg, #C5A572 0%, #D4B87A 40%, transparent 70%);
  }

  /* 텍스트 영역 (좌측 60%) */
  .text-area {
    position: absolute;
    top: 0; left: 0;
    width: 720px;
    height: 628px;
    padding: 52px 60px 52px 60px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  /* 코스닥 상장사 뱃지 */
  .badge {
    display: inline-flex;
    align-items: center;
    background: #C5A572;
    border-radius: 6px;
    padding: 10px 22px;
    align-self: flex-start;
  }

  .badge-text {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 36px;
    font-weight: 700;
    color: #1B365D;
    letter-spacing: 0.04em;
  }

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

  /* 서브카피 */
  .subcopy {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 28px;
    font-weight: 500;
    color: #5B9BD5;
    letter-spacing: 0.02em;
    line-height: 1.4;
  }

  /* CTA 버튼 */
  .cta-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #C5A572 0%, #D4B87A 100%);
    border-radius: 6px;
    padding: 14px 36px;
    min-width: 220px;
    min-height: 56px;
    align-self: flex-start;
  }

  .cta-text {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 26px;
    font-weight: 700;
    color: #1A0E00;
    letter-spacing: 0.02em;
  }

  /* 하단 보조 정보 (선택) */
  .bottom-info {
    position: absolute;
    bottom: 24px;
    left: 60px;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 22px;
    font-weight: 500;
    color: rgba(255,255,255,0.45);
    letter-spacing: 0.03em;
  }
</style>
</head>
<body>
<div class="container">
  <div class="overlay-left"></div>
  <div class="top-accent"></div>

  <div class="text-area">
    <!-- 코스닥 상장사 뱃지 -->
    <div class="badge">
      <span class="badge-text">코스닥 상장사</span>
    </div>

    <!-- 메인 헤드라인 -->
    <div class="headline">
      정당한 보상을<br>받고 계신가요?
    </div>

    <!-- 서브카피 -->
    <div class="subcopy">
      투명한 수수료 구조 · 99% 정착률
    </div>

    <!-- CTA 버튼 -->
    <div class="cta-btn">
      <span class="cta-text">조건 확인하기</span>
    </div>
  </div>

  <!-- 하단 보조 -->
  <div class="bottom-info">코스닥 상장 인카금융서비스</div>
</div>
</body>
</html>
"""

# ─── 1080x1080 정사각형 HTML ──────────────────────────────────────────────
HTML_1080 = """<!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@500;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;
  }

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

  body {
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background-color: #0D1E35;
    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;
  }

  /* 반투명 네이비 오버레이 — 전체 (opacity 0.55) */
  .overlay-full {
    position: absolute;
    inset: 0;
    background: rgba(27, 54, 93, 0.56);
  }

  /* 하단 그라데이션 강화 (CTA 가독성) */
  .overlay-bottom {
    position: absolute;
    bottom: 0; left: 0; right: 0;
    height: 320px;
    background: linear-gradient(
      0deg,
      rgba(13, 30, 53, 0.95) 0%,
      rgba(13, 30, 53, 0.70) 50%,
      transparent 100%
    );
  }

  /* 상단 골드 액센트 바 */
  .top-accent {
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 6px;
    background: linear-gradient(90deg, #C5A572 0%, #D4B87A 100%);
  }

  /* 전체 레이아웃 래퍼 */
  .layout {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 56px 64px 60px 64px;
  }

  /* 코스닥 상장사 뱃지 */
  .badge {
    display: inline-flex;
    align-items: center;
    background: #C5A572;
    border-radius: 6px;
    padding: 12px 28px;
  }

  .badge-text {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 40px;
    font-weight: 700;
    color: #1B365D;
    letter-spacing: 0.04em;
  }

  /* 헤드라인 + 서브카피 블록 */
  .copy-block {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 32px;
    text-align: center;
  }

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

  /* 구분선 */
  .divider {
    width: 80px;
    height: 3px;
    background: linear-gradient(90deg, #C5A572, #D4B87A);
    border-radius: 2px;
  }

  /* 서브카피 */
  .subcopy {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 34px;
    font-weight: 500;
    color: #A8C8F0;
    letter-spacing: 0.02em;
    text-align: center;
    line-height: 1.4;
    background: rgba(13, 30, 53, 0.55);
    padding: 14px 28px;
    border-radius: 8px;
  }

  /* CTA 버튼 */
  .cta-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #C5A572 0%, #D4B87A 100%);
    border-radius: 6px;
    padding: 18px 56px;
    min-width: 300px;
    min-height: 68px;
  }

  .cta-text {
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: 34px;
    font-weight: 700;
    color: #1A0E00;
    letter-spacing: 0.02em;
  }
</style>
</head>
<body>
<div class="container">
  <div class="overlay-full"></div>
  <div class="overlay-bottom"></div>
  <div class="top-accent"></div>

  <div class="layout">
    <!-- 상단 15%: 코스닥 상장사 뱃지 -->
    <div class="badge">
      <span class="badge-text">코스닥 상장사</span>
    </div>

    <!-- 중앙: 헤드라인 + 서브카피 -->
    <div class="copy-block">
      <div class="headline">
        정당한 보상을<br>받고 계신가요?
      </div>
      <div class="divider"></div>
      <div class="subcopy">
        투명한 수수료 구조 · 99% 정착률
      </div>
    </div>

    <!-- 하단 25%: CTA 버튼 -->
    <div class="cta-btn">
      <span class="cta-text">조건 확인하기</span>
    </div>
  </div>
</div>
</body>
</html>
"""


def render_html_to_png(html_content: str, output_path: Path, width: int, height: int) -> bool:
    """Playwright로 HTML을 PNG로 캡처합니다."""
    html_file = OUTPUT_DIR / f"overlay_incar_{width}x{height}.html"
    bg_url = f"file://{BG_PATH}" if BG_PATH.exists() and BG_PATH.stat().st_size > 0 else ""
    html_content = html_content.replace("__BG_PATH__", bg_url)
    html_file.write_text(html_content, encoding="utf-8")

    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": width, "height": height})
        page.goto(f"file://{html_file}")
        page.wait_for_timeout(3500)  # 웹폰트 로딩 대기
        page.screenshot(path=str(output_path), type="png")
        browser.close()

    if output_path.exists():
        size_kb = output_path.stat().st_size / 1024
        print(f"  저장 완료: {output_path} ({size_kb:.0f} KB)")
        return True
    return False


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

    print("=" * 65)
    print("인카다이렉트 M1-1 '정당한 대우' Google 배너 생성")
    print("컨셉 #49 Spikes Trust Protection — 기업 로비 배경")
    print("=" * 65)

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

    print("\n[2/3] 1200x628 가로형 배너 렌더링...")
    ok1 = render_html_to_png(HTML_1200, OUT_1200, 1200, 628)

    print("\n[3/3] 1080x1080 정사각형 배너 렌더링...")
    ok2 = render_html_to_png(HTML_1080, OUT_1080, 1080, 1080)

    print("\n" + "=" * 65)
    print("결과 요약")
    print("=" * 65)
    print(f"  1200x628 : {'OK' if ok1 else 'FAIL'} → {OUT_1200}")
    print(f"  1080x1080: {'OK' if ok2 else 'FAIL'} → {OUT_1080}")
    return 0 if (ok1 and ok2) else 1


if __name__ == "__main__":
    sys.exit(main())
