#!/usr/bin/env python3
"""컨셉 #45 Finance Luxury Frame — Robinhood Visual System (One Show 2025 Gold Pencil)"""

import base64
import shutil
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

# ── 경로 설정 ──────────────────────────────────────────────────────────────
OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/concept-catalog/45-oneshow-finance-luxury")
BG_PATH = OUTPUT_DIR / "bg.jpg"
SAMPLE_PATH = OUTPUT_DIR / "sample.png"
COPY_PATH = OUTPUT_DIR / "45-finance-luxury-frame.png"

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

# Option B: Business suit lapel + business card extreme close-up (dark tones)
BG_PROMPT = (
    "Extreme macro close-up of a luxury business suit lapel and business card, "
    "very dark luxury editorial photography, "
    "deep charcoal black fabric texture, fine wool weave visible up close, "
    "a crisp matte white business card resting against the lapel, "
    "dramatic low-key lighting with single rim light from side, "
    "95% of the frame is deep shadow, only fabric texture catches faint light, "
    "ultra shallow depth of field, bokeh background, "
    "average brightness 20-25%, "
    "shot on Hasselblad H6D with 120mm macro lens, "
    "luxury fashion editorial, Robinhood rebrand aesthetic, "
    "no text, no watermarks, square 1:1 format"
)

HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@400;700;900&family=Noto+Sans+KR:wght@400;700;900&display=swap" rel="stylesheet">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background-color: #0A0A0A;
  }
  .container {
    position: relative;
    width: 1080px;
    height: 1080px;
    background-image: url('__BG_PATH__');
    background-size: cover;
    background-position: center;
  }

  /* 상단→하단 반투명 검정 그라디언트 오버레이 */
  .overlay-gradient {
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0.72) 0%,
      rgba(0, 0, 0, 0.45) 35%,
      rgba(0, 0, 0, 0.25) 55%,
      rgba(0, 0, 0, 0.78) 80%,
      rgba(0, 0, 0, 0.92) 100%
    );
  }

  /* 상단 1/3 — 메인 헤드라인 영역 */
  .top-block {
    position: absolute;
    top: 80px;
    left: 72px;
    right: 72px;
  }

  /* 메인 헤드라인 */
  .headline {
    font-family: 'Noto Serif KR', 'Pretendard', 'Noto Sans KR', serif;
    font-size: 84px;
    font-weight: 700;
    color: #FFFFFF;
    line-height: 1.25;
    letter-spacing: -0.02em;
  }

  /* 중앙 — 액센트 숫자 블록 */
  .center-block {
    position: absolute;
    top: 50%;
    left: 72px;
    right: 72px;
    transform: translateY(-50%);
  }

  /* 액센트 넘버 — 단 하나의 컬러 */
  .accent-number {
    font-family: 'Noto Sans KR', 'Pretendard', sans-serif;
    font-size: 96px;
    font-weight: 900;
    color: #39FF14;
    line-height: 1.1;
    letter-spacing: -0.03em;
    display: block;
  }

  /* 서브 텍스트 */
  .sub-text {
    font-family: 'Noto Sans KR', 'Pretendard', sans-serif;
    font-size: 64px;
    font-weight: 700;
    color: rgba(255, 255, 255, 0.70);
    line-height: 1.2;
    letter-spacing: -0.01em;
    margin-top: 12px;
  }

  /* 하단 CTA 블록 */
  .bottom-block {
    position: absolute;
    bottom: 72px;
    left: 72px;
    right: 72px;
  }

  /* 얇은 흰색 구분선 */
  .divider {
    width: 100%;
    height: 1px;
    background: rgba(255, 255, 255, 0.25);
    margin-bottom: 28px;
  }

  /* CTA 텍스트 */
  .cta-text {
    font-family: 'Noto Sans KR', 'Pretendard', sans-serif;
    font-size: 40px;
    font-weight: 400;
    color: #FFFFFF;
    letter-spacing: 0.04em;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .cta-brand {
    font-weight: 700;
  }

  /* 화살표 화살표 아이콘 */
  .cta-arrow {
    font-size: 40px;
    color: #39FF14;
  }

  /* 좌측 하단 태그 */
  .tag {
    position: absolute;
    top: 80px;
    right: 72px;
    font-family: 'Noto Sans KR', 'Pretendard', sans-serif;
    font-size: 28px;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.4);
    letter-spacing: 0.1em;
    text-transform: uppercase;
  }
</style>
</head>
<body>
<div class="container">
  <div class="overlay-gradient"></div>

  <!-- 태그 -->
  <div class="tag">T.O.P 사업단</div>

  <!-- 상단 헤드라인 -->
  <div class="top-block">
    <div class="headline">열심히는 하는데,<br>월급은 제자리걸음?</div>
  </div>

  <!-- 중앙 액센트 넘버 + 서브 -->
  <div class="center-block">
    <span class="accent-number">최대 1,000만원</span>
    <div class="sub-text">신입 정착지원금</div>
  </div>

  <!-- 하단 CTA -->
  <div class="bottom-block">
    <div class="divider"></div>
    <div class="cta-text">
      <span><span class="cta-brand">T.O.P 사업단</span> &nbsp;|&nbsp; 지금 상담 신청하기</span>
      <span class="cta-arrow">→</span>
    </div>
  </div>
</div>
</body>
</html>
"""


def generate_background() -> bool:
    """Gemini SA 토큰으로 배경 이미지를 생성합니다."""
    sa_token = gcloud_auth.get_service_account_token("https://www.googleapis.com/auth/generative-language")
    if not sa_token:
        print("  [오류] SA 토큰 없음")
        return False
    headers = {"Authorization": f"Bearer {sa_token}", "Content-Type": "application/json"}
    # Try flash-image-preview first (more widely accessible)
    models_to_try = [
        "gemini-2.0-flash-preview-image-generation",
        "gemini-3.1-flash-image-preview",
        "gemini-3-pro-image-preview",
    ]
    for model in models_to_try:
        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)[:300]}")
        else:
            print(f"  [HTTP {resp.status_code}] {resp.text[:200]}")
    return False


def render_html(html_content: str) -> bool:
    """Playwright로 HTML을 PNG로 캡처합니다."""
    html_file = OUTPUT_DIR / "overlay45.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": 1080, "height": 1080})
        page.goto(f"file://{html_file}")
        # 웹폰트 로딩 대기
        page.wait_for_timeout(3000)
        page.screenshot(path=str(SAMPLE_PATH), type="png")
        browser.close()
    print(f"  PNG 저장 완료: {SAMPLE_PATH}")
    return True


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

    print("=" * 60)
    print("컨셉 #45 Finance Luxury Frame 생성")
    print("Inspired by Robinhood Visual System (One Show 2025 Gold)")
    print("=" * 60)

    print("\n[1/3] 배경 이미지 생성 (Gemini AI)...")
    ok = generate_background()
    if not ok:
        print("  [경고] 배경 생성 실패. 순수 검정 배경으로 대체합니다.")
        # 순수 검정 배경으로 fallback — 여전히 HTML 렌더링은 진행
        BG_PATH.write_bytes(b"")  # placeholder, HTML은 body background-color #0A0A0A로 대체

    print("\n[2/3] HTML 오버레이 렌더링 (Playwright)...")
    if BG_PATH.exists() and BG_PATH.stat().st_size > 0:
        bg_url = f"file://{BG_PATH}"
    else:
        bg_url = ""  # 배경 없이 body 배경색만 사용
    html = HTML_TEMPLATE.replace("__BG_PATH__", bg_url)
    render_html(html)

    print("\n[3/3] 복사본 생성...")
    shutil.copy2(SAMPLE_PATH, COPY_PATH)
    print(f"  복사 완료: {COPY_PATH}")

    print(f"\n완료!")
    print(f"  sample.png : {SAMPLE_PATH}")
    print(f"  named copy : {COPY_PATH}")


if __name__ == "__main__":
    main()
