#!/usr/bin/env python3
"""컨셉 #27 Kia Style — 대담한 에너지 이미지 생성"""

import base64
import json
import sys
import time
from pathlib import Path

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

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth
_SIZE_22PX = 22
_SIZE_44PX = 44
_SUBHEAD_PX = SUBHEAD_MIN_PX
_SIZE_104PX = 104
_LH_RATIO = HEAD_SUB_RATIO
_LH_1_1 = 1.1

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

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

BG_PROMPT = (
    "Dynamic diagonal split composition background, "
    "bottom-left area dark charcoal #1A1A1A, top-right area vivid red #BB162B, "
    "sharp diagonal edge at 15-degree angle cutting across the frame from bottom-left to top-right, "
    "subtle motion blur texture suggesting speed and energy, "
    "high energy bold graphic design style, "
    "no text, no people, no logos, 1080x1080 square"
)

HTML_TEMPLATE = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @import url('file://{FONT_DIR}/PretendardVariable.ttf');
  * {{ margin: 0; padding: 0; box-sizing: border-box; }}
  body {{
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}
  .container {{
    position: relative;
    width: 1080px;
    height: 1080px;
    background-image: url('__BG_PATH__');
    background-size: cover;
    background-position: center;
  }}
  /* 대각선 오버레이 강화 — 좌하단 어두운 반투명 레이어 */
  .diagonal-overlay {{
    position: absolute;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: linear-gradient(
      135deg,
      rgba(26,26,26,0.55) 0%,
      rgba(26,26,26,0.45) 45%,
      rgba(187,22,43,0.0) 55%,
      rgba(187,22,43,0.0) 100%
    );
  }}
  /* 텍스트 그룹 */
  .text-group {{
    position: absolute;
    left: 64px;
    bottom: 180px;
    max-width: 720px;
  }}
  .sub-text {{
    font-size: {_SUBHEAD_PX}px;
    font-weight: 400;
    color: rgba(255,255,255,0.88);
    line-height: {_LH_RATIO};
    margin-bottom: 20px;
    letter-spacing: -0.02em;
  }}
  .headline {{
    font-size: {_SIZE_104PX}px;
    font-weight: 900;
    color: #FFFFFF;
    line-height: {_LH_1_1};
    letter-spacing: -0.03em;
    margin-bottom: 48px;
    /* 사선 경계를 가로지르는 느낌 — 약간 우측으로 넘침 */
    position: relative;
    left: -4px;
  }}
  /* CTA 버튼 */
  .cta-wrapper {{
    position: absolute;
    left: 64px;
    bottom: 72px;
  }}
  .cta-btn {{
    display: inline-block;
    background-color: #C8E600;
    color: #000000;
    font-size: {_SIZE_44PX}px;
    font-weight: 800;
    padding: 18px 52px;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    clip-path: polygon(0 0, calc(100% - 16px) 0, 100% 100%, 16px 100%);
  }}
  /* 액센트 라임 사선 장식 */
  .accent-line {{
    position: absolute;
    top: 0; right: 0;
    width: 8px;
    height: 100%;
    background: #C8E600;
    opacity: 0.85;
  }}
  /* 우상단 레드 영역 강조 텍스처 */
  .top-right-accent {{
    position: absolute;
    top: 40px;
    right: 56px;
    font-size: {_SIZE_22PX}px;
    font-weight: 700;
    color: rgba(255,255,255,0.35);
    letter-spacing: 0.25em;
    text-transform: uppercase;
    writing-mode: vertical-rl;
    text-orientation: mixed;
  }}
</style>
</head>
<body>
<div class="container">
  <div class="diagonal-overlay"></div>
  <div class="text-group">
    <div class="sub-text">열심히는 하는데, 결과가 없다면</div>
    <div class="headline">월급 제자리걸음?<br>이제 판을 바꿔!</div>
  </div>
  <div class="cta-wrapper">
    <div class="cta-btn">지금 바꿔 →</div>
  </div>
  <div class="accent-line"></div>
  <div class="top-right-accent">CHANGE NOW</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()
