#!/usr/bin/env python3
"""컨셉 #28 W Concept Style — 에디토리얼 미니멀 이미지 생성"""

import base64
import sys
import time
from pathlib import Path

import requests
from playwright.sync_api import sync_playwright
from gen_config import WORKSPACE_ROOT, CTA_MIN_PX, HEAD_SUB_RATIO, SUBHEAD_MIN_PX

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth
_CTA_PX = CTA_MIN_PX
_SUBHEAD_PX = SUBHEAD_MIN_PX
_SIZE_88PX = 88
_LH_1_15 = 1.15
_LH_RATIO = HEAD_SUB_RATIO

# ── 경로 설정 ──────────────────────────────────────────────────────────────
OUTPUT_DIR = WORKSPACE_ROOT / "output/meta-ads/concept-catalog/28-wconcept-style"
BG_PATH = OUTPUT_DIR / "bg.jpg"
SAMPLE_PATH = OUTPUT_DIR / "sample.png"

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

BG_PROMPT = (
    "Abstract minimalist empty background, very light warm cream white color, "
    "extremely clean with subtle paper grain texture, soft ambient lighting, "
    "no objects, no text, no people, "
    "high-end editorial aesthetic, 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', 'Noto Serif KR', sans-serif;
    background-color: #F5F5F3;
  }
  .container {
    position: relative;
    width: 1080px;
    height: 1080px;
    background-image: url('__BG_PATH__');
    background-size: cover;
    background-position: center;
  }

  /* 좌측 세로 텍스트 (RECRUITING 2026) — writing-mode 방식으로 변경 */
  .vertical-label {
    position: absolute;
    left: 28px;
    top: 50%;
    transform: translateY(-50%);
    writing-mode: vertical-rl;
    text-orientation: mixed;
    transform: translateY(-50%) rotate(180deg);
    font-size: {_CTA_PX}px;
    font-weight: 300;
    color: #8C8C8C;
    letter-spacing: 0.22em;
    text-transform: uppercase;
    white-space: nowrap;
  }

  /* 좌측 세로 장식선 */
  .left-line {
    position: absolute;
    left: 90px;
    top: 100px;
    bottom: 100px;
    width: 1px;
    background: linear-gradient(to bottom, transparent, #C8C8C8 20%, #C8C8C8 80%, transparent);
  }

  /* 우측 콘텐츠 영역 */
  .content-area {
    position: absolute;
    left: 120px;
    right: 64px;
    bottom: 90px;
  }

  /* 상단 구분자 작은 텍스트 */
  .eyebrow {
    font-size: {_CTA_PX}px;
    font-weight: 300;
    color: #8C8C8C;
    letter-spacing: 0.18em;
    text-transform: uppercase;
    margin-bottom: 32px;
  }

  /* 메인 헤드라인 — 세리프 느낌 (Noto Serif KR 또는 Noto Sans KR Light) */
  .headline {
    font-size: {_SIZE_88PX}px;
    font-weight: 200;
    color: #1C1C1C;
    line-height: {_LH_1_15};
    letter-spacing: -0.025em;
    margin-bottom: 36px;
    font-family: 'Noto Serif KR', 'Pretendard', serif;
  }

  /* 얇은 구분선 */
  .divider {
    width: 56px;
    height: 1px;
    background: #1C1C1C;
    margin-bottom: 32px;
  }

  /* 보조 텍스트 */
  .sub-text {
    font-size: {_SUBHEAD_PX}px;
    font-weight: 100;
    color: #8C8C8C;
    line-height: {_LH_RATIO};
    letter-spacing: -0.01em;
    margin-bottom: 44px;
  }

  /* CTA — 버건디 밑줄 링크 스타일 */
  .cta {
    font-size: {_CTA_PX}px;
    font-weight: 400;
    color: #8B1A2F;
    letter-spacing: 0.04em;
    border-bottom: 1.5px solid #8B1A2F;
    display: inline-block;
    padding-bottom: 4px;
  }

  /* 우상단 작은 에디토리얼 넘버 */
  .issue-number {
    position: absolute;
    top: 60px;
    right: 64px;
    font-size: {_CTA_PX}px;
    font-weight: 200;
    color: #C0C0C0;
    letter-spacing: 0.08em;
  }

  /* 좌상단 브랜드 마크 */
  .brand-mark {
    position: absolute;
    top: 60px;
    left: 120px;
    font-size: {_CTA_PX}px;
    font-weight: 800;
    color: #0A0A0A;
    letter-spacing: 0.12em;
    text-transform: uppercase;
  }
</style>
</head>
<body>
<div class="container">
  <div class="left-line"></div>
  <div class="vertical-label">Recruiting 2026</div>
  <div class="brand-mark">CAREER</div>
  <div class="issue-number">No. 28</div>
  <div class="content-area">
    <div class="eyebrow">Editorial</div>
    <div class="headline">열심히는 하는데,<br>월급은 제자리걸음?</div>
    <div class="divider"></div>
    <div class="sub-text">당신의 커리어,<br>다시 디자인하세요</div>
    <div class="cta">확인하기 →</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"}
    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}")
            return True
    print("  [오류] 이미지 파트 없음")
    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()
