"""컨셉 #41 당신 같은 사람 (Unedited Reality Portrait) 하이브리드 이미지 생성.

Gemini 생성 인물 이미지를 폴라로이드 프레임에 배치하고
HTML/CSS 텍스트 오버레이를 Playwright로 합성합니다.
"""

from __future__ import annotations

import shutil
from pathlib import Path

from playwright.sync_api import sync_playwright

# ──────────────────────────────────────────────────────────
# 경로 설정
# ──────────────────────────────────────────────────────────
OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/concept-catalog/41-cannes-unedited-reality")
BG_IMAGE = OUTPUT_DIR / "person-background.jpg"
SAMPLE_OUTPUT = OUTPUT_DIR / "sample.png"
CATALOG_OUTPUT = Path("/home/jay/workspace/output/meta-ads/concept-catalog/41-cannes-unedited-reality.png")

FONT_DIR = Path.home() / ".local/share/fonts/Pretendard"

# ──────────────────────────────────────────────────────────
# HTML 템플릿
# ──────────────────────────────────────────────────────────
def build_html(bg_image_path: str) -> str:
    """폴라로이드 프레임 + 텍스트 오버레이 HTML 생성."""
    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Black.otf') format('opentype');
    font-weight: 900;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-ExtraBold.otf') format('opentype');
    font-weight: 800;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-SemiBold.otf') format('opentype');
    font-weight: 600;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Medium.otf') format('opentype');
    font-weight: 500;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: url('file://{FONT_DIR}/Pretendard-Regular.otf') format('opentype');
    font-weight: 400;
  }}

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

  body {{
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background: #F5F0E8;
  }}

  .canvas {{
    width: 1080px;
    height: 1080px;
    position: relative;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    background: #F5F0E8;
  }}

  /* 상단 로고 영역 */
  .brand-top {{
    position: absolute;
    top: 48px;
    left: 72px;
    font-size: 40px;
    font-weight: 600;
    color: #1C1C1C;
    letter-spacing: -0.5px;
  }}

  .brand-right {{
    position: absolute;
    top: 48px;
    right: 72px;
    font-size: 40px;
    font-weight: 400;
    color: #8A8A8A;
  }}

  /* 폴라로이드 프레임 */
  .polaroid-frame {{
    position: absolute;
    top: 116px;
    left: 130px;
    width: 820px;
    height: 560px;
    background: #FFFFFF;
    padding: 18px;
    padding-bottom: 64px;
    box-shadow: 0 6px 30px rgba(0,0,0,0.20), 0 2px 8px rgba(0,0,0,0.12);
    border-radius: 4px;
    transform: rotate(-0.4deg);
  }}

  /* 이미지 영역 */
  .photo-area {{
    width: 100%;
    height: 440px;
    background: #D4CFC5;
    border-radius: 2px;
    overflow: hidden;
    position: relative;
  }}

  .photo-area img {{
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center top;
  }}

  /* 폴라로이드 캡션 */
  .polaroid-caption {{
    margin-top: 12px;
    text-align: center;
    font-size: 42px;
    font-weight: 500;
    color: #5A5A5A;
    line-height: 1.3;
    white-space: nowrap;
  }}

  .polaroid-caption .highlight {{
    color: #C8102E;
    font-weight: 700;
  }}

  /* 핵심 메시지 */
  .main-headline {{
    position: absolute;
    top: 716px;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 90px;
    font-weight: 800;
    color: #1C1C1C;
    letter-spacing: -2px;
    line-height: 1.05;
  }}

  /* 보조 메시지 */
  .sub-message {{
    position: absolute;
    top: 844px;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 46px;
    font-weight: 600;
    color: #5A5A5A;
    letter-spacing: -0.5px;
  }}

  /* CTA 버튼 */
  .cta-wrapper {{
    position: absolute;
    top: 942px;
    left: 0;
    right: 0;
    text-align: center;
  }}

  .cta-btn {{
    display: inline-block;
    font-size: 44px;
    font-weight: 700;
    color: #FFFFFF;
    background: #1C1C1C;
    padding: 14px 48px;
    border-radius: 4px;
    letter-spacing: -0.5px;
  }}

  /* 폴라로이드 세부 텍스처 (약간의 노이즈감) */
  .polaroid-frame::after {{
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    background: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' opacity='0.03'/%3E%3C/svg%3E");
    pointer-events: none;
    border-radius: 4px;
    opacity: 0.3;
  }}
</style>
</head>
<body>
<div class="canvas">

  <!-- 브랜드 상단 -->
  <div class="brand-top">T.O.P 사업단</div>
  <div class="brand-right">인카금융서비스</div>

  <!-- 폴라로이드 프레임 -->
  <div class="polaroid-frame">
    <div class="photo-area">
      <img src="file://{bg_image_path}" alt="FA 인물 사진" />
    </div>
    <div class="polaroid-caption">
      이분이 지난달 <span class="highlight">1,200만</span>원 번 FA입니다
    </div>
  </div>

  <!-- 핵심 메시지 -->
  <div class="main-headline">당신도 될 수 있습니다.</div>

  <!-- 보조 메시지 -->
  <div class="sub-message">정착지원금으로 안정적 시작</div>

  <!-- CTA -->
  <div class="cta-wrapper">
    <span class="cta-btn">지금 상담 신청하기 →</span>
  </div>

</div>
</body>
</html>"""


def main() -> None:
    if not BG_IMAGE.exists():
        raise FileNotFoundError(f"배경 이미지 없음: {BG_IMAGE}")

    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    html_content = build_html(str(BG_IMAGE.resolve()))
    html_path = OUTPUT_DIR / "_concept41_template.html"
    html_path.write_text(html_content, encoding="utf-8")
    print(f"HTML 템플릿 저장: {html_path}")

    print("Playwright로 합성 중...")
    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.resolve()}", wait_until="networkidle")
            # 폰트 렌더링 대기
            page.wait_for_timeout(2000)
            page.screenshot(path=str(SAMPLE_OUTPUT), type="png")
        finally:
            browser.close()

    size = SAMPLE_OUTPUT.stat().st_size
    print(f"sample.png 저장 완료: {SAMPLE_OUTPUT} ({size:,} bytes)")

    # 복사본 저장
    shutil.copy2(SAMPLE_OUTPUT, CATALOG_OUTPUT)
    print(f"카탈로그 복사본 저장: {CATALOG_OUTPUT}")


if __name__ == "__main__":
    main()
