#!/usr/bin/env python3
"""Sample B — Impact Number 광고 배너 생성 (hybrid-image 방식)

파이프라인:
1. Gemini API → 추상 금융 배경 이미지 생성 (JPEG)
2. HTML/CSS 오버레이 → Playwright 스크린샷 → PNG 최종 합성
"""

import base64
import json
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/meta-ads/angle-A/concept-samples")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

BG_PATH = OUTPUT_DIR / "sample-B-number-bg.jpg"
FINAL_PATH = OUTPUT_DIR / "sample-B-number.png"
HTML_TEMPLATE_PATH = OUTPUT_DIR / "sample-B-number-template.html"

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

BG_PROMPT = (
    "Abstract financial data visualization background. "
    "Dark navy blue base (#0A1628), deep midnight blue tones. "
    "Glowing gold accent lines forming rising curves and upward trending graphs. "
    "Subtle grid lines, faint data chart elements in background. "
    "Bokeh light particles, luminous gold streaks suggesting growth and momentum. "
    "Premium luxury financial atmosphere. "
    "No text, no numbers, no labels. Pure abstract atmospheric background. "
    "Cinematic quality, ultra-premium financial brand aesthetic. "
    "1:1 square format, 1080x1080px."
)


# ─────────────────────────────────────────────────────────────────────────────
# Step 1: Gemini 배경 이미지 생성
# ─────────────────────────────────────────────────────────────────────────────

def generate_background() -> Path:
    """Gemini API로 배경 이미지를 생성하고 저장합니다."""
    print("[Step 1] Gemini 배경 이미지 생성 중...")
    start = time.time()

    # SA 토큰 방식 사용 (API 키는 쿼터 초과 가능성)
    token = gcloud_auth.get_service_account_token(GEMINI_SCOPE)
    print(f"  SA 토큰 획득 완료 (길이: {len(token)} chars)")

    # 이미지 생성 모델 우선순위
    models_to_try = [
        "gemini-2.5-flash-image",
        "gemini-3-pro-image-preview",
        "gemini-3.1-flash-image-preview",
    ]

    for model_id in models_to_try:
        print(f"  모델 시도: {model_id}")
        try:
            url = f"{GEMINI_API_BASE}/models/{model_id}:generateContent"
            headers = {
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json",
            }

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

            resp = requests.post(url, headers=headers, json=payload, timeout=120)
            print(f"  HTTP 상태: {resp.status_code}")

            if resp.status_code not in (200,):
                print(f"  응답 오류: {resp.text[:300]}")
                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:
                text_parts = [p.get("text", "") for p in parts if "text" in p]
                print(f"  이미지 없음. 텍스트: {text_parts[:1]}")
                continue

            mime_type = image_part["inlineData"].get("mimeType", "image/jpeg")
            image_bytes = base64.b64decode(image_part["inlineData"]["data"])

            ext = ".jpg" if "jpeg" in mime_type else ".png"
            bg_path = BG_PATH.with_suffix(ext)
            bg_path.write_bytes(image_bytes)

            elapsed = time.time() - start
            print(f"  배경 생성 완료: {bg_path.name} ({len(image_bytes):,} bytes, {elapsed:.1f}초)")
            return bg_path

        except Exception as e:
            print(f"  모델 {model_id} 오류: {e}")
            continue

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


# ─────────────────────────────────────────────────────────────────────────────
# Step 2: HTML 오버레이 템플릿 생성
# ─────────────────────────────────────────────────────────────────────────────

def create_html_template(bg_path: Path) -> Path:
    """HTML/CSS 오버레이 템플릿을 생성합니다."""
    print("[Step 2] HTML 오버레이 템플릿 생성 중...")

    bg_url = f"file://{bg_path.resolve()}"

    html = f"""<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=1080">
  <style>
    @import url('file:///home/jay/.local/share/fonts/Pretendard/PretendardVariable.ttf');

    @font-face {{
      font-family: 'Pretendard';
      src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Black.otf') format('opentype');
      font-weight: 900;
    }}
    @font-face {{
      font-family: 'Pretendard';
      src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Bold.otf') format('opentype');
      font-weight: 700;
    }}
    @font-face {{
      font-family: 'Pretendard';
      src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Medium.otf') format('opentype');
      font-weight: 500;
    }}
    @font-face {{
      font-family: 'Pretendard';
      src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Regular.otf') format('opentype');
      font-weight: 400;
    }}

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

    body {{
      width: 1080px;
      height: 1080px;
      overflow: hidden;
      background: #0A1628;
    }}

    .container {{
      position: relative;
      width: 1080px;
      height: 1080px;
      overflow: hidden;
      background-image: url('{bg_url}');
      background-size: cover;
      background-position: center;
      background-color: #0A1628;
    }}

    /* 다크 오버레이 — 배경 이미지 위에 살짝 어둡게 */
    .dark-overlay {{
      position: absolute;
      inset: 0;
      background: linear-gradient(
        180deg,
        rgba(10, 22, 40, 0.55) 0%,
        rgba(10, 22, 40, 0.35) 40%,
        rgba(10, 22, 40, 0.55) 70%,
        rgba(10, 22, 40, 0.80) 100%
      );
    }}

    /* 중앙 콘텐츠 블록 */
    .content-block {{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -52%);
      text-align: center;
      width: 960px;
    }}

    /* 임팩트 숫자 */
    .impact-number {{
      font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
      font-weight: 900;
      font-size: 200px;
      line-height: 0.9;
      color: #D4A843;
      letter-spacing: -4px;
      text-shadow:
        0 0 60px rgba(212, 168, 67, 0.6),
        0 0 120px rgba(212, 168, 67, 0.3),
        0 4px 30px rgba(0, 0, 0, 0.8);
      display: block;
    }}

    /* 서브텍스트 — 매출 성장 */
    .sub-text {{
      font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
      font-weight: 500;
      font-size: 44px;
      color: #FFFFFF;
      letter-spacing: 8px;
      margin-top: 28px;
      display: block;
      text-shadow: 0 2px 12px rgba(0, 0, 0, 0.7);
      opacity: 0.92;
    }}

    /* 골드 구분선 */
    .divider {{
      width: 120px;
      height: 2px;
      background: linear-gradient(90deg, transparent, #D4A843, transparent);
      margin: 36px auto 0;
    }}

    /* 하단 정보 */
    .bottom-info {{
      position: absolute;
      bottom: 60px;
      left: 50%;
      transform: translateX(-50%);
      text-align: center;
      width: 900px;
    }}

    .bottom-text {{
      font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
      font-weight: 400;
      font-size: 26px;
      color: rgba(255, 255, 255, 0.70);
      letter-spacing: 2px;
      text-shadow: 0 1px 8px rgba(0, 0, 0, 0.8);
    }}

    .bottom-text .sep {{
      color: #D4A843;
      margin: 0 12px;
      opacity: 0.8;
    }}
  </style>
</head>
<body>
  <div class="container">
    <!-- 배경 오버레이 -->
    <div class="dark-overlay"></div>

    <!-- 중앙 임팩트 숫자 블록 -->
    <div class="content-block">
      <span class="impact-number">1,863%</span>
      <span class="sub-text">매출 성장</span>
      <div class="divider"></div>
    </div>

    <!-- 하단 정보 -->
    <div class="bottom-info">
      <p class="bottom-text">
        코스닥 상장
        <span class="sep">|</span>
        본부5
        <span class="sep">|</span>
        지점10
        <span class="sep">|</span>
        200+명
      </p>
    </div>
  </div>
</body>
</html>"""

    HTML_TEMPLATE_PATH.write_text(html, encoding="utf-8")
    print(f"  HTML 템플릿 저장: {HTML_TEMPLATE_PATH.name}")
    return HTML_TEMPLATE_PATH


# ─────────────────────────────────────────────────────────────────────────────
# Step 3: Playwright 캡처
# ─────────────────────────────────────────────────────────────────────────────

def capture_with_playwright(html_path: Path) -> Path:
    """Playwright로 HTML을 1080x1080 PNG로 캡처합니다."""
    print("[Step 3] Playwright 캡처 중...")
    start = time.time()

    with sync_playwright() as p:
        browser = p.chromium.launch(args=["--no-sandbox", "--disable-setuid-sandbox"])
        try:
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            template_url = f"file://{html_path.resolve()}"
            page.goto(template_url, wait_until="networkidle")
            # 폰트 및 이미지 렌더링 완료 대기
            page.wait_for_timeout(2000)
            page.screenshot(path=str(FINAL_PATH), type="png", clip={"x": 0, "y": 0, "width": 1080, "height": 1080})
        finally:
            browser.close()

    elapsed = time.time() - start
    size_kb = FINAL_PATH.stat().st_size / 1024
    print(f"  캡처 완료: {FINAL_PATH} ({size_kb:.0f} KB, {elapsed:.1f}초)")
    return FINAL_PATH


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

def main():
    print("=" * 60)
    print("Sample B — Impact Number 배너 생성 시작")
    print(f"출력 경로: {FINAL_PATH}")
    print("=" * 60)
    total_start = time.time()

    # Step 1: 배경 생성
    bg_path = generate_background()

    # Step 2: HTML 템플릿 생성
    html_path = create_html_template(bg_path)

    # Step 3: Playwright 캡처
    final_path = capture_with_playwright(html_path)

    total_elapsed = time.time() - total_start
    print("=" * 60)
    print(f"완료! 총 소요 시간: {total_elapsed:.1f}초")
    print(f"최종 파일: {final_path}")
    print("=" * 60)


if __name__ == "__main__":
    main()
