#!/usr/bin/env python3
"""GA 배너 M2-2 '관리자 비전' 세트 — 2장 생성
  1. ga-leader-1200x628.png  (가로형)
  2. ga-leader-1080x1080.png (정사각형)
컨셉 #45 금융 럭셔리 + GA 그린 적용
"""

import base64
import sys
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright
from gen_config import WORKSPACE_ROOT, FONT_DIR

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth
_SIZE_22PX = 22
_SIZE_24PX = 24
_SIZE_26PX = 26
_SIZE_28PX = 28
_SIZE_30PX = 30
_SIZE_46PX = 46
_SIZE_58PX = 58
_LH_1_25 = 1.25
_LH_1_22 = 1.22
_LH_1_5 = 1.5

# ── 경로 ──────────────────────────────────────────────────────────────────────
WORK_DIR = WORKSPACE_ROOT / "output/google-ads/banners"
OUTPUT_1200x628 = WORK_DIR / "ga-leader-1200x628.png"
OUTPUT_1080x1080 = WORK_DIR / "ga-leader-1080x1080.png"
BG_PATH = WORK_DIR / "ga_leader_bg.jpg"

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"

# ── Gemini 배경 프롬프트 ───────────────────────────────────────────────────────
BG_PROMPT = (
    "A person standing in front of a whiteboard in a wide open modern office, "
    "seen from behind, drawing a simple org chart or strategy diagram. "
    "Bright natural daylight, clean minimalist office environment. "
    "The person is wearing smart business casual attire. "
    "The whiteboard shows clean lines and boxes – an organizational chart. "
    "Wide-angle photorealistic scene conveying leadership and planning. "
    "Soft natural light through large windows, neutral tones. "
    "Professional business photography quality. No text, no watermarks."
)

# ── HTML 템플릿: 1200x628 (가로형) ───────────────────────────────────────────
HTML_1200x628 = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('{font_dir}/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('{font_dir}/Pretendard-Medium.otf') format('opentype');
    font-weight: 500;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('{font_dir}/Pretendard-SemiBold.otf') format('opentype');
    font-weight: 600;
  }}
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  body {{
    width: 1200px;
    height: 628px;
    overflow: hidden;
    background: #1a2a1a;
  }}
  .container {{
    position: relative;
    width: 1200px;
    height: 628px;
    overflow: hidden;
  }}
  /* 배경 이미지 — 우측 45% */
  .bg-image {{
    position: absolute;
    top: 0;
    right: 0;
    width: 54%;
    height: 100%;
    background-image: url('{bg_path}');
    background-size: cover;
    background-position: center right;
  }}
  /* 우측 이미지 위에 얇은 투명 오버레이만 (피사체 보호) */
  .bg-image::after {{
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to right,
      rgba(240,245,240,0.55) 0%,
      rgba(240,245,240,0.1) 35%,
      rgba(240,245,240,0.0) 100%
    );
  }}
  /* 좌측 텍스트 패널 — 55% */
  .left-panel {{
    position: absolute;
    top: 0;
    left: 0;
    width: 55%;
    height: 100%;
    background: rgba(248,250,248,0.82);
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 52px 56px;
  }}
  /* 상단 레이블 */
  .label {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_22PX}px;
    font-weight: 600;
    color: #00897B;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    margin-bottom: 18px;
  }}
  /* 헤드라인 */
  .headline {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_46PX}px;
    font-weight: 700;
    color: #1a2a1a;
    line-height: {_LH_1_25};
    letter-spacing: -0.02em;
    margin-bottom: 20px;
  }}
  /* 구분선 */
  .divider {{
    width: 56px;
    height: 4px;
    background: #2E7D32;
    border-radius: 2px;
    margin-bottom: 20px;
  }}
  /* 서브텍스트 */
  .sub {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_24PX}px;
    font-weight: 500;
    color: #78909C;
    letter-spacing: 0.04em;
    margin-bottom: 36px;
  }}
  /* CTA 버튼 */
  .cta-btn {{
    display: inline-block;
    background: #2E7D32;
    color: #FFFFFF;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_22PX}px;
    font-weight: 700;
    padding: 16px 36px;
    border-radius: 4px;
    letter-spacing: 0.03em;
    white-space: nowrap;
    width: fit-content;
  }}
</style>
</head>
<body>
<div class="container">
  <!-- 배경 이미지 (우측) -->
  <div class="bg-image"></div>

  <!-- 좌측 텍스트 패널 -->
  <div class="left-panel">
    <div class="label">GA Manager Path</div>
    <div class="headline">GA 지점장,<br>가장 빠른 경로 안내</div>
    <div class="divider"></div>
    <div class="sub">교육 &nbsp;|&nbsp; 인프라 &nbsp;|&nbsp; 운영 지원</div>
    <div class="cta-btn">지점장 경로 확인</div>
  </div>
</div>
</body>
</html>
"""

# ── HTML 템플릿: 1080x1080 (정사각형) ────────────────────────────────────────
HTML_1080x1080 = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('{font_dir}/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('{font_dir}/Pretendard-Medium.otf') format('opentype');
    font-weight: 500;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('{font_dir}/Pretendard-SemiBold.otf') format('opentype');
    font-weight: 600;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('{font_dir}/Pretendard-ExtraBold.otf') format('opentype');
    font-weight: 800;
  }}
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  body {{
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background: #1a2a1a;
  }}
  .container {{
    position: relative;
    width: 1080px;
    height: 1080px;
    overflow: hidden;
  }}
  /* 전체 배경 이미지 */
  .bg-image {{
    position: absolute;
    inset: 0;
    background-image: url('{bg_path}');
    background-size: cover;
    background-position: center;
  }}
  /* 라이트 그린 그라데이션 오버레이: 상단→하단 밝아지는 방향 */
  /* 텍스트 가독성 위해 상단에 더 진한 처리, 하단은 밝게 */
  .overlay {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to bottom,
      rgba(28, 56, 28, 0.72) 0%,
      rgba(40, 72, 40, 0.58) 30%,
      rgba(60, 100, 60, 0.38) 60%,
      rgba(200, 230, 200, 0.22) 100%
    );
  }}
  /* 텍스트 영역 */
  .content {{
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 72px 64px 76px;
  }}
  /* 상단 헤드라인 블록 */
  .top-block {{
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    flex: 0 0 auto;
    padding-top: 16px;
  }}
  .label {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_26PX}px;
    font-weight: 600;
    color: rgba(200, 240, 200, 0.9);
    letter-spacing: 0.14em;
    text-transform: uppercase;
    margin-bottom: 22px;
  }}
  .headline {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_58PX}px;
    font-weight: 800;
    color: #FFFFFF;
    line-height: {_LH_1_22};
    letter-spacing: -0.02em;
    text-align: center;
    text-shadow: 0 2px 16px rgba(0,0,0,0.45);
  }}
  /* 중앙 지원 사항 */
  .mid-block {{
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    flex: 0 0 auto;
  }}
  .divider {{
    width: 64px;
    height: 4px;
    background: #A5D6A7;
    border-radius: 2px;
    margin-bottom: 28px;
  }}
  .support-list {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_30PX}px;
    font-weight: 500;
    color: rgba(255,255,255,0.92);
    letter-spacing: 0.06em;
    text-align: center;
    text-shadow: 0 1px 8px rgba(0,0,0,0.4);
    line-height: {_LH_1_5};
  }}
  /* 하단 CTA */
  .bottom-block {{
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 0 0 auto;
  }}
  .cta-btn {{
    display: inline-block;
    background: #2E7D32;
    color: #FFFFFF;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_28PX}px;
    font-weight: 700;
    padding: 20px 56px;
    border-radius: 4px;
    letter-spacing: 0.04em;
    text-align: center;
    box-shadow: 0 4px 20px rgba(46, 125, 50, 0.5);
  }}
</style>
</head>
<body>
<div class="container">
  <div class="bg-image"></div>
  <div class="overlay"></div>
  <div class="content">
    <!-- 상단 헤드라인 -->
    <div class="top-block">
      <div class="label">GA Manager Path</div>
      <div class="headline">GA 지점장,<br>가장 빠른 경로 안내</div>
    </div>
    <!-- 중앙 지원 사항 -->
    <div class="mid-block">
      <div class="divider"></div>
      <div class="support-list">교육 &nbsp;|&nbsp; 인프라 &nbsp;|&nbsp; 운영 지원</div>
    </div>
    <!-- 하단 CTA -->
    <div class="bottom-block">
      <div class="cta-btn">지점장 경로 확인</div>
    </div>
  </div>
</div>
</body>
</html>
"""


def generate_background() -> bool:
    """Gemini API로 배경 이미지를 생성합니다."""
    try:
        sa_token = gcloud_auth.get_service_account_token(
            "https://www.googleapis.com/auth/generative-language"
        )
    except Exception as e:
        print(f"  [SA 토큰 오류] {e} — ADC/gcloud 시도")
        try:
            sa_token = gcloud_auth.get_access_token()
        except Exception as e2:
            print(f"  [인증 실패] {e2}")
            return False

    headers = {"Authorization": f"Bearer {sa_token}", "Content-Type": "application/json"}
    models = [
        "gemini-3.1-flash-image-preview",
        "gemini-3-pro-image-preview",
        "gemini-2.5-flash-image",
    ]
    for model in models:
        url = f"{GEMINI_API_BASE}/models/{model}:generateContent"
        payload = {
            "contents": [{"parts": [{"text": BG_PROMPT}]}],
            "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]},
        }
        print(f"  배경 생성 요청 중... (모델: {model})")
        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=120)
        except Exception as e:
            print(f"  [연결 오류] {e}")
            continue
        if resp.status_code == 200:
            data = resp.json()
            for part in (
                data.get("candidates", [{}])[0]
                .get("content", {})
                .get("parts", [])
            ):
                if "inlineData" in part:
                    img_bytes = base64.b64decode(part["inlineData"]["data"])
                    BG_PATH.write_bytes(img_bytes)
                    print(f"  배경 저장 완료: {BG_PATH} ({len(img_bytes):,} bytes)")
                    return True
            reason = data.get("candidates", [{}])[0].get("finishReason", "?")
            print(f"  [이미지 파트 없음] finishReason={reason}")
            print(f"  응답 일부: {str(data)[:400]}")
        else:
            print(f"  [HTTP {resp.status_code}] {resp.text[:300]}")
    return False


def render_html(html_content: str, output_path: Path, width: int, height: int) -> bool:
    """Playwright로 HTML을 PNG로 캡처합니다."""
    html_file = WORK_DIR / f"overlay_{width}x{height}.html"
    html_file.write_text(html_content, encoding="utf-8")
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": width, "height": height})
        page.goto(f"file://{html_file}")
        page.wait_for_timeout(2500)  # 로컬 폰트 로딩 대기
        page.screenshot(path=str(output_path), type="png")
        browser.close()
    size_kb = output_path.stat().st_size / 1024
    print(f"  PNG 저장 완료: {output_path} ({size_kb:.0f} KB)")
    return True


def main():
    WORK_DIR.mkdir(parents=True, exist_ok=True)

    print("=" * 60)
    print("GA 배너 M2-2 '관리자 비전' 세트 생성")
    print("컨셉 #45 금융 럭셔리 + GA 그린")
    print("=" * 60)

    # 1. 배경 생성
    print("\n[1/3] Gemini 배경 이미지 생성...")
    bg_ok = generate_background()
    if bg_ok:
        bg_url = f"file://{BG_PATH}"
        print("  배경 생성 성공")
    else:
        print("  [경고] 배경 생성 실패 — 컬러 폴백으로 진행")
        bg_url = ""

    # 2. 1200x628 렌더링
    print("\n[2/3] 1200x628 가로형 배너 렌더링...")
    html_wide = HTML_1200x628.format(font_dir=f"file://{FONT_DIR}", bg_path=bg_url)
    render_html(html_wide, OUTPUT_1200x628, 1200, 628)

    # 3. 1080x1080 렌더링
    print("\n[3/3] 1080x1080 정사각형 배너 렌더링...")
    html_sq = HTML_1080x1080.format(font_dir=f"file://{FONT_DIR}", bg_path=bg_url)
    render_html(html_sq, OUTPUT_1080x1080, 1080, 1080)

    print("\n완료!")
    print(f"  1200x628 : {OUTPUT_1200x628}")
    print(f"  1080x1080: {OUTPUT_1080x1080}")


if __name__ == "__main__":
    main()
