#!/usr/bin/env python3
"""GA 배너 M2-2 'GA × 관리자 비전' 세트 생성 — 하이브리드 방식 (Gemini 배경 + Playwright 오버레이).

산출물:
  /home/jay/workspace/output/google-ads/banners/m2/m2-2-1200x628.png
  /home/jay/workspace/output/google-ads/banners/m2/m2-2-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("/home/jay/workspace/tools/ai-image-gen")
sys.path.insert(0, str(TOOL_DIR))

import gcloud_auth  # noqa: E402

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

OUTPUT_1200x628 = OUTPUT_DIR / "m2-2-1200x628.png"
OUTPUT_1080x1080 = OUTPUT_DIR / "m2-2-1080x1080.png"

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

# ──────────────────────────────────────────────────────────
# Gemini 배경 생성 프롬프트 (관리자 비전 — 지시사항 그대로)
# ──────────────────────────────────────────────────────────
GEMINI_BG_PROMPT = (
    "Photographic scene of a modern open-plan office space in Seoul. "
    "Medium shot, slightly elevated angle (eye-level standing), looking "
    "across a clean workspace. One male professional in his late 30s, "
    "business casual (white shirt, dark slacks), standing near a clean "
    "white standing desk, looking at a laptop screen slightly angled away. "
    "His posture is upright and purposeful but relaxed. Face in 3/4 profile, "
    "partially visible but not identifiable. The background shows a well-lit "
    "open office with glass-walled meeting rooms — empty. Green potted plants "
    "(monstera) visible in two spots. Warm morning natural light from windows "
    "on the right side. The overall composition has the person on the right "
    "half of frame, leaving the left half open for text. Shallow depth of field, "
    "background office slightly out of focus. 사진 품질, 실사, 오피스 관리자 장면."
)

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

MODELS_TO_TRY = [
    "gemini-2.0-flash-preview-image-generation",
    "gemini-3-pro-image-preview",
    "gemini-3.1-flash-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("  인증: API 키 사용")
        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 MODELS_TO_TRY:
            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 (가로형)
# 디자인 스펙:
#   - 좌측 660px에 미드 그린 그라데이션 오버레이 opacity 0.72
#   - 패딩: 좌 60px, 상 52px
#   - 헤드라인: 54px Bold #FAFAFA, line-height 1.2
#   - 지원 항목: 44px Medium #A5D6A7, gap 20px
#   - 보조 정보: 40px Medium #FAFAFA, gap 16px
#   - CTA: y:530px 고정, 높이 56px, 너비 240px, round 4px, 포레스트그린 #2E7D32, 텍스트 #FAFAFA 44px Bold
#   - 모서리 radius 4px
# ──────────────────────────────────────────────────────────
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;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}

  .canvas {{
    width: 1200px;
    height: 628px;
    position: relative;
    overflow: hidden;
    border-radius: 4px;
  }}

  /* 전체 배경 이미지 (우측 인물이 보이도록) */
  .bg-full {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1200px;
    height: 628px;
    background-image: url('file://{bg_image_path}');
    background-size: cover;
    background-position: center center;
  }}

  /* 좌측 660px 미드 그린 그라데이션 오버레이 opacity 0.72 */
  .overlay-left {{
    position: absolute;
    top: 0;
    left: 0;
    width: 660px;
    height: 628px;
    background: linear-gradient(
      to right,
      rgba(45, 80, 22, 0.72) 0%,
      rgba(45, 80, 22, 0.72) 75%,
      rgba(45, 80, 22, 0.36) 90%,
      rgba(45, 80, 22, 0.0) 100%
    );
  }}

  /* 텍스트 영역 — 좌측 660px, 패딩 좌 60px 상 52px */
  .text-area {{
    position: absolute;
    top: 0;
    left: 0;
    width: 660px;
    height: 628px;
    padding-left: 60px;
    padding-top: 52px;
    padding-right: 40px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
  }}

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

  /* 지원 항목: 44px Medium #A5D6A7, gap 20px */
  .support-items {{
    font-size: 44px;
    font-weight: 500;
    color: #A5D6A7;
    line-height: 1.3;
    margin-top: 20px;
    letter-spacing: -0.5px;
  }}

  /* 보조 정보: 40px Medium #FAFAFA, gap 16px */
  .aux-info {{
    font-size: 40px;
    font-weight: 500;
    color: #FAFAFA;
    line-height: 1.3;
    margin-top: 16px;
    letter-spacing: -0.5px;
  }}

  /* CTA: y:530px 고정, 높이 56px, 너비 auto, round 4px, 다크그린 #1B5E20 (AAA 대비율) */
  .cta-btn {{
    position: absolute;
    top: 530px;
    left: 60px;
    width: auto;
    height: 56px;
    background: #1B5E20;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 44px;
    font-weight: 700;
    color: #FAFAFA;
    white-space: nowrap;
    letter-spacing: -0.5px;
    padding: 0 32px;
  }}
</style>
</head>
<body>
<div class="canvas">

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

  <!-- 좌측 미드 그린 그라데이션 오버레이 -->
  <div class="overlay-left"></div>

  <!-- 텍스트 영역 -->
  <div class="text-area">
    <div class="headline">GA 지점장,&#10;가장 빠른 경로 안내</div>
    <div class="support-items">교육  |  인프라  |  운영 지원</div>
    <div class="aux-info">독립 운영 + GA의 안정적 지원</div>
  </div>

  <!-- CTA 버튼 (y:530px 고정) -->
  <div class="cta-btn">지점장 경로 확인 →</div>

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


# ──────────────────────────────────────────────────────────
# HTML 템플릿 — 1080x1080 (정사각형)
# 디자인 스펙:
#   - 배경 전체 깔림 + 미드 그린 그라데이션 상단 #2D5016 opacity 0.71 → 하단 투명
#   - 패딩: 좌우 72px, 상 88px, 하 80px
#   - 헤드라인: 60px Bold #FAFAFA, 중앙 정렬, line-height 1.2
#   - 지원 항목: 44px Medium #A5D6A7, 중앙 정렬, gap 24px
#   - 보조 정보: 40px Medium #FAFAFA, 중앙 정렬, gap 16px
#   - CTA: 중앙 정렬, 높이 68px, 너비 340px, round 4px, 포레스트그린 #2E7D32, 텍스트 #FAFAFA 48px Bold, gap 36px
#   - 하단 인물/오피스가 충분히 보여야 함 (그라데이션: 상→하 투명)
# ──────────────────────────────────────────────────────────
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;
    border-radius: 4px;
  }}

  /* 전체 배경 이미지 — 인물 상반신이 하단 40% 영역에 보이도록 */
  .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 70%;
  }}

  /* 미드 그린 그라데이션: 상단 opacity 0.71 → 하단 투명 (하단 인물/오피스 노출) */
  .overlay-top {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1080px;
    height: 1080px;
    background: linear-gradient(
      to bottom,
      rgba(45, 80, 22, 0.71) 0%,
      rgba(45, 80, 22, 0.71) 45%,
      rgba(45, 80, 22, 0.35) 70%,
      rgba(45, 80, 22, 0.0) 100%
    );
  }}

  /* 콘텐츠 영역: 패딩 좌우 72px, 상 88px, 하 80px, 중앙 정렬 */
  .content-area {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1080px;
    height: 1080px;
    padding: 88px 72px 80px 72px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
  }}

  /* 헤드라인: 60px Bold #FAFAFA, 중앙 정렬, line-height 1.2 */
  .headline {{
    font-size: 60px;
    font-weight: 700;
    color: #FAFAFA;
    line-height: 1.2;
    letter-spacing: -1.5px;
    text-align: center;
    white-space: pre-line;
  }}

  /* 지원 항목: 44px Medium #A5D6A7, 중앙 정렬, gap 24px */
  .support-items {{
    font-size: 44px;
    font-weight: 500;
    color: #A5D6A7;
    line-height: 1.3;
    text-align: center;
    margin-top: 24px;
    letter-spacing: -0.5px;
  }}

  /* 보조 정보: 40px Medium #FAFAFA, 중앙 정렬, gap 16px */
  .aux-info {{
    font-size: 40px;
    font-weight: 500;
    color: #FAFAFA;
    line-height: 1.3;
    text-align: center;
    margin-top: 16px;
    letter-spacing: -0.5px;
  }}

  /* CTA: 중앙, 높이 68px, 너비 auto, round 4px, 다크그린 #1B5E20 (AAA 대비율), gap 36px */
  .cta-btn {{
    margin-top: 36px;
    width: auto;
    height: 76px;
    background: #1B5E20;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 48px;
    font-weight: 700;
    color: #FAFAFA;
    white-space: nowrap;
    letter-spacing: -0.5px;
    padding: 0 40px;
  }}
</style>
</head>
<body>
<div class="canvas">

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

  <!-- 미드 그린 그라데이션 오버레이 (상→하 투명) -->
  <div class="overlay-top"></div>

  <!-- 콘텐츠 영역 (상단 정렬, 중앙 텍스트) -->
  <div class="content-area">
    <div class="headline">GA 지점장,&#10;가장 빠른 경로 안내</div>
    <div class="support-items">교육  |  인프라  |  운영 지원</div>
    <div class="aux-info">독립 운영 + GA의 안정적 지원</div>
    <div class="cta-btn">지점장 경로 확인 →</div>
  </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-2 'GA × 관리자 비전' 하이브리드 이미지 생성")
    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()
