#!/usr/bin/env python3
"""Facebook 페이지 커버 이미지 생성: 전국보험설계사채용 (820×312px)
Gemini 배경 생성 + HTML 오버레이 + Playwright PNG 렌더링
"""

from __future__ import annotations

import base64
import json
import os
import sys
import time
from pathlib import Path

import requests

# ─────────────────────────────────────────────────────────────────────────────
# 설정
# ─────────────────────────────────────────────────────────────────────────────

OUTPUT_DIR = Path("/home/jay/workspace/output/fb-pages")
BG_PATH = OUTPUT_DIR / "recruit_bg.jpg"
HTML_PATH = OUTPUT_DIR / "recruit-cover-820x312.html"
PNG_PATH = OUTPUT_DIR / "recruit-cover-820x312.png"

WIDTH = 820
HEIGHT = 312

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
GEMINI_MODEL = "gemini-2.5-flash-image"

# Gemini 배경 프롬프트 - 포토리얼 비즈니스/오피스 씬
BG_PROMPT = (
    "Professional office scene photograph. "
    "Modern corporate meeting room in Korea, wide panoramic view. "
    "Floor-to-ceiling windows showing city skyline, warm afternoon golden hour light. "
    "Clean minimalist interior with navy blue and warm wood accents. "
    "Empty conference table reflecting light, blurred depth of field background. "
    "Shot on Sony A7R V, 35mm f/2.8, cinematic color grade. "
    "No people, no text, no icons, no graphics. "
    "Wide horizontal composition suitable for a Facebook cover photo banner. "
    "High quality corporate real estate photography style. "
    "Color palette: deep navy, warm gold, cream white. "
    "Aspect ratio: landscape wide format."
)

# ─────────────────────────────────────────────────────────────────────────────
# 인증
# ─────────────────────────────────────────────────────────────────────────────

sys.path.insert(0, "/home/jay/workspace/tools/ai-image-gen")
import gcloud_auth


def get_token() -> str:
    return gcloud_auth.get_access_token()


def get_api_key() -> str | None:
    return gcloud_auth.get_api_key("GEMINI_API_KEY")


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

def generate_background() -> bool:
    """Gemini API로 배경 이미지를 생성하고 BG_PATH에 저장합니다."""
    print("[1/3] Gemini 배경 이미지 생성 중...")

    # SA 토큰 우선 사용 (API key는 quota 제한이 있음)
    try:
        token = gcloud_auth.get_service_account_token()
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }
        use_api_key = False
        print("  SA 토큰 인증 사용")
    except Exception:
        api_key = get_api_key()
        if api_key:
            headers = {"Content-Type": "application/json"}
            use_api_key = True
            print("  API 키 인증 사용")
        else:
            token = get_token()
            headers = {
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json",
            }
            use_api_key = False

    payload = {
        "contents": [{"parts": [{"text": BG_PROMPT}]}],
        "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
    }

    models_to_try = [
        "gemini-2.5-flash-image",
        "gemini-3-pro-image-preview",
        "gemini-3.1-flash-image-preview",
        "imagen-4.0-fast-generate-001",
    ]

    for model in models_to_try:
        try:
            if use_api_key:
                api_key = get_api_key()
                try_url = f"{GEMINI_API_BASE}/models/{model}:generateContent?key={api_key}"
                if "imagen" in model:
                    try_url = f"{GEMINI_API_BASE}/models/{model}:predict?key={api_key}"
            else:
                try_url = f"{GEMINI_API_BASE}/models/{model}:generateContent"
                if "imagen" in model:
                    try_url = f"{GEMINI_API_BASE}/models/{model}:predict"

            print(f"  시도 중: {model}")

            if "imagen" in model:
                # Imagen API
                imagen_payload = {
                    "instances": [{"prompt": BG_PROMPT}],
                    "parameters": {"sampleCount": 1, "aspectRatio": "16:9"},
                }
                resp = requests.post(try_url, headers=headers, json=imagen_payload, timeout=120)
                if resp.status_code == 200:
                    data = resp.json()
                    predictions = data.get("predictions", [])
                    if predictions:
                        b64 = predictions[0].get("bytesBase64Encoded", "")
                        if b64:
                            img_bytes = base64.b64decode(b64)
                            BG_PATH.write_bytes(img_bytes)
                            print(f"  [OK] 배경 저장: {BG_PATH} ({len(img_bytes)//1024}KB)")
                            return True
            else:
                resp = requests.post(try_url, headers=headers, json=payload, timeout=120)
                if resp.status_code == 200:
                    data = resp.json()
                    candidates = data.get("candidates", [])
                    for candidate in candidates:
                        parts = candidate.get("content", {}).get("parts", [])
                        for part in parts:
                            if "inlineData" in part:
                                b64 = part["inlineData"].get("data", "")
                                if b64:
                                    img_bytes = base64.b64decode(b64)
                                    BG_PATH.write_bytes(img_bytes)
                                    print(f"  [OK] 배경 저장: {BG_PATH} ({len(img_bytes)//1024}KB)")
                                    return True
                else:
                    print(f"  [{resp.status_code}] {model} 실패: {resp.text[:200]}")

        except Exception as e:
            print(f"  [ERROR] {model}: {e}")
            continue

    print("  [WARN] Gemini 배경 생성 실패 — 그라데이션 폴백 사용")
    return False


# ─────────────────────────────────────────────────────────────────────────────
# HTML 생성
# ─────────────────────────────────────────────────────────────────────────────

def build_html(bg_available: bool) -> str:
    """820×312 Facebook 커버 HTML을 생성합니다."""

    if bg_available and BG_PATH.exists():
        bg_style = f"background-image: url('file://{BG_PATH.resolve()}'); background-size: cover; background-position: center right;"
    else:
        # 폴백: navy 그라데이션
        bg_style = "background: linear-gradient(135deg, #1B365D 0%, #2C5282 60%, #1a4a6e 100%);"

    html = f"""<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=820">
<title>전국보험설계사채용 Facebook 커버</title>
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-ExtraBold.otf') format('opentype');
    font-weight: 800;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Regular.otf') format('opentype');
    font-weight: 400;
    font-style: normal;
  }}

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

  body {{
    width: {WIDTH}px;
    height: {HEIGHT}px;
    overflow: hidden;
    background: #0a0a0a;
  }}

  .cover {{
    position: relative;
    width: {WIDTH}px;
    height: {HEIGHT}px;
    {bg_style}
    overflow: hidden;
  }}

  /* 좌→우 그라데이션 오버레이: 텍스트 가독성 확보 */
  .overlay-gradient {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to right,
      rgba(27, 54, 93, 0.92) 0%,
      rgba(27, 54, 93, 0.88) 30%,
      rgba(27, 54, 93, 0.65) 55%,
      rgba(27, 54, 93, 0.10) 80%,
      transparent 100%
    );
  }}

  /* 하단 미묘한 섀도우 — 배경 틴티드 */
  .overlay-bottom {{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 80px;
    background: linear-gradient(to top, rgba(11, 29, 58, 0.4) 0%, transparent 100%);
  }}

  /* 텍스트 블록: 좌측 55% 영역 */
  .text-block {{
    position: absolute;
    top: 50%;
    left: 48px;
    transform: translateY(-50%);
    width: 420px;
    display: flex;
    flex-direction: column;
    gap: 14px;
  }}

  /* 상단 배지 */
  .badge {{
    display: inline-flex;
    align-items: center;
    gap: 6px;
    width: fit-content;
    padding: 5px 14px;
    border: 1.5px solid rgba(201, 168, 76, 0.6);
    border-radius: 100px;
    background: rgba(201, 168, 76, 0.12);
  }}

  .badge-dot {{
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #C9A84C;
    flex-shrink: 0;
  }}

  .badge-text {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-weight: 700;
    font-size: 11px;
    letter-spacing: 0.12em;
    color: #C9A84C;
    white-space: nowrap;
    text-transform: uppercase;
  }}

  /* 메인 헤드라인 */
  .headline {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-weight: 800;
    font-size: 36px;
    line-height: 1.2;
    color: #F5F0E8;
    white-space: nowrap;
    word-break: keep-all;
    text-shadow: 0 2px 12px rgba(11, 29, 58, 0.5);
    letter-spacing: -0.02em;
  }}

  /* 서브카피 */
  .subcopy {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-weight: 700;
    font-size: 15px;
    line-height: 1.375;
    color: #C9A84C;
    white-space: nowrap;
    word-break: keep-all;
    letter-spacing: 0.04em;
  }}

  /* 구분자 스타일 */
  .subcopy .sep {{
    color: rgba(201, 168, 76, 0.5);
    margin: 0 8px;
    font-weight: 400;
  }}

  /* 하단 구분선 + 태그라인 */
  .divider {{
    width: 40px;
    height: 2px;
    background: linear-gradient(to right, #C9A84C, rgba(201, 168, 76, 0.2));
    border-radius: 1px;
  }}

  .tagline {{
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-weight: 400;
    font-size: 12px;
    color: rgba(245, 240, 232, 0.65);
    white-space: nowrap;
    letter-spacing: 0.01em;
  }}

  /* 우측 로고 영역 (선택적 — 브랜딩) */
  .logo-area {{
    position: absolute;
    top: 24px;
    right: 32px;
    display: flex;
    align-items: center;
    gap: 8px;
  }}

  .logo-icon {{
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background: rgba(201, 168, 76, 0.2);
    border: 1.5px solid rgba(201, 168, 76, 0.4);
    display: flex;
    align-items: center;
    justify-content: center;
  }}

  .logo-icon svg {{
    width: 18px;
    height: 18px;
  }}
</style>
</head>
<body>
<div class="cover">
  <!-- 배경 그라데이션 오버레이 -->
  <div class="overlay-gradient"></div>
  <div class="overlay-bottom"></div>

  <!-- 텍스트 블록 (좌측) -->
  <div class="text-block">
    <!-- 배지 -->
    <div class="badge">
      <div class="badge-dot"></div>
      <span class="badge-text">NATIONWIDE RECRUITING</span>
    </div>

    <!-- 메인 헤드라인 -->
    <h1 class="headline">전국 보험설계사 채용</h1>

    <!-- 서브카피 -->
    <p class="subcopy">
      정착지원금<span class="sep">|</span>경력 인정<span class="sep">|</span>전문 교육
    </p>

    <!-- 구분선 + 태그라인 -->
    <div class="divider"></div>
    <p class="tagline">당신의 커리어를 새로운 수준으로 — 지금 바로 시작하세요</p>
  </div>

  <!-- 우측 로고 아이콘 -->
  <div class="logo-area">
    <div class="logo-icon">
      <svg viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M9 2L11.5 7H16.5L12.5 10.5L14 15.5L9 12.5L4 15.5L5.5 10.5L1.5 7H6.5L9 2Z"
              fill="#C9A84C" opacity="0.9"/>
      </svg>
    </div>
  </div>
</div>
</body>
</html>"""
    return html


# ─────────────────────────────────────────────────────────────────────────────
# Playwright PNG 렌더링
# ─────────────────────────────────────────────────────────────────────────────

def render_png():
    """Playwright로 HTML을 820×312 PNG로 렌더링합니다."""
    print("[3/3] Playwright PNG 렌더링 중...")
    from playwright.sync_api import sync_playwright

    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(2000)  # 폰트 & 배경 로딩 대기
            page.screenshot(path=str(PNG_PATH), type="png", clip={
                "x": 0, "y": 0,
                "width": WIDTH, "height": HEIGHT
            })
        finally:
            browser.close()

    size_kb = PNG_PATH.stat().st_size / 1024
    print(f"  [OK] PNG 저장: {PNG_PATH} ({size_kb:.0f}KB)")


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

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

    # 1. Gemini 배경 생성
    bg_ok = generate_background()

    # 2. HTML 생성
    print("[2/3] HTML 오버레이 생성 중...")
    html_content = build_html(bg_ok)
    HTML_PATH.write_text(html_content, encoding="utf-8")
    print(f"  [OK] HTML 저장: {HTML_PATH}")

    # 3. PNG 렌더링
    render_png()

    # 최종 확인
    if PNG_PATH.exists():
        size_kb = PNG_PATH.stat().st_size / 1024
        print(f"\n=== 완료 ===")
        print(f"PNG: {PNG_PATH} ({size_kb:.0f}KB)")
        print(f"HTML: {HTML_PATH}")
        print(f"배경: {'Gemini AI' if bg_ok else '그라데이션 폴백'}")
    else:
        print("\n[FAIL] PNG 파일이 생성되지 않았습니다.")
        sys.exit(1)


if __name__ == "__main__":
    main()
