#!/usr/bin/env python3
"""Cell-5 GA × 관리자/조직 비전 배너 — 2장 생성
  1. meta-feed-1080x1080.png  (정사각형)
  2. google-resp-1200x628.png (가로형)

Cell-4 GA 브랜드 다크 레드 시스템 기반.
"""

import base64
import sys
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright

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

# ── 경로 ──────────────────────────────────────────────────────────────────────
OUT_DIR = Path("/home/jay/workspace/output/banners/cell-5-ga-leader")
OUT_1080 = OUT_DIR / "meta-feed-1080x1080.png"
OUT_1200 = OUT_DIR / "google-resp-1200x628.png"
HTML_1080 = OUT_DIR / "meta-feed-1080x1080.html"
HTML_1200 = OUT_DIR / "google-resp-1200x628.html"
BG_1080 = OUT_DIR / "bg-cell5-1080.png"
BG_1200 = OUT_DIR / "bg-cell5-1200.png"

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
FONT_DIR = "file:///home/jay/.local/share/fonts/Pretendard"

# ── Gemini 배경 프롬프트 ───────────────────────────────────────────────────────
BG_PROMPT_1080 = (
    "Dark moody cafe interior, empty chairs around a small table, "
    "open laptop with glowing screen, single warm light source from above, "
    "contemplative atmosphere, dark tones with warm highlights, "
    "corporate meeting space feeling, no people, cinematic lighting, "
    "ultra-realistic photograph"
)

BG_PROMPT_1200 = (
    "Wide angle view of dark modern meeting room, long table with empty chairs, "
    "city lights visible through window on right side, warm desk lamp on table, "
    "lonely professional atmosphere, dark ambient with warm accents, "
    "no people, ultra-realistic photograph, landscape format"
)

# ── HTML 템플릿: 1080×1080 ────────────────────────────────────────────────────
HTML_1080_TEMPLATE = """\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{ font-family: 'Pretendard'; src: url('{font_dir}/Pretendard-Black.otf') format('opentype'); font-weight: 900; }}
  @font-face {{ font-family: 'Pretendard'; src: url('{font_dir}/Pretendard-ExtraBold.otf') format('opentype'); font-weight: 800; }}
  @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-SemiBold.otf') format('opentype'); font-weight: 600; }}
  @font-face {{ font-family: 'Pretendard'; src: url('{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;
    background: #0D0D0D;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}
  .container {{
    position: relative;
    width: 1080px;
    height: 1080px;
    overflow: hidden;
  }}

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

  /* 다크 오버레이 */
  .overlay-dark {{
    position: absolute;
    inset: 0;
    background: rgba(0,0,0,0.48);
  }}

  /* 레드 글로우 */
  .overlay-glow {{
    position: absolute;
    inset: 0;
    background: radial-gradient(ellipse 70% 55% at 50% 50%, rgba(239,59,36,0.18) 0%, transparent 70%);
  }}

  /* 중앙 다크 패널 */
  .panel {{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 860px;
    padding: 60px 52px;
    border-radius: 12px;
    background: rgba(13,13,13,0.82);
    backdrop-filter: blur(4px);
    display: flex;
    flex-direction: column;
    gap: 0;
  }}

  /* 뱃지 */
  .badge {{
    display: inline-flex;
    align-items: center;
    height: 52px;
    padding: 0 24px;
    background: #EF3B24;
    border-radius: 6px;
    font-size: 40px;
    font-weight: 700;
    color: #FFFFFF;
    letter-spacing: -0.02em;
    white-space: nowrap;
    width: fit-content;
    margin-bottom: 28px;
  }}

  /* 헤드라인 */
  .headline {{
    font-size: 68px;
    font-weight: 800;
    color: #FFFFFF;
    line-height: 1.22;
    letter-spacing: -0.03em;
    word-break: keep-all;
    margin-bottom: 20px;
  }}
  .headline .red {{ color: #EF3B24; }}

  /* date-tag / urgency */
  .date-tag {{
    font-size: 42px;
    font-weight: 700;
    color: rgba(239,59,36,0.85);
    letter-spacing: -0.02em;
    white-space: nowrap;
    margin-bottom: 18px;
  }}

  /* 구분자 */
  .divider {{
    width: 100%;
    height: 1px;
    background: rgba(239,59,36,0.7);
    margin: 22px 0;
  }}

  /* 서브카피 */
  .sub {{
    font-size: 46px;
    font-weight: 600;
    color: rgba(255,255,255,0.90);
    line-height: 1.35;
    letter-spacing: -0.02em;
    word-break: keep-all;
    margin-bottom: 32px;
  }}

  /* CTA */
  .cta {{
    display: inline-flex;
    align-items: center;
    height: auto;
    padding: 22px 48px;
    background: #EF3B24;
    border-radius: 8px;
    font-size: 46px;
    font-weight: 700;
    color: #FFFFFF;
    letter-spacing: -0.02em;
    white-space: nowrap;
    width: fit-content;
  }}
</style>
</head>
<body>
<div class="container">
  <div class="bg"></div>
  <div class="overlay-dark"></div>
  <div class="overlay-glow"></div>

  <div class="panel">
    <div class="badge">보험설계사 이직 가이드</div>
    <div class="headline">GA 지점장, <span class="red">혼자</span> 시작 안 해도 됩니다</div>
    <div class="date-tag">1200% 룰 시행 전 지점장 전환이 유리한 이유</div>
    <div class="divider"></div>
    <div class="sub">조직 구축 시 사무실 개설비 지원</div>
    <div class="cta">지점장 비전 상담 신청 →</div>
  </div>
</div>
</body>
</html>
"""

# ── HTML 템플릿: 1200×628 ────────────────────────────────────────────────────
HTML_1200_TEMPLATE = """\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{ font-family: 'Pretendard'; src: url('{font_dir}/Pretendard-Black.otf') format('opentype'); font-weight: 900; }}
  @font-face {{ font-family: 'Pretendard'; src: url('{font_dir}/Pretendard-ExtraBold.otf') format('opentype'); font-weight: 800; }}
  @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-SemiBold.otf') format('opentype'); font-weight: 600; }}
  @font-face {{ font-family: 'Pretendard'; src: url('{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: #0D0D0D;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}
  .container {{
    position: relative;
    width: 1200px;
    height: 628px;
    overflow: hidden;
  }}

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

  /* 좌→우 다크 그라데이션 */
  .overlay-grad {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to right,
      rgba(13,13,13,0.92) 0%,
      rgba(13,13,13,0.80) 55%,
      rgba(13,13,13,0.30) 80%,
      rgba(13,13,13,0.05) 100%
    );
  }}

  /* 레드 글로우 (좌측 집중) */
  .overlay-glow {{
    position: absolute;
    inset: 0;
    background: radial-gradient(ellipse 60% 80% at 30% 50%, rgba(239,59,36,0.16) 0%, transparent 70%);
  }}

  /* 좌측 콘텐츠 영역 */
  .left {{
    position: absolute;
    top: 0;
    left: 0;
    width: 760px;
    height: 100%;
    display: flex;
    flex-direction: row;
    align-items: stretch;
  }}

  /* 레드 세로 액센트바 */
  .accent-bar {{
    width: 4px;
    background: #EF3B24;
    margin: 60px 0;
    border-radius: 2px;
    flex-shrink: 0;
  }}

  /* 텍스트 스택 */
  .text-stack {{
    padding-left: 28px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 20px;
  }}

  /* 뱃지 */
  .badge {{
    display: inline-flex;
    align-items: center;
    height: 48px;
    padding: 0 20px;
    background: #EF3B24;
    border-radius: 6px;
    font-size: 40px;
    font-weight: 700;
    color: #FFFFFF;
    letter-spacing: -0.02em;
    white-space: nowrap;
    width: fit-content;
  }}

  /* 헤드라인 */
  .headline {{
    font-size: 62px;
    font-weight: 800;
    color: #FFFFFF;
    line-height: 1.22;
    letter-spacing: -0.03em;
    word-break: keep-all;
  }}
  .headline .red {{ color: #EF3B24; }}

  /* date-tag */
  .date-tag {{
    font-size: 42px;
    font-weight: 700;
    color: rgba(239,59,36,0.85);
    letter-spacing: -0.02em;
    white-space: nowrap;
  }}

  /* 구분자 */
  .divider {{
    color: rgba(239,59,36,0.7);
    font-size: 40px;
    font-weight: 400;
    line-height: 1;
  }}

  /* 서브카피 */
  .sub {{
    font-size: 40px;
    font-weight: 600;
    color: rgba(255,255,255,0.90);
    letter-spacing: -0.02em;
    word-break: keep-all;
  }}

  /* CTA */
  .cta {{
    display: inline-flex;
    align-items: center;
    padding: 20px 44px;
    background: #EF3B24;
    border-radius: 8px;
    font-size: 44px;
    font-weight: 700;
    color: #FFFFFF;
    letter-spacing: -0.02em;
    white-space: nowrap;
    width: fit-content;
  }}
</style>
</head>
<body>
<div class="container">
  <div class="bg"></div>
  <div class="overlay-grad"></div>
  <div class="overlay-glow"></div>

  <div class="left">
    <div class="accent-bar"></div>
    <div class="text-stack">
      <div class="badge">보험설계사 이직 가이드</div>
      <div class="headline">GA 지점장, <span class="red">혼자</span> 시작 안 해도 됩니다</div>
      <div class="date-tag">1200% 룰 시행 전 지점장 전환이 유리한 이유</div>
      <div class="divider">─────────────────────────────</div>
      <div class="sub">조직 구축 시 사무실 개설비 지원</div>
      <div class="cta">지점장 비전 상담 신청 →</div>
    </div>
  </div>
</div>
</body>
</html>
"""


def get_auth_token() -> str | None:
    """인증 토큰을 가져옵니다."""
    try:
        return gcloud_auth.get_service_account_token(
            "https://www.googleapis.com/auth/generative-language"
        )
    except Exception as e:
        print(f"  [SA 토큰 오류] {e} — ADC 시도")
    try:
        return gcloud_auth.get_access_token()
    except Exception as e2:
        print(f"  [인증 실패] {e2}")
        return None


def generate_background(prompt: str, output_path: Path) -> bool:
    """Gemini API로 배경 이미지를 생성합니다."""
    token = get_auth_token()
    if not token:
        return False

    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    models = [
        "gemini-2.0-flash-preview-image-generation",
        "gemini-3.1-flash-image-preview",
        "gemini-3-pro-image-preview",
    ]
    for model in models:
        url = f"{GEMINI_API_BASE}/models/{model}:generateContent"
        payload = {
            "contents": [{"parts": [{"text": 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"])
                    output_path.write_bytes(img_bytes)
                    print(f"  저장 완료: {output_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_path: Path, output_png: Path, width: int, height: int) -> bool:
    """Playwright로 HTML을 PNG로 캡처합니다."""
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": width, "height": height})
        page.goto(f"file://{html_path}")
        page.wait_for_timeout(3000)  # 로컬 폰트 로딩 대기
        page.screenshot(path=str(output_png), type="png")
        browser.close()
    size_kb = output_png.stat().st_size / 1024
    print(f"  PNG 저장: {output_png} ({size_kb:.0f} KB)")
    return True


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

    print("=" * 65)
    print("Cell-5 GA × 관리자/조직 비전 배너 생성")
    print("Cell-4 GA 다크 레드 브랜드 시스템")
    print("=" * 65)

    # ── 1. 배경 이미지 생성 ────────────────────────────────────────────────────
    print("\n[1/4] 1080×1080 배경 이미지 생성...")
    bg1080_ok = generate_background(BG_PROMPT_1080, BG_1080)
    bg1080_url = f"file://{BG_1080}" if bg1080_ok else ""
    if not bg1080_ok:
        print("  [경고] 배경 생성 실패 — 다크 폴백으로 진행")

    print("\n[2/4] 1200×628 배경 이미지 생성...")
    bg1200_ok = generate_background(BG_PROMPT_1200, BG_1200)
    bg1200_url = f"file://{BG_1200}" if bg1200_ok else ""
    if not bg1200_ok:
        print("  [경고] 배경 생성 실패 — 다크 폴백으로 진행")

    # ── 2. HTML 파일 작성 ──────────────────────────────────────────────────────
    print("\n[3/4] HTML 파일 작성 및 1080×1080 렌더링...")
    html_1080_content = HTML_1080_TEMPLATE.format(
        font_dir=FONT_DIR, bg_path=bg1080_url
    )
    HTML_1080.write_text(html_1080_content, encoding="utf-8")
    render_html(HTML_1080, OUT_1080, 1080, 1080)

    print("\n[4/4] HTML 파일 작성 및 1200×628 렌더링...")
    html_1200_content = HTML_1200_TEMPLATE.format(
        font_dir=FONT_DIR, bg_path=bg1200_url
    )
    HTML_1200.write_text(html_1200_content, encoding="utf-8")
    render_html(HTML_1200, OUT_1200, 1200, 628)

    print("\n완료!")
    print(f"  1080×1080 HTML: {HTML_1080}")
    print(f"  1080×1080 PNG : {OUT_1080}")
    print(f"  1200×628  HTML: {HTML_1200}")
    print(f"  1200×628  PNG : {OUT_1200}")


if __name__ == "__main__":
    main()
