#!/usr/bin/env python3
"""GA 배너 M2-3 영업지원 세트 생성 스크립트.

Gemini 배경 + HTML/CSS 오버레이 하이브리드 방식.
- 1200x628 (가로형)
- 1080x1080 (정사각형)
"""

from __future__ import annotations

import base64
import sys
import time
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth

# ─────────────────────────────────────────────────────────────────────────────
# 경로 설정
# ─────────────────────────────────────────────────────────────────────────────
OUTPUT_DIR = Path("/home/jay/workspace/output/google-ads/banners")
FONT_DIR = Path.home() / ".local/share/fonts/Pretendard"

BG_PATH = OUTPUT_DIR / "_ga_support_bg.jpg"
HTML_1200 = OUTPUT_DIR / "_ga_support_1200x628.html"
HTML_1080 = OUTPUT_DIR / "_ga_support_1080x1080.html"
OUT_1200 = OUTPUT_DIR / "ga-support-1200x628.png"
OUT_1080 = OUTPUT_DIR / "ga-support-1080x1080.png"

# Gemini 배경 프롬프트
GEMINI_PROMPT = (
    "A bright and warm small educational space scene. "
    "2 to 3 people sit around a round table looking at laptops and having a natural conversation. "
    "Natural light streaming through windows, indoor green plants, clean white modern interior. "
    "Collaborative and communicative comfortable work environment. "
    "Mid-range to distant shot of people, not too close. "
    "Photo realistic quality, warm tones, bright and airy atmosphere. "
    "High resolution photograph scene."
)

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
GEMINI_SCOPE = "https://www.googleapis.com/auth/generative-language"

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

def generate_background() -> Path:
    """Gemini API로 배경 이미지 생성."""
    print("[배경] Gemini API 토큰 획득 중...")
    token = gcloud_auth.get_service_account_token(GEMINI_SCOPE)
    print(f"[배경] 토큰 획득 완료 ({len(token)} chars)")

    models_to_try = [
        "gemini-2.0-flash-preview-image-generation",
        "gemini-3-pro-image-preview",
        "imagen-3.0-generate-001",
    ]

    for model_id in models_to_try:
        print(f"[배경] 모델 시도: {model_id}")
        url = f"{GEMINI_API_BASE}/models/{model_id}:generateContent"
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }
        payload = {
            "contents": [{"parts": [{"text": GEMINI_PROMPT}]}],
            "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
        }

        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=120)
            if resp.status_code in (403, 404):
                print(f"  → {resp.status_code} 접근 불가, 다음 모델 시도...")
                continue
            resp.raise_for_status()
        except requests.HTTPError as e:
            print(f"  → HTTP 오류: {e}, 다음 모델 시도...")
            continue

        data = resp.json()
        candidates = data.get("candidates", [])
        if not candidates:
            print(f"  → 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"  → 이미지 파트 없음, 다음 모델 시도...")
            continue

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

    raise RuntimeError("모든 Gemini 모델 시도 실패")


# ─────────────────────────────────────────────────────────────────────────────
# HTML 템플릿 빌더
# ─────────────────────────────────────────────────────────────────────────────

def font_faces() -> str:
    """Pretendard 폰트 @font-face 정의."""
    weights = [
        ("Bold", 700),
        ("SemiBold", 600),
        ("Medium", 500),
        ("Regular", 400),
        ("ExtraBold", 800),
        ("Black", 900),
    ]
    lines = []
    for name, w in weights:
        fpath = FONT_DIR / f"Pretendard-{name}.otf"
        lines.append(f"""  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{fpath}') format('opentype');
    font-weight: {w};
  }}""")
    return "\n".join(lines)


def build_html_1200(bg_path: str) -> str:
    """1200x628 가로형 배너 HTML."""
    ff = font_faces()
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
{ff}

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

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

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

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

  /* 우측 이미지→좌측 페이드 그라데이션 */
  .bg-panel::before {{
    content: '';
    position: absolute;
    top: 0; left: 0; bottom: 0;
    width: 160px;
    background: linear-gradient(to right, #F7F9F7 0%, rgba(247,249,247,0) 100%);
    z-index: 1;
  }}

  /* 좌측 60%: 텍스트 패널 */
  .text-panel {{
    position: absolute;
    top: 0;
    left: 0;
    width: 720px;
    height: 628px;
    background: linear-gradient(135deg, #F7F9F7 0%, #EEF5EE 100%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 72px;
    z-index: 2;
  }}

  /* 상단 태그 */
  .tag {{
    display: inline-block;
    background: #66BB6A;
    color: #FFFFFF;
    font-size: 26px;
    font-weight: 700;
    padding: 8px 22px;
    border-radius: 6px;
    margin-bottom: 28px;
    width: fit-content;
    letter-spacing: -0.3px;
  }}

  /* 헤드라인 */
  .headline {{
    font-size: 44px;
    font-weight: 700;
    color: #1A1A1A;
    line-height: 1.28;
    letter-spacing: -1px;
    margin-bottom: 20px;
  }}

  .headline .highlight {{
    color: #00897B;
  }}

  /* 서브 카피 */
  .sub-copy {{
    font-size: 26px;
    font-weight: 500;
    color: #555555;
    margin-bottom: 40px;
    letter-spacing: -0.3px;
    line-height: 1.5;
  }}

  .sub-copy .dot-sep {{
    color: #66BB6A;
    font-weight: 700;
    margin: 0 8px;
  }}

  /* CTA 버튼 */
  .cta-btn {{
    display: inline-block;
    background: #00897B;
    color: #FFFFFF;
    font-size: 28px;
    font-weight: 700;
    padding: 18px 40px;
    border-radius: 8px;
    letter-spacing: -0.5px;
    width: fit-content;
  }}

  .cta-btn .arrow {{
    margin-left: 8px;
    opacity: 0.9;
  }}

</style>
</head>
<body>
<div class="canvas">

  <!-- 우측 배경 이미지 -->
  <div class="bg-panel"></div>

  <!-- 좌측 텍스트 패널 -->
  <div class="text-panel">
    <div class="tag">영업지원 GA</div>
    <div class="headline">영업이 힘들다면,<br><span class="highlight">시스템 있는 GA</span></div>
    <div class="sub-copy">
      DB 제공<span class="dot-sep">|</span>교육<span class="dot-sep">|</span>함께 성장
    </div>
    <div class="cta-btn">영업지원 GA 알아보기 <span class="arrow">→</span></div>
  </div>

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


def build_html_1080(bg_path: str) -> str:
    """1080x1080 정사각형 배너 HTML."""
    ff = font_faces()
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
{ff}

  * {{ 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; right: 0; bottom: 0;
    background-image: url('file://{bg_path}');
    background-size: cover;
    background-position: center;
    z-index: 0;
  }}

  /* 라이트 그린 반투명 오버레이 (opacity 0.30) */
  .green-overlay {{
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(102, 187, 106, 0.30);
    z-index: 1;
  }}

  /* 하단 그라데이션: 텍스트 가독성 확보 */
  .bottom-gradient {{
    position: absolute;
    bottom: 0; left: 0; right: 0;
    height: 600px;
    background: linear-gradient(
      to bottom,
      rgba(245,249,245,0) 0%,
      rgba(245,249,245,0.75) 40%,
      rgba(245,249,245,0.95) 70%,
      #F5F9F5 100%
    );
    z-index: 2;
  }}

  /* 콘텐츠 레이어 */
  .content {{
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    z-index: 3;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-end;
    padding-bottom: 80px;
  }}

  /* 상단 태그 (배경 이미지 위 간격) */
  .tag {{
    display: inline-block;
    background: #66BB6A;
    color: #FFFFFF;
    font-size: 30px;
    font-weight: 700;
    padding: 10px 28px;
    border-radius: 8px;
    margin-bottom: 32px;
    letter-spacing: -0.3px;
  }}

  /* 헤드라인 */
  .headline {{
    font-size: 54px;
    font-weight: 700;
    color: #1A1A1A;
    text-align: center;
    line-height: 1.28;
    letter-spacing: -1.5px;
    margin-bottom: 28px;
    padding: 0 60px;
  }}

  .headline .highlight {{
    color: #00897B;
  }}

  /* 지원 항목 3줄 */
  .support-items {{
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    margin-bottom: 44px;
  }}

  .support-item {{
    display: flex;
    align-items: center;
    gap: 14px;
    font-size: 30px;
    font-weight: 500;
    color: #333333;
  }}

  .support-icon {{
    width: 36px;
    height: 36px;
    background: #66BB6A;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #FFFFFF;
    font-size: 22px;
    font-weight: 700;
    flex-shrink: 0;
    line-height: 1;
    padding-top: 2px;
  }}

  /* CTA 버튼 */
  .cta-btn {{
    display: inline-block;
    background: #00897B;
    color: #FFFFFF;
    font-size: 32px;
    font-weight: 700;
    padding: 22px 56px;
    border-radius: 8px;
    letter-spacing: -0.5px;
  }}

  .cta-btn .arrow {{
    margin-left: 10px;
  }}

</style>
</head>
<body>
<div class="canvas">

  <!-- 배경 이미지 -->
  <div class="bg-full"></div>

  <!-- 라이트 그린 오버레이 -->
  <div class="green-overlay"></div>

  <!-- 하단 그라데이션 -->
  <div class="bottom-gradient"></div>

  <!-- 콘텐츠 -->
  <div class="content">
    <div class="tag">영업지원 GA</div>
    <div class="headline">영업이 힘들다면,<br><span class="highlight">시스템 있는 GA</span></div>

    <div class="support-items">
      <div class="support-item">
        <div class="support-icon">✓</div>
        <span>DB 제공 — 영업할 고객, 미리 준비</span>
      </div>
      <div class="support-item">
        <div class="support-icon">✓</div>
        <span>교육 — 입사부터 성장까지 지원</span>
      </div>
      <div class="support-item">
        <div class="support-icon">✓</div>
        <span>함께 성장 — 팀과 함께하는 커리어</span>
      </div>
    </div>

    <div class="cta-btn">영업지원 GA 알아보기 <span class="arrow">→</span></div>
  </div>

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


# ─────────────────────────────────────────────────────────────────────────────
# 캡처 함수
# ─────────────────────────────────────────────────────────────────────────────

def capture_banner(html_path: Path, output_path: Path, width: int, height: int) -> None:
    """Playwright로 HTML 배너 캡처."""
    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            page = browser.new_page(viewport={"width": width, "height": height})
            page.goto(f"file://{html_path.resolve()}", wait_until="networkidle")
            # 폰트 및 이미지 렌더링 완료 대기
            page.wait_for_timeout(2500)
            output_path.parent.mkdir(parents=True, exist_ok=True)
            page.screenshot(path=str(output_path), type="png")
        finally:
            browser.close()


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

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

    # 1. 배경 이미지 생성
    print("=" * 60)
    print("GA 영업지원 배너 생성 시작")
    print("=" * 60)
    t0 = time.time()

    bg_path = generate_background()

    # 2. HTML 빌드 및 저장
    print("\n[HTML] 템플릿 빌드 중...")
    html_1200 = build_html_1200(str(bg_path.resolve()))
    HTML_1200.write_text(html_1200, encoding="utf-8")
    print(f"  → {HTML_1200}")

    html_1080 = build_html_1080(str(bg_path.resolve()))
    HTML_1080.write_text(html_1080, encoding="utf-8")
    print(f"  → {HTML_1080}")

    # 3. 캡처
    print("\n[캡처] 1200x628 배너...")
    capture_banner(HTML_1200, OUT_1200, 1200, 628)
    size_1200 = OUT_1200.stat().st_size
    print(f"  → {OUT_1200} ({size_1200:,} bytes)")

    print("\n[캡처] 1080x1080 배너...")
    capture_banner(HTML_1080, OUT_1080, 1080, 1080)
    size_1080 = OUT_1080.stat().st_size
    print(f"  → {OUT_1080} ({size_1080:,} bytes)")

    elapsed = time.time() - t0
    print("\n" + "=" * 60)
    print(f"완료! 총 소요 시간: {elapsed:.1f}초")
    print(f"산출물 1: {OUT_1200}")
    print(f"산출물 2: {OUT_1080}")
    print("=" * 60)


if __name__ == "__main__":
    main()
