#!/usr/bin/env python3
"""M3-3 서울대보험쌤 × 영업지원 Google 광고 배너 생성
- m3-3-1200x628.png (가로형)
- m3-3-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_3.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 a bright, cafe-like home office workspace. "
    "Medium shot, front-facing eye-level angle. A clean white desk near "
    "a large window — morning light streaming through, creating soft "
    "natural lens flare on the left side. A person visible from the left "
    "side only: arm in a casual white shirt sleeve, hand on a white MacBook "
    "keyboard. Face completely outside the frame. On the desk: an open "
    "planner/notebook with neat handwriting (not readable), a ceramic mug "
    "with coffee (steam visible), and a small potted plant. Through the window: "
    "green trees or foliage visible — urban outdoor but natural feel. The wall "
    "behind is white with one small framed print (abstract, not text-based). "
    "The overall atmosphere is bright, calm, and full of quiet optimism — "
    "the first morning of a new beginning. Warm morning color temperature. "
    "No text. No logos. 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:
    """1200x628 가로형 배너 HTML 생성.

    디자인 (업데이트: 딥 브라운 그라데이션 오버레이 → 프리미엄 다크 스타일):
    - Gemini 배경 전체
    - 딥 브라운 좌→우 그라데이션 오버레이 (m3-1 템플릿 A 적용)
    - 크림 헤드라인 #FFF8E7
    - 골드 서브카피 #C9A84C
    - CTA: 골드 그라데이션 배경, 다크 텍스트 #1A0E00
    - 골드 세로 액센트바
    """
    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;
  }}

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

  /* 딥 브라운 그라데이션 오버레이 (강화: 좌측 완전 커버) */
  .gradient-overlay {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to right,
      rgba(40,20,10,0.88) 0%,
      rgba(40,20,10,0.88) 38%,
      rgba(40,20,10,0.78) 52%,
      rgba(40,20,10,0.45) 68%,
      rgba(40,20,10,0.12) 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;
  }}

  /* 텍스트 영역: 좌측 62% */
  .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;
  }}

  /* 브랜드 뱃지 */
  .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: 28px;
    width: fit-content;
    white-space: nowrap;
  }}

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

  /* 지원 항목: 골드 #C9A84C */
  .support-items {{
    font-size: 42px;
    font-weight: 500;
    color: #C9A84C;
    letter-spacing: -0.5px;
    margin-bottom: 36px;
    white-space: nowrap;
  }}

  /* CTA 버튼: 골드 그라데이션 + 다크 텍스트 */
  .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;
    width: 260px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    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">영업 못하는 게 아닙니다&#10;— <span style="color:#C9A84C">시스템</span>이 없었을 뿐</div>
    <div class="support-items">AI자동화&nbsp;&nbsp;|&nbsp;&nbsp;DB영업&nbsp;&nbsp;|&nbsp;&nbsp;정착금 1,000만원</div>
    <div class="cta-btn">무료 상담 신청 →</div>
  </div>
</div>
</body>
</html>"""


def make_html_1080x1080(bg_path: Path) -> str:
    """1080x1080 정사각형 배너 HTML 생성.

    디자인:
    - Gemini 배경 전체
    - 크림 반투명 오버레이 opacity 0.38 (배경 아침 햇살/식물이 보이도록)
    - 중앙정렬 레이아웃
    - 딥 브라운 헤드라인 #3E2723
    - 다크 골드 서브카피 #A07828
    - CTA: 다크 골드 배경 #A07828, 크림 텍스트 #FFF8E7
    """
    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: #FFF8E7;
  }}

  .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.55 */
  .cream-overlay {{
    position: absolute;
    inset: 0;
    background: rgba(255, 248, 231, 0.55);
  }}

  /* 전체 컨텐츠 */
  .content {{
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 72px;
    gap: 32px;
    text-align: center;
  }}

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

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

  /* 헤드라인 */
  .headline {{
    font-size: 62px;
    font-weight: 700;
    color: #3E2723;
    line-height: 1.2;
    letter-spacing: -1px;
    text-align: center;
    white-space: pre-line;
    text-shadow: 0 1px 8px rgba(255, 248, 231, 0.6);
  }}

  /* 지원 항목 */
  .support-items {{
    font-size: 44px;
    font-weight: 500;
    color: #A07828;
    letter-spacing: -0.5px;
    text-align: center;
    white-space: nowrap;
    text-shadow: 0 0 8px rgba(255, 248, 231, 1), 0 0 16px rgba(255, 248, 231, 0.8);
  }}

  /* CTA 버튼: 골드 그라데이션 + 다크 텍스트 */
  .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;
    width: 420px;
    border-radius: 6px;
    letter-spacing: -0.5px;
    box-shadow: 0 6px 24px rgba(201,168,76,0.40);
    white-space: nowrap;
    margin-top: 8px;
  }}
</style>
</head>
<body>
<div class="container">
  <div class="bg-image"></div>
  <div class="cream-overlay"></div>

  <div class="text-panel">
    <div class="brand-badge">서울대보험쌤 · TOP사업단</div>
    <div class="headline">영업 못하는 게 아닙니다&#10;— <span style="color:#A07828">시스템</span>이 없었을 뿐</div>
    <div class="support-items">AI자동화&nbsp;&nbsp;|&nbsp;&nbsp;DB영업&nbsp;&nbsp;|&nbsp;&nbsp;정착금 1,000만원</div>
    <div class="cta-btn">무료 상담 신청 →</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_3_{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-3 서울대보험쌤 × 영업지원 배너 생성 시작")
    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-3-1200x628.png"
    print("\n[1] 1200x628 가로형 배너 생성 중...")
    try:
        if bg_path:
            html_1200 = make_html_1200x628(bg_path)
        else:
            # 폴백: 배경 없이 크림 단색으로
            html_1200 = make_html_1200x628(Path("/nonexistent")).replace(
                f"background-image: url('file:///nonexistent');",
                "background: linear-gradient(135deg, #FFF8E7 0%, #F5E8C4 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-3-1080x1080.png"
    print("\n[2] 1080x1080 정사각형 배너 생성 중...")
    try:
        if bg_path:
            html_1080 = make_html_1080x1080(bg_path)
        else:
            html_1080 = make_html_1080x1080(Path("/nonexistent")).replace(
                f"background-image: url('file:///nonexistent');",
                "background: linear-gradient(160deg, #FFF8E7 0%, #F0DFA8 60%, #FFF8E7 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"  1200x628: {out_1200} ({out_1200.stat().st_size / 1024:.0f} KB)")
    print(f"  1080x1080: {out_1080} ({out_1080.stat().st_size / 1024:.0f} KB)")
    print("=" * 60)


if __name__ == "__main__":
    main()
