#!/usr/bin/env python3
"""GA 배너 M2-1 '정당한 대우' 세트 생성 — 하이브리드 방식 (Gemini 배경 + Playwright 오버레이).

산출물:
  /home/jay/workspace/output/google-ads/banners/ga-fair-1200x628.png
  /home/jay/workspace/output/google-ads/banners/ga-fair-1080x1080.png
"""

from __future__ import annotations

import base64
import sys
import time
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright

# ──────────────────────────────────────────────────────────
# 경로 설정
# ──────────────────────────────────────────────────────────
TOOL_DIR = Path(__file__).parent
sys.path.insert(0, str(TOOL_DIR))

import gcloud_auth  # noqa: E402

OUTPUT_DIR = Path("/home/jay/workspace/output/google-ads/banners")
BG_IMAGE_PATH = OUTPUT_DIR / "ga-fair-bg.jpg"

OUTPUT_1200x628 = OUTPUT_DIR / "ga-fair-1200x628.png"
OUTPUT_1080x1080 = OUTPUT_DIR / "ga-fair-1080x1080.png"

FONT_DIR = Path.home() / ".local/share/fonts/Pretendard"

# ──────────────────────────────────────────────────────────
# Gemini 배경 생성
# ──────────────────────────────────────────────────────────
GEMINI_BG_PROMPT = (
    "A top-view photo scene of a clean office desk with two documents placed side by side. "
    "One document has red marks/annotations, the other has green checkmarks. "
    "A single pen and a coffee cup are on the desk. "
    "Minimalist and analytical atmosphere. Bright, even studio lighting. "
    "High-quality photorealistic style. Neutral and professional tone. "
    "No text, no people, no logos. Clean workspace scene."
)

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
GEMINI_SCOPE = "https://www.googleapis.com/auth/generative-language"
MODEL_PRIMARY = "gemini-3.1-flash-image-preview"
MODEL_FALLBACK = "gemini-3-pro-image-preview"


def generate_background() -> Path:
    """Gemini API로 배경 이미지를 생성하고 저장합니다."""
    print("[배경 생성] Gemini API 호출 중...")

    # API 키 우선 시도
    api_key = gcloud_auth.get_api_key("GEMINI_API_KEY")

    if api_key:
        print(f"  인증: API 키 사용")
        models_to_try = [
            "gemini-3.1-flash-image-preview",
            "gemini-3-pro-image-preview",
            "gemini-2.5-flash-image",
        ]
        for model in models_to_try:
            print(f"  모델 시도: {model}")
            try:
                url = f"{GEMINI_API_BASE}/models/{model}:generateContent?key={api_key}"
                payload = {
                    "contents": [{"parts": [{"text": GEMINI_BG_PROMPT}]}],
                    "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
                }
                resp = requests.post(url, json=payload, timeout=120)
                if resp.status_code == 200:
                    data = resp.json()
                    candidates = data.get("candidates", [])
                    if candidates:
                        parts = candidates[0].get("content", {}).get("parts", [])
                        for part in parts:
                            if "inlineData" in part:
                                img_b64 = part["inlineData"]["data"]
                                img_bytes = base64.b64decode(img_b64)
                                BG_IMAGE_PATH.write_bytes(img_bytes)
                                print(f"  배경 생성 완료: {BG_IMAGE_PATH} ({len(img_bytes):,} bytes)")
                                return BG_IMAGE_PATH
                print(f"  {model} 응답 {resp.status_code}: {resp.text[:200]}")
            except Exception as e:
                print(f"  {model} 오류: {e}")

    # SA 토큰 시도
    print("  API 키 실패, SA 토큰 시도...")
    try:
        token = gcloud_auth.get_service_account_token(GEMINI_SCOPE)
        for model in [MODEL_PRIMARY, MODEL_FALLBACK]:
            try:
                url = f"{GEMINI_API_BASE}/models/{model}:generateContent"
                headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
                payload = {
                    "contents": [{"parts": [{"text": GEMINI_BG_PROMPT}]}],
                    "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
                }
                resp = requests.post(url, headers=headers, json=payload, timeout=120)
                if resp.status_code == 200:
                    data = resp.json()
                    candidates = data.get("candidates", [])
                    if candidates:
                        parts = candidates[0].get("content", {}).get("parts", [])
                        for part in parts:
                            if "inlineData" in part:
                                img_b64 = part["inlineData"]["data"]
                                img_bytes = base64.b64decode(img_b64)
                                BG_IMAGE_PATH.write_bytes(img_bytes)
                                print(f"  배경 생성 완료 (SA): {BG_IMAGE_PATH}")
                                return BG_IMAGE_PATH
                print(f"  SA/{model} 응답 {resp.status_code}: {resp.text[:200]}")
            except Exception as e:
                print(f"  SA/{model} 오류: {e}")
    except Exception as e:
        print(f"  SA 토큰 오류: {e}")

    raise RuntimeError("모든 Gemini API 인증 방법 실패 — 배경 이미지를 생성할 수 없습니다.")


# ──────────────────────────────────────────────────────────
# HTML 템플릿 — 1200x628 (가로형)
# ──────────────────────────────────────────────────────────
def build_html_1200x628(bg_image_path: str) -> str:
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @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: 1200px;
    height: 628px;
    overflow: hidden;
    background: #1A2526;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}

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

  /* 우측 40% - Gemini 배경 이미지 */
  .bg-right {{
    position: absolute;
    top: 0;
    right: 0;
    width: 480px;
    height: 628px;
    background-image: url('file://{bg_image_path}');
    background-size: cover;
    background-position: center center;
  }}

  /* 좌측→우측 그라데이션 오버레이 (배경 위에 덮음) */
  .gradient-overlay {{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to right,
      #1A2526 0%,
      #1A2526 58%,
      rgba(26, 37, 38, 0.85) 70%,
      rgba(26, 37, 38, 0.3) 82%,
      rgba(26, 37, 38, 0.0) 100%
    );
  }}

  /* 좌측 텍스트 영역 — 좌측 60% 내 수직 중앙 */
  .text-area {{
    position: absolute;
    top: 0;
    left: 0;
    width: 720px;
    height: 628px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    padding: 0 72px;
  }}

  .tag-line {{
    font-size: 28px;
    font-weight: 500;
    color: #00897B;
    letter-spacing: 0.5px;
    margin-bottom: 20px;
    text-transform: uppercase;
  }}

  .headline {{
    font-size: 52px;
    font-weight: 700;
    color: #FFFFFF;
    line-height: 1.25;
    letter-spacing: -1px;
    margin-bottom: 24px;
  }}

  .headline .accent {{
    color: #A5D6A7;
  }}

  .sub {{
    font-size: 30px;
    font-weight: 500;
    color: #B0BEC5;
    line-height: 1.5;
    margin-bottom: 44px;
    letter-spacing: -0.3px;
  }}

  .cta-btn {{
    display: inline-block;
    font-size: 28px;
    font-weight: 700;
    color: #FFFFFF;
    background: #00897B;
    padding: 18px 44px;
    border-radius: 4px;
    letter-spacing: 0px;
    white-space: nowrap;
  }}

  /* 우측 상단 소형 배지 */
  .compare-badge {{
    position: absolute;
    top: 48px;
    right: 500px;
    background: rgba(46, 125, 50, 0.85);
    border: 1.5px solid #4CAF50;
    border-radius: 4px;
    padding: 10px 20px;
    font-size: 24px;
    font-weight: 600;
    color: #FFFFFF;
  }}

  /* 하단 데코 라인 */
  .deco-line {{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(to right, #2E7D32, #00897B, #00BCD4);
  }}
</style>
</head>
<body>
<div class="canvas">

  <!-- 우측 배경 -->
  <div class="bg-right"></div>

  <!-- 그라데이션 오버레이 -->
  <div class="gradient-overlay"></div>

  <!-- 텍스트 영역 -->
  <div class="text-area">
    <div class="tag-line">수수료 비교 분석</div>
    <div class="headline">GA 수수료 구조,<br><span class="accent">제대로 비교하세요</span></div>
    <div class="sub">같은 일인데 수수료가 다르다면?</div>
    <span class="cta-btn">GA 비교하기 →</span>
  </div>

  <!-- 비교 배지 -->
  <div class="compare-badge">객관적 데이터 비교</div>

  <!-- 하단 데코 -->
  <div class="deco-line"></div>

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


# ──────────────────────────────────────────────────────────
# HTML 템플릿 — 1080x1080 (정사각형)
# ──────────────────────────────────────────────────────────
def build_html_1080x1080(bg_image_path: str) -> str:
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @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;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}

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

  /* 전체 배경 이미지 */
  .bg-full {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1080px;
    height: 1080px;
    background-image: url('file://{bg_image_path}');
    background-size: cover;
    background-position: center center;
  }}

  /* 다크 그레이 반투명 오버레이 (opacity 0.55) */
  .dark-overlay {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1080px;
    height: 1080px;
    background: rgba(21, 27, 30, 0.62);
  }}

  /* 중앙 그라데이션 강화 (텍스트 가독성) */
  .center-gradient {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1080px;
    height: 1080px;
    background: radial-gradient(
      ellipse 900px 700px at center center,
      rgba(15, 20, 22, 0.55) 0%,
      rgba(15, 20, 22, 0.0) 70%
    );
  }}

  /* 상단 배지 */
  .top-badge {{
    position: absolute;
    top: 60px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(46, 125, 50, 0.9);
    border: 1.5px solid #66BB6A;
    border-radius: 4px;
    padding: 12px 36px;
    font-size: 26px;
    font-weight: 600;
    color: #FFFFFF;
    white-space: nowrap;
    letter-spacing: 0.5px;
  }}

  /* 중앙 40% 영역 헤드라인 */
  .headline-zone {{
    position: absolute;
    top: 216px;
    left: 0;
    right: 0;
    height: 432px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 0 80px;
  }}

  .headline {{
    font-size: 64px;
    font-weight: 700;
    color: #FFFFFF;
    line-height: 1.25;
    letter-spacing: -1.5px;
    margin-bottom: 32px;
    text-shadow: 0 2px 20px rgba(0,0,0,0.6);
  }}

  .headline .accent {{
    color: #A5D6A7;
  }}

  /* 중앙 하단 25% — 서브 카피 */
  .sub-zone {{
    position: absolute;
    top: 660px;
    left: 0;
    right: 0;
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 80px;
  }}

  .sub {{
    font-size: 36px;
    font-weight: 500;
    color: #B2DFDB;
    text-align: center;
    line-height: 1.5;
    letter-spacing: -0.3px;
    text-shadow: 0 1px 12px rgba(0,0,0,0.5);
  }}

  /* 하단 20% — CTA */
  .cta-zone {{
    position: absolute;
    top: 864px;
    left: 0;
    right: 0;
    height: 216px;
    display: flex;
    justify-content: center;
    align-items: center;
  }}

  .cta-btn {{
    display: inline-block;
    font-size: 36px;
    font-weight: 700;
    color: #FFFFFF;
    background: #00897B;
    padding: 22px 72px;
    border-radius: 4px;
    letter-spacing: 0px;
    white-space: nowrap;
    text-shadow: none;
  }}

  /* 하단 데코 라인 */
  .deco-line {{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 5px;
    background: linear-gradient(to right, #2E7D32, #00897B, #00BCD4);
  }}
</style>
</head>
<body>
<div class="canvas">

  <!-- 전체 배경 -->
  <div class="bg-full"></div>

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

  <!-- 센터 그라데이션 보강 -->
  <div class="center-gradient"></div>

  <!-- 상단 배지 -->
  <div class="top-badge">수수료 비교 분석</div>

  <!-- 헤드라인 영역 -->
  <div class="headline-zone">
    <div class="headline">GA 수수료 구조,<br><span class="accent">제대로 비교하세요</span></div>
  </div>

  <!-- 서브 카피 -->
  <div class="sub-zone">
    <div class="sub">같은 일인데 수수료가 다르다면?</div>
  </div>

  <!-- CTA -->
  <div class="cta-zone">
    <span class="cta-btn">GA 비교하기 →</span>
  </div>

  <!-- 하단 데코 -->
  <div class="deco-line"></div>

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


# ──────────────────────────────────────────────────────────
# Playwright 캡처
# ──────────────────────────────────────────────────────────
def capture(html_content: str, output_path: Path, width: int, height: int) -> None:
    html_file = output_path.parent / f"_tmp_{output_path.stem}.html"
    html_file.write_text(html_content, encoding="utf-8")
    print(f"  HTML 템플릿 저장: {html_file}")

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


# ──────────────────────────────────────────────────────────
# 메인
# ──────────────────────────────────────────────────────────
def main() -> None:
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    print("=" * 60)
    print("GA 배너 M2-1 '정당한 대우' 하이브리드 이미지 생성")
    print("=" * 60)

    # 1. Gemini 배경 생성
    t0 = time.time()
    bg_path = generate_background()
    print(f"  배경 생성 소요: {time.time()-t0:.1f}초\n")

    bg_str = str(bg_path.resolve())

    # 2. 1200x628 생성
    print("[1/2] 1200x628 가로형 배너 생성...")
    t1 = time.time()
    html_wide = build_html_1200x628(bg_str)
    capture(html_wide, OUTPUT_1200x628, 1200, 628)
    print(f"  소요: {time.time()-t1:.1f}초\n")

    # 3. 1080x1080 생성
    print("[2/2] 1080x1080 정사각형 배너 생성...")
    t2 = time.time()
    html_sq = build_html_1080x1080(bg_str)
    capture(html_sq, OUTPUT_1080x1080, 1080, 1080)
    print(f"  소요: {time.time()-t2:.1f}초\n")

    print("=" * 60)
    print("완료!")
    print(f"  {OUTPUT_1200x628}")
    print(f"  {OUTPUT_1080x1080}")
    print(f"  총 소요: {time.time()-t0:.1f}초")


if __name__ == "__main__":
    main()
