#!/usr/bin/env python3
"""
컨셉 #32 삼성화재 스타일 하이브리드 이미지 생성기
Gemini AI 배경 + HTML 텍스트 오버레이 → 최종 합성 이미지
"""

from __future__ import annotations

import base64
import shutil
import sys
import time
from pathlib import Path

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

# ─── 경로 설정 ───────────────────────────────────────────────────────────────
SCRIPT_DIR = Path(__file__).parent
OUTPUT_DIR = WORKSPACE_ROOT / "output/meta-ads/concept-catalog/32-samsungfire-style"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

BG_PATH = OUTPUT_DIR / "bg_gemini.jpg"
TEMPLATE_PATH = OUTPUT_DIR / "template.html"
SAMPLE_PATH = OUTPUT_DIR / "sample.png"
FINAL_PATH = OUTPUT_DIR / "32-samsungfire-style.png"

# ─── Gemini 배경 생성 ─────────────────────────────────────────────────────────
GEMINI_PROMPT = (
    "Clean minimal office environment background, bright natural daylight through large windows, "
    "soft spring morning atmosphere, white desks and workstations with subtle blue accents, "
    "professional Korean corporate office interior, upper floor city view partially visible, "
    "abstract upward growth chart elements subtly integrated into environment, "
    "color palette: predominantly white and very pale sky blue (#EAF6FB tones), "
    "no people, no text, no faces, photorealistic high quality, 1080x1080 pixels, "
    "clean modern Korean corporate aesthetic, hopeful and premium atmosphere"
)

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
MODEL_ID = "gemini-3-pro-image-preview"
FALLBACK_MODEL_ID = "gemini-3.1-flash-image-preview"

sys.path.insert(0, str(SCRIPT_DIR))
import gcloud_auth  # noqa: E402
_CTA_PX = CTA_MIN_PX
_SIZE_44PX = 44
_SUBHEAD_PX = SUBHEAD_MIN_PX
_METRIC_PX = CORE_METRIC_MIN_PX
_SIZE_120PX = 120
_LH_1 = 1
_LH_1_2 = 1.2
_LH_1_1 = 1.1
_LH_RATIO = HEAD_SUB_RATIO


def generate_background() -> Path:
    """Gemini API로 배경 이미지를 생성합니다. SA 토큰 우선 사용."""
    print("[1/3] Gemini 배경 이미지 생성 중...")

    # SA 토큰 사용 (rate limit 없는 서비스 계정)
    token = gcloud_auth.get_service_account_token()
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}",
    }

    payload = {
        "contents": [
            {
                "parts": [
                    {"text": GEMINI_PROMPT}
                ]
            }
        ],
        "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
    }

    for model in [MODEL_ID, FALLBACK_MODEL_ID]:
        url = f"{GEMINI_API_BASE}/models/{model}:generateContent"
        print(f"  모델 시도: {model}")
        for attempt in range(2):
            try:
                resp = requests.post(url, headers=headers, json=payload, timeout=120)
                if resp.status_code == 200:
                    data = resp.json()
                    candidates = data.get("candidates", [])
                    if candidates:
                        parts = candidates[0].get("content", {}).get("parts", [])
                        for part in parts:
                            if "inlineData" in part:
                                img_data = base64.b64decode(part["inlineData"]["data"])
                                BG_PATH.write_bytes(img_data)
                                print(f"  배경 이미지 저장: {BG_PATH} ({len(img_data):,} bytes)")
                                return BG_PATH
                    print(f"  응답 구조 이상: {list(data.keys())}")
                else:
                    print(f"  API 오류 {resp.status_code}: {resp.text[:200]}")
            except Exception as e:
                print(f"  시도 {attempt+1} 실패: {e}")
            if attempt < 1:
                time.sleep(3)

    raise RuntimeError("Gemini 배경 생성 실패")


# ─── HTML 템플릿 생성 ──────────────────────────────────────────────────────────

def build_html_template(bg_path: Path) -> Path:
    """HTML 텍스트 오버레이 템플릿을 생성합니다."""
    print("[2/3] HTML 텍스트 오버레이 템플릿 생성 중...")

    bg_uri = bg_path.as_uri()

    html = f"""<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1080">
<title>컨셉 #32 삼성화재 스타일</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
  @font-face {{
    font-family: 'Pretendard';
    src: local('Pretendard-Black'),
         url('/home/jay/.local/share/fonts/Pretendard/Pretendard-Black.otf') format('opentype');
    font-weight: 900;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: local('Pretendard-ExtraBold'),
         url('/home/jay/.local/share/fonts/Pretendard/Pretendard-ExtraBold.otf') format('opentype');
    font-weight: 800;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: local('Pretendard-Bold'),
         url('/home/jay/.local/share/fonts/Pretendard/Pretendard-Bold.otf') format('opentype');
    font-weight: 700;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: local('Pretendard-SemiBold'),
         url('/home/jay/.local/share/fonts/Pretendard/Pretendard-SemiBold.otf') format('opentype');
    font-weight: 600;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: local('Pretendard-Medium'),
         url('/home/jay/.local/share/fonts/Pretendard/Pretendard-Medium.otf') format('opentype');
    font-weight: 500;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: local('Pretendard-Regular'),
         url('/home/jay/.local/share/fonts/Pretendard/Pretendard-Regular.otf') format('opentype');
    font-weight: 400;
    font-style: normal;
  }}
  @font-face {{
    font-family: 'Pretendard';
    src: local('Pretendard-Light'),
         url('/home/jay/.local/share/fonts/Pretendard/Pretendard-Light.otf') format('opentype');
    font-weight: 300;
    font-style: normal;
  }}

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

  body {{
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    background: #EAF6FB;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
  }}

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

  /* 배경 이미지 레이어 */
  .bg-image {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1080px;
    height: 1080px;
    background-image: url('{bg_uri}');
    background-size: cover;
    background-position: center;
  }}

  /* 반투명 오버레이 — 텍스트 가독성 확보 */
  .bg-overlay {{
    position: absolute;
    top: 0;
    left: 0;
    width: 1080px;
    height: 1080px;
    background: rgba(234, 246, 251, 0.78);
  }}

  /* ── 상단 악센트 라인 ── */
  .accent-line-top {{
    position: absolute;
    top: 108px;
    left: 0;
    width: 1080px;
    height: 3px;
    background: #5BC2E7;
  }}

  /* ── 상단 바 ── */
  .top-bar {{
    position: absolute;
    top: 60px;
    left: 72px;
    right: 72px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }}

  .top-left {{
    font-size: {_CTA_PX}px;
    font-weight: 400;
    color: #003CDC;
    letter-spacing: 0.08em;
    line-height: {_LH_1};
  }}

  .top-right {{
    font-size: {_CTA_PX}px;
    font-weight: 400;
    color: #003CDC;
    letter-spacing: 0.03em;
    line-height: {_LH_1};
    text-align: right;
  }}

  /* ── 메인 헤드라인 블록 ── */
  .headline-block {{
    position: absolute;
    top: 148px;
    left: 72px;
    right: 72px;
  }}

  .headline-line1 {{
    font-size: {_METRIC_PX}px;
    font-weight: 800;
    color: #003CDC;
    letter-spacing: -0.01em;
    line-height: {_LH_1}.2;
    margin-bottom: 4px;
  }}

  .headline-number {{
    font-size: {_SIZE_120PX}px;
    font-weight: 900;
    color: #003CDC;
    letter-spacing: -0.02em;
    line-height: {_LH_1}.1;
    margin-bottom: 0px;
  }}

  .headline-line3 {{
    font-size: {_METRIC_PX}px;
    font-weight: 800;
    color: #003CDC;
    letter-spacing: -0.01em;
    line-height: {_LH_1}.2;
  }}

  /* ── 중간 악센트 바 ── */
  .accent-bar-mid {{
    position: absolute;
    top: 610px;
    left: 72px;
    width: 260px;
    height: 5px;
    background: #5BC2E7;
    border-radius: 3px;
  }}

  /* ── 서브 헤드라인 ── */
  .sub-headline {{
    position: absolute;
    top: 636px;
    left: 72px;
    right: 72px;
    font-size: {_SUBHEAD_PX}px;
    font-weight: 600;
    color: #003CDC;
    letter-spacing: -0.005em;
    line-height: {_LH_1}.3;
  }}

  /* ── 배지 행 ── */
  .badge-row {{
    position: absolute;
    top: 730px;
    left: 72px;
    right: 72px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
  }}

  .badge {{
    background: #5BC2E7;
    color: #FFFFFF;
    font-size: {_CTA_PX}px;
    font-weight: 700;
    padding: 14px 32px;
    border-radius: 24px;
    display: inline-block;
    letter-spacing: 0.02em;
    line-height: {_LH_1};
    white-space: nowrap;
  }}

  /* ── CTA 버튼 ── */
  .cta-wrapper {{
    position: absolute;
    top: 840px;
    left: 72px;
  }}

  .cta-button {{
    background: #5BC2E7;
    color: #003CDC;
    font-family: 'Pretendard', 'Noto Sans KR', sans-serif;
    font-size: {_SIZE_44PX}px;
    font-weight: 700;
    padding: 22px 64px;
    border-radius: 30px;
    border: none;
    letter-spacing: 0.04em;
    display: inline-block;
    line-height: {_LH_1};
    white-space: nowrap;
  }}

  /* ── 하단 악센트 라인 ── */
  .accent-line-bottom {{
    position: absolute;
    top: 1000px;
    left: 0;
    width: 1080px;
    height: 3px;
    background: #5BC2E7;
  }}

  /* ── 하단 푸터 텍스트 ── */
  .footer-text {{
    position: absolute;
    top: 1022px;
    left: 72px;
    right: 72px;
    font-size: {_CTA_PX}px;
    font-weight: 300;
    color: rgba(0, 61, 220, 0.70);
    letter-spacing: 0.03em;
    line-height: {_LH_1}.3;
    white-space: nowrap;
  }}
</style>
</head>
<body>
<div class="canvas">

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

  <!-- 반투명 오버레이 -->
  <div class="bg-overlay"></div>

  <!-- 상단 악센트 라인 -->
  <div class="accent-line-top"></div>

  <!-- 상단 바: T.O.P 사업단 / #1 성장 조직 -->
  <div class="top-bar">
    <div class="top-left">T.O.P 사업단</div>
    <div class="top-right">#1 성장 조직 · 코스닥 상장 인카금융</div>
  </div>

  <!-- 메인 헤드라인 블록 -->
  <div class="headline-block">
    <div class="headline-line1">당신이 머무르는 동안,</div>
    <div class="headline-number">매출 1,863%</div>
    <div class="headline-line3">성장했습니다</div>
  </div>

  <!-- 중간 악센트 바 -->
  <div class="accent-bar-mid"></div>

  <!-- 서브 헤드라인 -->
  <div class="sub-headline">판을 바꾸는 전략, T.O.P 사업단</div>

  <!-- 배지 행 -->
  <div class="badge-row">
    <span class="badge">482명 → 5,500명 성장</span>
    <span class="badge">신입 최대 1,000만원</span>
  </div>

  <!-- CTA 버튼 -->
  <div class="cta-wrapper">
    <div class="cta-button">지금 지원하기 →</div>
  </div>

  <!-- 하단 악센트 라인 -->
  <div class="accent-line-bottom"></div>

  <!-- 하단 푸터 텍스트 -->
  <div class="footer-text">상위 1%의 영업 로직을 배우다 · 대체 불가능한 전문가</div>

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

    TEMPLATE_PATH.write_text(html, encoding="utf-8")
    print(f"  HTML 템플릿 저장: {TEMPLATE_PATH}")
    return TEMPLATE_PATH


# ─── Playwright 캡처 ──────────────────────────────────────────────────────────

def capture_composite(template_path: Path) -> Path:
    """Playwright로 HTML을 렌더링하여 최종 합성 이미지를 캡처합니다."""
    print("[3/3] Playwright로 최종 이미지 캡처 중...")

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage"],
        )
        context = browser.new_context(
            viewport={"width": 1080, "height": 1080},
            device_scale_factor=1,
        )
        page = context.new_page()

        # HTML 파일 로드
        page.goto(f"file://{template_path}", wait_until="networkidle", timeout=30000)

        # 폰트 로딩 대기
        page.evaluate("() => document.fonts.ready")
        page.wait_for_timeout(2000)  # 추가 렌더링 대기

        # 스크린샷 캡처
        page.screenshot(
            path=str(SAMPLE_PATH),
            clip={"x": 0, "y": 0, "width": 1080, "height": 1080},
            type="png",
        )

        browser.close()

    print(f"  최종 이미지 저장: {SAMPLE_PATH}")
    return SAMPLE_PATH


# ─── 메인 ─────────────────────────────────────────────────────────────────────

def main():
    print("=" * 60)
    print("컨셉 #32 삼성화재 스타일 하이브리드 이미지 생성")
    print("=" * 60)

    start = time.time()

    # 1. Gemini 배경 생성
    bg_path = generate_background()

    # 2. HTML 템플릿 생성
    template_path = build_html_template(bg_path)

    # 3. Playwright 캡처
    sample_path = capture_composite(template_path)

    # 4. 두 번째 경로에 복사
    shutil.copy2(sample_path, FINAL_PATH)
    print(f"  복사 완료: {FINAL_PATH}")

    elapsed = time.time() - start
    print(f"\n완료! 소요 시간: {elapsed:.1f}초")
    print(f"  sample.png  → {SAMPLE_PATH}")
    print(f"  32-samsungfire-style.png → {FINAL_PATH}")
    print(f"  template.html → {template_path}")


if __name__ == "__main__":
    main()
