#!/usr/bin/env python3
"""컨셉 #47 K.R Award Emotional Finance — T.O.P 리크루팅 Meta 광고.

Samsung Fire '보험 선물하기', Hanwha 감성 콜라보 캠페인 레퍼런스.
따뜻한 Warm Beige 배경 + Deep Blue 타이포그래피.
Gemini AI 배경 + HTML/CSS 텍스트 오버레이 하이브리드 파이프라인.
"""

from __future__ import annotations

import base64
import shutil
import sys
from pathlib import Path

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

sys.path.insert(0, str(Path(__file__).parent))
import gcloud_auth
_SIZE_28PX = 28
_SIZE_36PX = 36
_CTA_PX = CTA_MIN_PX
_SIZE_42PX = 42
_SIZE_46PX = 46
_SUBHEAD_PX = SUBHEAD_MIN_PX
_SIZE_88PX = 88
_LH_1_18 = 1.18
_LH_1_25 = 1.25
_LH_1_4 = 1.4

# ── 경로 설정 ──────────────────────────────────────────────────────────────
OUTPUT_DIR = WORKSPACE_ROOT / "output/meta-ads/concept-catalog/47-kr-award-emotional-finance"
BG_PATH = OUTPUT_DIR / "bg.jpg"
SAMPLE_PATH = OUTPUT_DIR / "sample.png"
COPY_PATH = OUTPUT_DIR / "47-kr-award-emotional-finance.png"

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

# ── 배경 이미지 프롬프트 ────────────────────────────────────────────────────
# 따뜻한 감성 금융 광고 배경: 한 쌍의 손이 따뜻하게 맞잡힌 부드러운 분위기
BG_PROMPT = (
    "Warm lifestyle photography, soft focus, cinematic mood. "
    "Two hands gently clasped together in a supportive handshake — one hand older, "
    "one younger — symbolizing mentorship and trust. "
    "Warm beige and cream tones dominate: soft natural window light from the left, "
    "blurred bokeh background in warm ivory and pale gold. "
    "The hands are centered in the lower half of the frame, upper half is beautiful "
    "warm-toned soft bokeh light. "
    "Color palette: warm cream #F5E6D3, soft gold, pale ivory, warm white. "
    "No text, no watermarks, no logos. "
    "Shot on Canon EOS R5 with 85mm f/1.4 lens, editorial lifestyle photography. "
    "Emotional warmth, human connection, trust and care. "
    "Square 1:1 format, 1080x1080."
)

# ── HTML 오버레이 템플릿 ────────────────────────────────────────────────────
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="ko">
<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: #F5E6D3;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}

  .canvas {{
    position: relative;
    width: 1080px;
    height: 1080px;
    overflow: hidden;
  }}

  /* ── 배경 이미지 ── */
  .bg-image {{
    position: absolute;
    inset: 0;
    background-image: url('{bg_url}');
    background-size: cover;
    background-position: center bottom;
  }}

  /* ── 부드러운 따뜻한 오버레이 그라디언트 ── */
  .warm-overlay {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to bottom,
      rgba(245, 230, 211, 0.92) 0%,
      rgba(245, 230, 211, 0.88) 38%,
      rgba(245, 230, 211, 0.60) 58%,
      rgba(245, 230, 211, 0.82) 78%,
      rgba(245, 230, 211, 0.96) 100%
    );
  }}

  /* ── 상단 브랜드 태그 ── */
  .brand-tag {{
    position: absolute;
    top: 56px;
    left: 0;
    right: 0;
    text-align: center;
    font-size: {_SIZE_36PX}px;
    font-weight: 700;
    color: #E8836A;
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }}

  /* ── 상단 장식 라인 ── */
  .top-accent-line {{
    position: absolute;
    top: 108px;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 4px;
    background: #E8836A;
    border-radius: 2px;
  }}

  /* ── 메인 헤드라인 블록 ── */
  .headline-block {{
    position: absolute;
    top: 140px;
    left: 80px;
    right: 80px;
    text-align: center;
  }}

  .headline-main {{
    font-size: {_SIZE_88PX}px;
    font-weight: 800;
    color: #003D82;
    line-height: {_LH_1_18};
    letter-spacing: -0.03em;
    word-break: keep-all;
  }}

  .headline-main .em {{
    color: #E8836A;
  }}

  /* ── 구분선 ── */
  .divider {{
    position: absolute;
    top: 424px;
    left: 50%;
    transform: translateX(-50%);
    width: 480px;
    height: 2px;
    background: linear-gradient(
      to right,
      transparent,
      #003D82 20%,
      #003D82 80%,
      transparent
    );
    opacity: 0.35;
  }}

  /* ── 서브 헤드라인 ── */
  .sub-headline {{
    position: absolute;
    top: 450px;
    left: 80px;
    right: 80px;
    text-align: center;
    font-size: {_SUBHEAD_PX}px;
    font-weight: 700;
    color: #003D82;
    line-height: {_LH_1_25};
    letter-spacing: -0.02em;
    word-break: keep-all;
  }}

  /* ── 바디 카피 ── */
  .body-copy {{
    position: absolute;
    top: 576px;
    left: 80px;
    right: 80px;
    text-align: center;
    font-size: {_SIZE_42PX}px;
    font-weight: 500;
    color: #5C4A35;
    letter-spacing: -0.01em;
    line-height: {_LH_1_4};
    word-break: keep-all;
  }}

  .body-copy .highlight-amount {{
    font-weight: 800;
    color: #003D82;
  }}

  /* ── 하단 카드 영역 (이미지 위) ── */
  .bottom-card {{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 400px;
  }}

  /* ── 따뜻한 손 이미지 (배경 하단 포커스) ── */

  /* ── 지원금 배지 ── */
  .support-badge {{
    position: absolute;
    top: 650px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0, 61, 130, 0.08);
    border: 2px solid rgba(0, 61, 130, 0.20);
    border-radius: 50px;
    padding: 16px 48px;
    white-space: nowrap;
    text-align: center;
  }}

  .support-badge-text {{
    font-size: {_CTA_PX}px;
    font-weight: 600;
    color: #5C4A35;
    letter-spacing: -0.01em;
  }}

  .support-badge-text .badge-em {{
    font-weight: 800;
    color: #003D82;
  }}

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

  .cta-btn {{
    display: inline-block;
    background: #003D82;
    color: #FFFFFF;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_46PX}px;
    font-weight: 700;
    letter-spacing: -0.01em;
    padding: 22px 72px;
    border-radius: 60px;
    box-shadow: 0 8px 32px rgba(0, 61, 130, 0.30);
  }}

  /* ── 하단 소인 ── */
  .footer-note {{
    position: absolute;
    bottom: 44px;
    left: 0;
    right: 0;
    text-align: center;
    font-size: {_SIZE_28PX}px;
    font-weight: 400;
    color: #A08870;
    letter-spacing: 0.01em;
  }}

  /* ── 장식 원형 요소 ── */
  .deco-circle-1 {{
    position: absolute;
    top: -80px;
    right: -80px;
    width: 320px;
    height: 320px;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(232, 131, 106, 0.12) 0%, transparent 70%);
  }}

  .deco-circle-2 {{
    position: absolute;
    bottom: 200px;
    left: -60px;
    width: 240px;
    height: 240px;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(0, 61, 130, 0.08) 0%, transparent 70%);
  }}

  /* ── 스파클 도트 ── */
  .sparkle {{
    position: absolute;
    border-radius: 50%;
  }}
  .sparkle-1 {{
    top: 128px;
    left: 120px;
    width: 10px;
    height: 10px;
    background: #E8836A;
    opacity: 0.6;
  }}
  .sparkle-2 {{
    top: 152px;
    right: 140px;
    width: 7px;
    height: 7px;
    background: #003D82;
    opacity: 0.4;
  }}
  .sparkle-3 {{
    top: 420px;
    left: 160px;
    width: 8px;
    height: 8px;
    background: #E8836A;
    opacity: 0.5;
  }}
  .sparkle-4 {{
    top: 430px;
    right: 180px;
    width: 6px;
    height: 6px;
    background: #003D82;
    opacity: 0.35;
  }}

</style>
</head>
<body>
<div class="canvas">

  <!-- 배경 이미지 -->
  <div class="bg-image"></div>

  <!-- 따뜻한 오버레이 -->
  <div class="warm-overlay"></div>

  <!-- 장식 원형 -->
  <div class="deco-circle-1"></div>
  <div class="deco-circle-2"></div>

  <!-- 스파클 도트 -->
  <div class="sparkle sparkle-1"></div>
  <div class="sparkle sparkle-2"></div>
  <div class="sparkle sparkle-3"></div>
  <div class="sparkle sparkle-4"></div>

  <!-- 브랜드 태그 -->
  <div class="brand-tag">T.O.P 사업단</div>

  <!-- 상단 강조 라인 -->
  <div class="top-accent-line"></div>

  <!-- 메인 헤드라인 -->
  <div class="headline-block">
    <div class="headline-main">
      열심히는 하는데,<br>
      소득은 <span class="em">제자리걸음?</span>
    </div>
  </div>

  <!-- 구분선 -->
  <div class="divider"></div>

  <!-- 서브 헤드라인 -->
  <div class="sub-headline">당신의 성장에 힘이 돼줄게요</div>

  <!-- 바디 카피 -->
  <div class="body-copy">
    T.O.P 사업단 &nbsp;|&nbsp; 정착지원금 최대 <span class="highlight-amount">1,000만원</span>
  </div>

  <!-- 지원금 배지 -->
  <div class="support-badge">
    <span class="support-badge-text">
      FA 전환 후 <span class="badge-em">월 평균 수입 2배↑</span>
    </span>
  </div>

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

  <!-- 하단 소인 -->
  <div class="footer-note">인카금융서비스 T.O.P 사업단 · 금융위 등록 보험설계사</div>

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


def generate_background() -> bool:
    """Gemini AI로 따뜻한 감성 배경 이미지를 생성합니다."""
    try:
        sa_token = gcloud_auth.get_service_account_token(
            "https://www.googleapis.com/auth/generative-language"
        )
    except RuntimeError as e:
        print(f"  [오류] SA 토큰 획득 실패: {e}")
        return False

    headers = {
        "Authorization": f"Bearer {sa_token}",
        "Content-Type": "application/json",
    }

    models_to_try = [
        "gemini-2.5-flash-image",
        "gemini-3.1-flash-image-preview",
        "gemini-3-pro-image-preview",
        "imagen-4.0-generate-001",
        "imagen-4.0-fast-generate-001",
    ]

    for model in models_to_try:
        url = f"{GEMINI_API_BASE}/models/{model}:generateContent"
        payload = {
            "contents": [{"parts": [{"text": BG_PROMPT}]}],
            "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]},
        }

        # imagen 모델은 다른 엔드포인트/페이로드 구조 사용
        if model.startswith("imagen"):
            url = f"{GEMINI_API_BASE}/models/{model}:predict"
            payload = {
                "instances": [{"prompt": BG_PROMPT}],
                "parameters": {"sampleCount": 1, "aspectRatio": "1:1"},
            }

        print(f"  배경 생성 요청 중... (모델: {model})")
        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=120)
        except Exception as e:
            print(f"  [오류] 연결 실패: {e}")
            continue

        if resp.status_code == 200:
            data = resp.json()

            # generateContent 응답 파싱
            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

            # imagen predict 응답 파싱
            for pred in data.get("predictions", []):
                if "bytesBase64Encoded" in pred:
                    img_bytes = base64.b64decode(pred["bytesBase64Encoded"])
                    BG_PATH.write_bytes(img_bytes)
                    print(f"  배경 저장 완료 (imagen): {BG_PATH} ({len(img_bytes):,} bytes)")
                    return True

            reason = (
                data.get("candidates", [{}])[0].get("finishReason", "?")
            )
            print(f"  [오류] 이미지 파트 없음 (finishReason: {reason})")
            print(f"  응답 미리보기: {str(data)[:400]}")
        else:
            print(f"  [HTTP {resp.status_code}] {resp.text[:300]}")

    return False


def render_html(bg_url: str) -> None:
    """HTML 오버레이를 Playwright로 PNG 캡처합니다."""
    html_content = HTML_TEMPLATE.format(
        font_dir=str(FONT_DIR),
        bg_url=bg_url,
    )
    html_file = OUTPUT_DIR / "_concept47_template.html"
    html_file.write_text(html_content, encoding="utf-8")
    print(f"  HTML 템플릿 저장: {html_file}")

    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            page.goto(f"file://{html_file.resolve()}", wait_until="networkidle")
            # 폰트 로딩 완전 대기
            page.wait_for_timeout(2500)
            page.screenshot(path=str(SAMPLE_PATH), type="png")
        finally:
            browser.close()

    size = SAMPLE_PATH.stat().st_size
    print(f"  PNG 저장 완료: {SAMPLE_PATH} ({size:,} bytes)")


def main() -> None:
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    print("=" * 64)
    print("컨셉 #47 K.R Award Emotional Finance")
    print("T.O.P 리크루팅 Meta 광고 — 감정 기반 금융 광고")
    print("Inspired by Samsung Fire '보험 선물하기' campaign")
    print("=" * 64)

    print("\n[1/3] 배경 이미지 생성 (Gemini AI)...")
    ok = generate_background()
    if not ok:
        print("  [경고] AI 배경 생성 실패. 순수 Warm Beige CSS 배경으로 대체합니다.")
        bg_url = ""
    else:
        bg_url = f"file://{BG_PATH.resolve()}"

    print("\n[2/3] HTML 오버레이 렌더링 (Playwright)...")
    render_html(bg_url)

    print("\n[3/3] 복사본 생성...")
    shutil.copy2(SAMPLE_PATH, COPY_PATH)
    print(f"  복사 완료: {COPY_PATH}")

    print(f"\n완료!")
    print(f"  sample.png  : {SAMPLE_PATH}")
    print(f"  named copy  : {COPY_PATH}")
    sz = SAMPLE_PATH.stat().st_size / 1024
    print(f"  파일 크기   : {sz:.0f} KB")


if __name__ == "__main__":
    main()
