#!/usr/bin/env python3
"""컨셉 #29 Chanel Style — 럭셔리 절제 이미지 생성"""

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

# ── 경로 설정 ──────────────────────────────────────────────────────────────
OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/concept-catalog/29-chanel-style")
BG_PATH = OUTPUT_DIR / "bg.jpg"
SAMPLE_PATH = OUTPUT_DIR / "sample.png"

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

BG_PROMPT = (
    "Pure white minimalist background, extremely clean and empty, "
    "subtle warm light gradient from top center creating soft glow, "
    "luxury fashion editorial aesthetic, no texture, no objects, "
    "vast negative space, no text, no people, square format"
)

HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    background-color: #FFFFFF;
  }
  .container {
    position: relative;
    width: 1080px;
    height: 1080px;
    background-image: url('__BG_PATH__');
    background-size: cover;
    background-position: center;
  }

  /* 극단적 여백: 상 40% : 콘텐츠 20% : 하 40% */
  .center-block {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 840px;
    text-align: center;
  }

  /* 핵심 헤드라인 — Noto Serif KR / Playfair Display 느낌 */
  .headline {
    font-size: 84px;
    font-weight: 200;
    color: #0D0D0D;
    line-height: 1.25;
    letter-spacing: -0.02em;
    font-family: 'Noto Serif KR', 'Pretendard', serif;
    margin-bottom: 52px;
  }

  /* 0.5px 수평선 */
  .divider {
    width: 100%;
    height: 0.5px;
    background: #0D0D0D;
    margin-bottom: 52px;
  }

  /* 보조 — 골드 올캡스 넓은 letter-spacing */
  .sub-text {
    font-size: 64px;
    font-weight: 200;
    color: #C9A84C;
    letter-spacing: 0.18em;
    text-transform: uppercase;
    line-height: 1.3;
    margin-bottom: 72px;
  }

  /* CTA — 블랙 올캡스, 넓은 letter-spacing */
  .cta {
    font-size: 40px;
    font-weight: 300;
    color: #0D0D0D;
    letter-spacing: 0.4em;
    text-transform: uppercase;
    display: inline-block;
    border-bottom: 0.5px solid #0D0D0D;
    padding-bottom: 6px;
  }

  /* 상단 브랜드 워터마크 */
  .top-mark {
    position: absolute;
    top: 56px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 40px;
    font-weight: 200;
    color: #BFBFBF;
    letter-spacing: 0.35em;
    text-transform: uppercase;
    white-space: nowrap;
  }

  /* 하단 미세 텍스트 */
  .bottom-note {
    position: absolute;
    bottom: 52px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 40px;
    font-weight: 200;
    color: #C0C0C0;
    letter-spacing: 0.2em;
    text-transform: uppercase;
    white-space: nowrap;
  }

  /* 좌측 세로 골드 장식선 */
  .gold-line-left {
    position: absolute;
    left: 72px;
    top: 200px;
    bottom: 200px;
    width: 0.5px;
    background: linear-gradient(to bottom, transparent, #C9A84C 30%, #C9A84C 70%, transparent);
  }

  /* 우측 세로 골드 장식선 */
  .gold-line-right {
    position: absolute;
    right: 72px;
    top: 200px;
    bottom: 200px;
    width: 0.5px;
    background: linear-gradient(to bottom, transparent, #C9A84C 30%, #C9A84C 70%, transparent);
  }
</style>
</head>
<body>
<div class="container">
  <div class="top-mark">Prestige Career</div>
  <div class="gold-line-left"></div>
  <div class="gold-line-right"></div>
  <div class="center-block">
    <div class="headline">열심히는 하는데,<br>월급은 제자리걸음?</div>
    <div class="divider"></div>
    <div class="sub-text">당신의 가치는 다릅니다</div>
    <div class="cta">확인하기</div>
  </div>
  <div class="bottom-note">2026 · Career Design</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"}
    url = f"{GEMINI_API_BASE}/models/gemini-3.1-flash-image-preview:generateContent"
    payload = {
        "contents": [{"parts": [{"text": BG_PROMPT}]}],
        "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]},
    }
    print("  배경 생성 요청 중...")
    resp = requests.post(url, headers=headers, json=payload, timeout=120)
    if resp.status_code != 200:
        print(f"  [오류] {resp.status_code}: {resp.text[:300]}")
        return False
    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})")
    return False


def render_html(html_content: str) -> bool:
    """Playwright로 HTML을 PNG로 캡처합니다."""
    html_file = OUTPUT_DIR / "overlay.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(1500)
        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("[1/2] 배경 이미지 생성...")
    ok = generate_background()
    if not ok:
        sys.exit(1)

    print("[2/2] HTML 오버레이 렌더링...")
    bg_url = f"file://{BG_PATH}"
    html = HTML_TEMPLATE.replace("__BG_PATH__", bg_url)
    render_html(html)
    print(f"\n완료: {SAMPLE_PATH}")


if __name__ == "__main__":
    main()
