#!/usr/bin/env python3
"""M3-1 서울대보험쌤 × 정당한 대우 Google 광고 배너 생성
- m3-1-1200x628.png (가로형)
- m3-1-1080x1080.png (정사각형)
"""

from __future__ import annotations

import base64
import json
import sys
import time
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright

# ── 경로 설정 ────────────────────────────────────────────────────────────────
BASE_DIR = Path(__file__).parent
OUTPUT_DIR = Path("/home/jay/workspace/output/google-ads/banners/m3")
TMP_DIR = BASE_DIR / "output" / "v4-hybrid"
BG_PATH = TMP_DIR / "bg_m3_1.jpg"

# Gemini API 설정
GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
MODEL_ID = "gemini-3-pro-image-preview"
FALLBACK_MODEL_ID = "gemini-3.1-flash-image-preview"

# ── 배경 프롬프트 (디자인 디렉션 원문) ────────────────────────────────────────
BG_PROMPT = (
    "Photographic scene of an elegant, warm private study in the evening. "
    "Medium shot, slightly low angle looking across the room. A large "
    "walnut-toned bookshelf fills most of the back wall — books neatly "
    "organized, warm ambient lighting from integrated shelf lighting. "
    "A solid walnut desk in the foreground, left side: a MacBook Pro closed, "
    "a handwritten notebook open with a pen resting on it, and a small "
    "glass of water. A warm reading lamp on the right edge of the desk "
    "casting directional amber light. Through a window on the left wall, "
    "a soft Seoul cityscape at dusk — lights beginning to appear, sky "
    "in deep blue-orange gradient. The room feels lived-in but immaculate — "
    "a space of concentrated expertise and quiet ambition. Camera: 50mm "
    "equivalent, natural indoor lighting with warm color temperature. "
    "No text. No logos. No people. No icons. No graphics."
)


# ── Gemini 배경 생성 ──────────────────────────────────────────────────────────

def get_auth_token() -> str:
    """gcloud_auth 모듈로 Bearer 토큰을 획득합니다."""
    sys.path.insert(0, str(BASE_DIR))
    import gcloud_auth
    return gcloud_auth.get_access_token()


def _call_model(token: str, api_key: str | None, model: str, payload: dict) -> requests.Response:
    """SA 토큰 우선, 실패 시 API 키로 Gemini 호출."""
    url_bearer = f"{GEMINI_API_BASE}/models/{model}:generateContent"
    headers_bearer = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    resp = requests.post(url_bearer, headers=headers_bearer, json=payload, timeout=300)
    if resp.status_code == 200:
        return resp
    # API 키 폴백
    if api_key:
        url_key = f"{GEMINI_API_BASE}/models/{model}:generateContent?key={api_key}"
        headers_key = {"Content-Type": "application/json"}
        return requests.post(url_key, headers=headers_key, json=payload, timeout=300)
    return resp


def generate_background() -> Path:
    """Gemini API로 배경 이미지를 생성하고 경로를 반환합니다."""
    # 이미 생성된 배경이 있으면 재사용
    if BG_PATH.exists() and BG_PATH.stat().st_size > 50_000:
        print(f"[배경] 기존 배경 이미지 재사용: {BG_PATH}")
        return BG_PATH

    print("[배경] Gemini API로 배경 이미지 생성 중...")
    token = get_auth_token()
    sys.path.insert(0, str(BASE_DIR))
    import gcloud_auth as ga
    api_key = ga.get_api_key("GEMINI_API_KEY")

    payload = {
        "contents": [{"parts": [{"text": BG_PROMPT}]}],
        "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
    }

    models_to_try = [MODEL_ID, FALLBACK_MODEL_ID]
    last_error = None

    for attempt, model in enumerate(models_to_try, 1):
        print(f"  시도 {attempt}: 모델={model}")
        try:
            resp = _call_model(token, api_key, model, payload)
        except Exception as e:
            last_error = str(e)
            print(f"  요청 실패: {e}")
            continue

        if resp.status_code in (400, 403, 404):
            print(f"  모델 접근 실패 ({resp.status_code}: {resp.text[:200]})")
            last_error = f"HTTP {resp.status_code}"
            continue

        if resp.status_code != 200:
            print(f"  HTTP {resp.status_code}: {resp.text[:300]}")
            last_error = f"HTTP {resp.status_code}"
            continue

        data = resp.json()
        candidates = data.get("candidates", [])
        if not candidates:
            print(f"  응답에 candidates 없음: {json.dumps(data)[:200]}")
            last_error = "No candidates"
            continue

        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:
            print(f"  이미지 없음. parts: {[list(p.keys()) for p in parts]}")
            last_error = "No inlineData"
            continue

        mime = image_part["inlineData"].get("mimeType", "image/jpeg")
        img_bytes = base64.b64decode(image_part["inlineData"]["data"])
        BG_PATH.write_bytes(img_bytes)
        print(f"  [배경] 저장 완료: {BG_PATH} ({len(img_bytes):,} bytes, mime={mime})")
        return BG_PATH

    raise RuntimeError(f"배경 이미지 생성 실패: {last_error}")


# ── HTML 템플릿 ───────────────────────────────────────────────────────────────

def make_html_1200x628(bg_path: Path) -> str:
    """1200×628 가로형 배너 HTML 생성."""
    bg_uri = f"file://{bg_path.resolve()}"
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Medium.otf') format('opentype');
    font-weight: 500;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-SemiBold.otf') format('opentype');
    font-weight: 600;
  }}
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}

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

  .container {{
    position: relative;
    width: 1200px;
    height: 628px;
    overflow: hidden;
  }}

  /* 배경 이미지: 우측 40% 영역에서 전체로 확장 */
  .bg-image {{
    position: absolute;
    right: 0;
    top: 0;
    width: 65%;
    height: 100%;
    background-image: url('{bg_uri}');
    background-size: cover;
    background-position: center right;
  }}

  /* 좌→우 딥 브라운 그라데이션 오버레이 */
  .gradient-overlay {{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to right,
      rgba(62,39,35,0.78) 0%,
      rgba(62,39,35,0.78) 40%,
      rgba(62,39,35,0.70) 52%,
      rgba(62,39,35,0.40) 68%,
      rgba(62,39,35,0.10) 82%,
      transparent 100%
    );
  }}

  /* 골드 세로 액센트바 */
  .accent-bar {{
    position: absolute;
    top: 80px;
    left: 0;
    width: 4px;
    height: 460px;
    background: linear-gradient(to bottom, #C9A84C, #D4B87A);
    border-radius: 2px;
  }}

  /* 좌측 텍스트 영역: 60% */
  .text-area {{
    position: absolute;
    left: 0;
    top: 0;
    width: 62%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 48px 56px 48px 60px;
    gap: 0;
  }}

  /* 브랜드 뱃지: 높이 48px, 폰트 40px Bold #1A0E00, 배경 #C9A84C */
  .brand-badge {{
    display: inline-flex;
    align-items: center;
    background: #C9A84C;
    color: #1A0E00;
    font-size: 40px;
    font-weight: 700;
    height: 48px;
    padding: 0 20px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    margin-bottom: 26px;
    width: fit-content;
    white-space: nowrap;
  }}

  /* 헤드라인: 58px Bold #FFF8E7, line-height 1.2 */
  .headline {{
    font-size: 58px;
    font-weight: 700;
    color: #FFF8E7;
    line-height: 1.2;
    letter-spacing: -1.2px;
    margin-bottom: 20px;
  }}

  /* 서브카피: 44px Medium #C9A84C */
  .sub-copy {{
    font-size: 44px;
    font-weight: 500;
    color: #C9A84C;
    letter-spacing: -0.5px;
    margin-bottom: 12px;
    text-shadow: 0 2px 8px rgba(0,0,0,0.7);
  }}

  /* 서브카피2: 40px Medium #FFF8E7 */
  .sub-copy-2 {{
    font-size: 40px;
    font-weight: 500;
    color: #FFF8E7;
    letter-spacing: -0.5px;
    margin-bottom: 36px;
    text-shadow: 0 1px 4px rgba(0,0,0,0.5);
  }}

  /* CTA 버튼: 높이 56px, 너비 220px, 골드 그라데이션, #1A0E00 44px Bold, round 6px */
  .cta-btn {{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #C9A84C 0%, #D4B87A 100%);
    color: #1A0E00;
    font-size: 44px;
    font-weight: 700;
    height: 56px;
    min-width: 220px;
    padding: 0 28px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    width: fit-content;
    box-shadow: 0 4px 16px rgba(201,168,76,0.35);
    white-space: nowrap;
  }}
</style>
</head>
<body>
<div class="container">
  <!-- 배경 이미지 -->
  <div class="bg-image"></div>
  <!-- 그라데이션 오버레이 -->
  <div class="gradient-overlay"></div>
  <!-- 골드 세로 액센트바 -->
  <div class="accent-bar"></div>
  <!-- 텍스트 영역 -->
  <div class="text-area">
    <div class="brand-badge">서울대보험쌤 · TOP사업단</div>
    <div class="headline"><span style="color:#C9A84C">지점장</span>이 직접<br>컨설팅하는 보험영업</div>
    <div class="sub-copy">AI 시스템으로 실적을 극대화</div>
    <div class="sub-copy-2">DB영업 | 멘토링 | 정착금 1,000만원</div>
    <div class="cta-btn">무료 상담 신청 →</div>
  </div>
</div>
</body>
</html>"""


def make_html_1080x1080(bg_path: Path) -> str:
    """1080×1080 정사각형 배너 HTML 생성."""
    bg_uri = f"file://{bg_path.resolve()}"
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Medium.otf') format('opentype');
    font-weight: 500;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-SemiBold.otf') format('opentype');
    font-weight: 600;
  }}
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}

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

  .container {{
    position: relative;
    width: 1080px;
    height: 1080px;
    overflow: hidden;
  }}

  /* 전체 배경 이미지 */
  .bg-image {{
    position: absolute;
    inset: 0;
    background-image: url('{bg_uri}');
    background-size: cover;
    background-position: center;
  }}

  /* 딥 브라운 반투명 오버레이 opacity 0.58 */
  .dark-overlay {{
    position: absolute;
    inset: 0;
    background: rgba(62, 39, 35, 0.58);
  }}

  /* 전체 콘텐츠 레이아웃: 패딩 좌우 72px, 상하 80px */
  .content {{
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 72px;
  }}

  /* 크림 반투명 텍스트 패널 */
  .text-panel {{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 860px;
    padding: 56px 48px;
    background: rgba(255, 248, 231, 0.82);
    border-radius: 12px;
    backdrop-filter: blur(4px);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 28px;
    text-align: center;
  }}

  /* 브랜드 뱃지: 높이 52px, 폰트 40px Bold #1A0E00, 배경 #C9A84C */
  .brand-badge {{
    display: inline-flex;
    align-items: center;
    background: #C9A84C;
    color: #1A0E00;
    font-size: 40px;
    font-weight: 700;
    height: 52px;
    padding: 0 24px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    white-space: nowrap;
    margin-bottom: 0;
  }}

  /* 중앙 영역 */
  .middle-area {{
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    width: 100%;
  }}

  /* 헤드라인: 60px Bold #3E2723, 중앙정렬 (크림 패널 위) */
  .headline {{
    font-size: 60px;
    font-weight: 700;
    color: #3E2723;
    line-height: 1.25;
    letter-spacing: -1.5px;
    text-align: center;
  }}

  /* 서브카피 1줄: 44px Medium #A07828 */
  .sub-copy-1 {{
    font-size: 44px;
    font-weight: 500;
    color: #A07828;
    letter-spacing: -0.5px;
    text-align: center;
  }}

  /* CTA 버튼: 높이 68px, 너비 360px, 골드 그라데이션, #1A0E00 48px Bold */
  .cta-btn {{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #C9A84C 0%, #D4B87A 100%);
    color: #1A0E00;
    font-size: 48px;
    font-weight: 700;
    height: 68px;
    min-width: 360px;
    padding: 0 40px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    box-shadow: 0 6px 24px rgba(201,168,76,0.45);
    white-space: nowrap;
  }}
</style>
</head>
<body>
<div class="container">
  <!-- 전체 배경 이미지 -->
  <div class="bg-image"></div>
  <!-- 딥 브라운 오버레이 -->
  <div class="dark-overlay"></div>

  <div class="content">
    <!-- 크림 텍스트 패널 -->
    <div class="text-panel">
      <!-- 뱃지 -->
      <div class="brand-badge">서울대보험쌤 · TOP사업단</div>
      <!-- 헤드라인 + 서브카피 -->
      <div class="headline"><span style="color:#C9A84C">지점장</span>이 직접<br>컨설팅하는 보험영업</div>
      <div class="sub-copy-1">AI 시스템으로 실적을 극대화</div>
      <!-- CTA -->
      <div class="cta-btn">무료 상담 신청 →</div>
    </div>
  </div>
</div>
</body>
</html>"""


# ── Playwright 캡처 ───────────────────────────────────────────────────────────

def capture_html_to_png(html_content: str, width: int, height: int, output_path: Path) -> None:
    """HTML을 Playwright로 캡처하여 PNG로 저장합니다."""
    tmp_html = TMP_DIR / f"_tmp_m3_1_{width}x{height}.html"
    tmp_html.write_text(html_content, encoding="utf-8")

    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            page = browser.new_page(viewport={"width": width, "height": height})
            page.goto(f"file://{tmp_html.resolve()}", wait_until="networkidle")
            page.wait_for_timeout(2000)  # 폰트 로딩 대기
            output_path.parent.mkdir(parents=True, exist_ok=True)
            page.screenshot(path=str(output_path), type="png", clip={
                "x": 0, "y": 0, "width": width, "height": height
            })
            print(f"  [캡처] {output_path} ({output_path.stat().st_size / 1024:.0f} KB)")
        finally:
            browser.close()

    tmp_html.unlink(missing_ok=True)


# ── 메인 ─────────────────────────────────────────────────────────────────────

def main():
    print("=" * 60)
    print("M3-1 서울대보험쌤 × 정당한 대우 배너 생성 시작")
    print("=" * 60)

    TMP_DIR.mkdir(parents=True, exist_ok=True)
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    # 1. 배경 이미지 생성
    try:
        bg_path = generate_background()
    except Exception as e:
        print(f"[오류] 배경 생성 실패: {e}")
        print("[폴백] 다크 그라데이션 배경으로 대체합니다.")
        bg_path = None

    # 2. 1200x628 배너 생성
    out_1200 = OUTPUT_DIR / "m3-1-1200x628.png"
    print("\n[1] 1200×628 가로형 배너 생성 중...")
    try:
        if bg_path:
            html_1200 = make_html_1200x628(bg_path)
        else:
            # 폴백: 배경 없이 다크 그라데이션
            dummy = Path("/nonexistent_bg")
            html_1200 = make_html_1200x628(dummy).replace(
                f"url('file:///nonexistent_bg')",
                "none",
            ).replace(
                ".bg-image {",
                ".bg-image { background: linear-gradient(135deg, #3E2723 0%, #5D3A28 50%, #3E2723 100%);",
            )
        capture_html_to_png(html_1200, 1200, 628, out_1200)
        print(f"  완료: {out_1200}")
    except Exception as e:
        print(f"  [오류] {e}")
        raise

    # 3. 1080x1080 배너 생성
    out_1080 = OUTPUT_DIR / "m3-1-1080x1080.png"
    print("\n[2] 1080×1080 정사각형 배너 생성 중...")
    try:
        if bg_path:
            html_1080 = make_html_1080x1080(bg_path)
        else:
            dummy = Path("/nonexistent_bg")
            html_1080 = make_html_1080x1080(dummy).replace(
                f"url('file:///nonexistent_bg')",
                "none",
            ).replace(
                ".bg-image {",
                ".bg-image { background: linear-gradient(160deg, #2C1810 0%, #4A2C1C 40%, #3E2723 100%);",
            )
        capture_html_to_png(html_1080, 1080, 1080, out_1080)
        print(f"  완료: {out_1080}")
    except Exception as e:
        print(f"  [오류] {e}")
        raise

    print("\n" + "=" * 60)
    print("생성 완료!")
    print(f"  1200×628 : {out_1200}  ({out_1200.stat().st_size / 1024:.0f} KB)")
    print(f"  1080×1080: {out_1080}  ({out_1080.stat().st_size / 1024:.0f} KB)")
    print("=" * 60)


if __name__ == "__main__":
    main()
