#!/usr/bin/env python3
"""컨셉 #30 — 아르티장 오렌지 (Hermès Style) 이미지 생성."""

import base64
import sys
import time
from pathlib import Path

import requests

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth

OUTPUT_PATH = Path("/home/jay/workspace/output/meta-ads/concept-catalog/30-hermes-style/sample.png")
HTML_PATH = Path("/tmp/concept30_overlay.html")

BG_PROMPT = (
    "Warm ivory artisan background, delicate hand-drawn style orange line art illustration "
    "on the right side showing abstract flowing ribbon and elegant curves, fine paper texture, "
    "warm ambient lighting, Hermès-inspired artistic aesthetic, no text, no words, no letters, "
    "analog illustration quality, 1080x1080 square format"
)

HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=1080"/>
  <title>Concept 30 - Hermes Style</title>
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,600;1,300;1,400;1,600;1,700&family=Noto+Serif+KR:wght@300;400;600&display=swap');

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

    html, body {{
      width: 1080px;
      height: 1080px;
      overflow: hidden;
      -webkit-font-smoothing: antialiased;
    }}

    body {{
      position: relative;
      background: #FAF3E8;
    }}

    #bg-layer {{
      position: absolute;
      inset: 0;
      z-index: 0;
      background-image: url('{bg_url}');
      background-size: cover;
      background-position: center center;
      background-repeat: no-repeat;
    }}

    /* 좌측 아이보리 반투명 패널 */
    .left-panel {{
      position: absolute;
      top: 0;
      left: 0;
      width: 580px;
      height: 1080px;
      z-index: 2;
      background: linear-gradient(
        90deg,
        rgba(250, 243, 232, 0.96) 0%,
        rgba(250, 243, 232, 0.85) 80%,
        rgba(250, 243, 232, 0) 100%
      );
    }}

    /* 텍스트 영역 */
    .text-zone {{
      position: absolute;
      top: 0;
      left: 0;
      width: 540px;
      height: 1080px;
      z-index: 3;
      padding: 100px 60px 80px 72px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
    }}

    /* 장식 라인 */
    .deco-line {{
      width: 48px;
      height: 2px;
      background-color: #E8611A;
      margin-bottom: 36px;
    }}

    /* 핵심 메시지 */
    .headline {{
      font-family: 'Cormorant Garamond', 'Noto Serif KR', 'Nanum Myeongjo', serif;
      font-size: 84px;
      font-weight: 600;
      font-style: italic;
      line-height: 1.18;
      color: #2C1810;
      letter-spacing: -0.02em;
      white-space: pre-line;
      margin-bottom: 44px;
    }}

    /* 서브 카피 */
    .subtext {{
      font-family: 'Cormorant Garamond', 'Noto Serif KR', serif;
      font-size: 64px;
      font-weight: 300;
      font-style: normal;
      line-height: 1.25;
      color: #A0784A;
      letter-spacing: -0.01em;
      margin-bottom: auto;
    }}

    /* 하단 장식선 */
    .bottom-deco {{
      width: 100%;
      height: 1px;
      background: linear-gradient(90deg, #A0784A, transparent);
      margin-bottom: 32px;
    }}

    /* CTA */
    .cta {{
      font-family: 'Cormorant Garamond', 'Noto Serif KR', serif;
      font-size: 40px;
      font-weight: 400;
      color: #2C1810;
      text-decoration: underline;
      text-underline-offset: 6px;
      text-decoration-color: #E8611A;
      letter-spacing: 0.02em;
    }}

    /* 우측 하단 브랜드 태그 */
    .brand-tag {{
      position: absolute;
      bottom: 48px;
      right: 60px;
      z-index: 4;
      font-family: 'Cormorant Garamond', serif;
      font-size: 24px;
      font-weight: 300;
      letter-spacing: 0.18em;
      color: #A0784A;
      text-transform: uppercase;
    }}
  </style>
</head>
<body>
  <div id="bg-layer"></div>
  <div class="left-panel"></div>
  <div class="text-zone">
    <div class="deco-line"></div>
    <div class="headline">열심히는 하는데,&#10;월급은 제자리걸음?</div>
    <div class="subtext">당신의 노력에 맞는&#10;무대가 필요합니다</div>
    <div class="bottom-deco"></div>
    <div class="cta">확인하기 →</div>
  </div>
  <div class="brand-tag">Career · Growth</div>
</body>
</html>"""


def generate_bg_image(token: str, prompt: str) -> bytes:
    """Gemini API로 배경 이미지 생성."""
    model_ids = [
        "gemini-3-pro-image-preview",
        "gemini-3.1-flash-image-preview",
        "gemini-2.5-flash-image",
    ]
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }
    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
    }

    last_err = None
    for model_id in model_ids:
        url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_id}:generateContent"
        print(f"  [Gemini] 배경 이미지 생성 중 (모델: {model_id})...")
        start = time.time()
        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=300)
            if resp.status_code in (403, 404):
                print(f"  [Gemini] {resp.status_code} — 다음 모델 시도...")
                last_err = resp.status_code
                continue
            resp.raise_for_status()
            elapsed = time.time() - start
            print(f"  [Gemini] 완료 ({elapsed:.1f}초)")
            break
        except Exception as e:
            last_err = e
            print(f"  [Gemini] 오류: {e} — 다음 모델 시도...")
            continue
    else:
        raise RuntimeError(f"모든 모델 실패. 마지막 오류: {last_err}")

    data = resp.json()
    candidates = data.get("candidates", [])
    if not candidates:
        raise RuntimeError(f"No candidates: {str(data)[:300]}")

    for part in candidates[0].get("content", {}).get("parts", []):
        if "inlineData" in part:
            return base64.b64decode(part["inlineData"]["data"])

    raise RuntimeError("이미지 데이터가 응답에 없습니다.")


def render_html_to_png(bg_bytes: bytes, html_template: str, output_path: Path) -> None:
    """HTML + Playwright로 최종 PNG 생성."""
    from playwright.sync_api import sync_playwright

    # 배경 이미지를 data URI로 변환
    import base64 as b64
    bg_b64 = b64.b64encode(bg_bytes).decode()
    bg_data_url = f"data:image/jpeg;base64,{bg_b64}"

    html_content = html_template.format(bg_url=bg_data_url)
    HTML_PATH.write_text(html_content, encoding="utf-8")
    print(f"  [HTML] 템플릿 저장: {HTML_PATH}")

    output_path.parent.mkdir(parents=True, exist_ok=True)

    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            page.goto(f"file://{HTML_PATH}", wait_until="networkidle")
            page.wait_for_timeout(2000)
            page.screenshot(path=str(output_path), type="png")
            print(f"  [PNG] 저장 완료: {output_path}")
        finally:
            browser.close()


def main():
    print("=== 컨셉 #30 아르티장 오렌지 (Hermès Style) 생성 시작 ===")

    print("\n[1/3] Gemini 인증 토큰 획득...")
    token = gcloud_auth.get_service_account_token(
        "https://www.googleapis.com/auth/generative-language"
    )
    print(f"  토큰 획득 성공 (길이: {len(token)}자)")

    print("\n[2/3] 배경 이미지 생성...")
    bg_bytes = generate_bg_image(token, BG_PROMPT)
    print(f"  배경 이미지 크기: {len(bg_bytes):,} bytes")

    print("\n[3/3] HTML 오버레이 합성 및 PNG 저장...")
    render_html_to_png(bg_bytes, HTML_TEMPLATE, OUTPUT_PATH)

    size_kb = OUTPUT_PATH.stat().st_size / 1024
    print(f"\n=== 완료: {OUTPUT_PATH} ({size_kb:.0f} KB) ===")


if __name__ == "__main__":
    main()
