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

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")
TMP_DIR = BASE_DIR / "output" / "v4-hybrid"
BG_PATH = TMP_DIR / "bg_snu_fair.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 = (
    "A premium private study or home office at evening. Warm indirect lighting, "
    "wooden bookshelf with neatly arranged books, a clean desk with a laptop and "
    "a notepad. Through the window, a softly glowing city night view can be seen. "
    "The atmosphere feels like a professional's personal workspace — warm yet "
    "professional, sophisticated. Dark-to-mid tones with warm gold accent lighting. "
    "No people. No text. No logos. Photorealistic quality, cinematic lighting, "
    "8K resolution. Landscape orientation suitable for a wide banner."
)


# ── 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 호출."""
    # SA 토큰 우선
    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:
    """1200x628 가로형 배너 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;
  }}

  /* 배경 이미지: 우측 60% 영역 */
  .bg-image {{
    position: absolute;
    right: 0;
    top: 0;
    width: 60%;
    height: 100%;
    background-image: url('{bg_uri}');
    background-size: cover;
    background-position: center;
  }}

  /* 좌→우 그라데이션 오버레이 (다크 브라운→투명) */
  .gradient-overlay {{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to right,
      #3E2723 0%,
      #3E2723 38%,
      rgba(62,39,35,0.92) 50%,
      rgba(62,39,35,0.5) 65%,
      rgba(62,39,35,0.1) 80%,
      transparent 100%
    );
  }}

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

  /* 브랜드 뱃지 */
  .brand-badge {{
    display: inline-flex;
    align-items: center;
    background: #C9A84C;
    color: #1A0E00;
    font-size: 40px;
    font-weight: 700;
    padding: 8px 22px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    margin-bottom: 28px;
    width: fit-content;
  }}

  /* 헤드라인 */
  .headline {{
    font-size: 50px;
    font-weight: 700;
    color: #FFF8E7;
    line-height: 1.25;
    letter-spacing: -1px;
    margin-bottom: 20px;
    white-space: pre-line;
  }}

  /* 서브 카피 */
  .sub-copy {{
    font-size: 40px;
    font-weight: 500;
    color: #C9A84C;
    letter-spacing: -0.5px;
    margin-bottom: 38px;
  }}

  /* CTA 버튼 */
  .cta-btn {{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #C9A84C 0%, #D4B87A 100%);
    color: #1A0E00;
    font-size: 40px;
    font-weight: 700;
    padding: 16px 44px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    width: fit-content;
    box-shadow: 0 4px 16px rgba(201,168,76,0.35);
  }}
</style>
</head>
<body>
<div class="container">
  <!-- 배경 이미지 -->
  <div class="bg-image"></div>
  <!-- 그라데이션 오버레이 -->
  <div class="gradient-overlay"></div>
  <!-- 텍스트 영역 -->
  <div class="text-area">
    <div class="brand-badge">서울대보험쌤</div>
    <div class="headline">지점장이 직접 컨설팅하는&#10;보험영업</div>
    <div class="sub-copy">AI 시스템으로 실적을 극대화</div>
    <div class="cta-btn">무료 상담 신청</div>
  </div>
</div>
</body>
</html>"""


def make_html_1080x1080(bg_path: Path) -> str:
    """1080x1080 정사각형 배너 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.5) */
  .dark-overlay {{
    position: absolute;
    inset: 0;
    background: rgba(62, 39, 35, 0.55);
  }}

  /* 하단 그라데이션 (텍스트 가독성 강화) */
  .bottom-gradient {{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 65%;
    background: linear-gradient(
      to bottom,
      transparent 0%,
      rgba(30, 15, 5, 0.6) 40%,
      rgba(30, 15, 5, 0.82) 100%
    );
  }}

  /* 전체 텍스트 레이아웃 */
  .content {{
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    padding: 54px 60px 60px;
  }}

  /* 상단 뱃지 영역 (상단 12%) */
  .top-area {{
    height: 12%;
    display: flex;
    align-items: flex-start;
  }}

  .brand-badge {{
    display: inline-flex;
    align-items: center;
    background: #C9A84C;
    color: #1A0E00;
    font-size: 42px;
    font-weight: 700;
    padding: 8px 24px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    width: fit-content;
  }}

  /* 중앙 헤드라인 영역 (중앙 40%) */
  .middle-area {{
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    gap: 28px;
    padding: 0 20px;
  }}

  .headline {{
    font-size: 62px;
    font-weight: 700;
    color: #FFF8E7;
    line-height: 1.28;
    letter-spacing: -1.5px;
    text-align: center;
    white-space: pre-line;
    text-shadow: 0 2px 12px rgba(0,0,0,0.5);
  }}

  .sub-copy {{
    font-size: 42px;
    font-weight: 500;
    color: #C9A84C;
    letter-spacing: -0.5px;
    text-align: center;
    text-shadow: 0 2px 8px rgba(0,0,0,0.4);
  }}

  /* 하단 CTA 영역 (하단 25%) */
  .bottom-area {{
    height: 25%;
    display: flex;
    align-items: center;
    justify-content: center;
  }}

  .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;
    padding: 22px 80px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    box-shadow: 0 6px 24px rgba(201,168,76,0.45);
    min-width: 380px;
  }}
</style>
</head>
<body>
<div class="container">
  <div class="bg-image"></div>
  <div class="dark-overlay"></div>
  <div class="bottom-gradient"></div>

  <div class="content">
    <div class="top-area">
      <div class="brand-badge">서울대보험쌤</div>
    </div>

    <div class="middle-area">
      <div class="headline">지점장이 직접 컨설팅하는&#10;보험영업</div>
      <div class="sub-copy">AI 시스템으로 실적을 극대화</div>
    </div>

    <div class="bottom-area">
      <div class="cta-btn">무료 상담 신청</div>
    </div>
  </div>
</div>
</body>
</html>"""


# ── 폴백 HTML (배경 이미지 없을 때: 다크 그라데이션 배경) ──────────────────────────

def make_html_no_bg_1200x628() -> str:
    """배경 이미지 없는 1200x628 폴백 배너."""
    return make_html_1200x628(Path("/nonexistent")).replace(
        "background-image: url('file:///nonexistent');",
        "/* no bg */",
    ).replace(
        "background: linear-gradient(\n      to right,\n      #3E2723 0%,\n      #3E2723 38%,\n      rgba(62,39,35,0.92) 50%,\n      rgba(62,39,35,0.5) 65%,\n      rgba(62,39,35,0.1) 80%,\n      transparent 100%\n    );",
        "background: linear-gradient(135deg, #3E2723 0%, #5D3A28 50%, #3E2723 100%);",
    )


def make_html_no_bg_1080x1080() -> str:
    """배경 이미지 없는 1080x1080 폴백 배너."""
    return make_html_1080x1080(Path("/nonexistent")).replace(
        "background-image: url('file:///nonexistent');",
        "background: linear-gradient(160deg, #2C1810 0%, #4A2C1C 40%, #3E2723 100%);",
    )


# ── 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_banner_{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 / "snu-fair-1200x628.png"
    print("\n[1] 1200x628 가로형 배너 생성 중...")
    try:
        html_1200 = make_html_1200x628(bg_path) if bg_path else make_html_no_bg_1200x628()
        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 / "snu-fair-1080x1080.png"
    print("\n[2] 1080x1080 정사각형 배너 생성 중...")
    try:
        html_1080 = make_html_1080x1080(bg_path) if bg_path else make_html_no_bg_1080x1080()
        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"  1200x628: {out_1200}")
    print(f"  1080x1080: {out_1080}")
    print("=" * 60)


if __name__ == "__main__":
    main()
