#!/usr/bin/env python3
"""
#13 CSS Flexbox + 그라디언트 배너 v2 생성기
Gemini 배경 + HTML 오버레이 하이브리드 방식
"""

import base64
import json
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, CTA_MIN_PX, SUBHEAD_MIN_PX

# ── 경로 설정 ──────────────────────────────────────────────────────────────────
TOOL_DIR = Path(__file__).parent
OUTPUT_DIR = WORKSPACE_ROOT / "output/meta-ads/concept-catalog/13-css-gradient"
BG_PATH = TOOL_DIR / "output" / "v4-hybrid" / "bg_13_v2.jpg"
HTML_PATH = TOOL_DIR / "output" / "v4-hybrid" / "overlay_13_v2.html"
FINAL_PATH = OUTPUT_DIR / "sample-v2.png"
COPY_PATH  = OUTPUT_DIR / "13-css-gradient-v2.png"

sys.path.insert(0, str(TOOL_DIR))
import gcloud_auth
_CTA_PX = CTA_MIN_PX
_SIZE_44PX = 44
_SUBHEAD_PX = SUBHEAD_MIN_PX
_SIZE_72PX = 72
_SIZE_88PX = 88
_LH_1_2 = 1.2
_LH_1_15 = 1.15
_LH_1_4 = 1.4

# ── Gemini 배경 프롬프트 ────────────────────────────────────────────────────────
BG_PROMPT = (
    "Dark blue-green gradient abstract background, professional and corporate feel, "
    "deep navy blue (#0a1628) at top-left transitioning to dark teal green (#0d3d3a) at bottom-right, "
    "subtle geometric grid overlay with very faint lines, no text, no people, no logos, "
    "clean minimal texture, high contrast, very dark overall, 1080x1080 square format. "
    "Pure abstract gradient background only."
)

MODEL_ID = "gemini-3-pro-image-preview"
GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
GEMINI_SCOPE = "https://www.googleapis.com/auth/generative-language"


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

    # SA 토큰을 우선 사용 (API Key 쿼터 초과 방지)
    try:
        print("  SA Bearer 토큰 인증 사용")
        token = gcloud_auth.get_service_account_token(GEMINI_SCOPE)
        url = f"{GEMINI_API_BASE}/models/{MODEL_ID}:generateContent"
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }
    except Exception as e:
        api_key = gcloud_auth.get_api_key("GEMINI_API_KEY")
        if api_key:
            print(f"  API Key 인증 fallback 사용")
            url = f"{GEMINI_API_BASE}/models/{MODEL_ID}:generateContent?key={api_key}"
            headers = {"Content-Type": "application/json"}
        else:
            raise RuntimeError(f"인증 실패: {e}")

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

    start = time.time()
    resp = requests.post(url, headers=headers, json=payload, timeout=120)

    if resp.status_code != 200:
        print(f"  [경고] Gemini API 실패 ({resp.status_code}): {resp.text[:300]}")
        print("  → CSS 그라디언트 배경으로 대체합니다.")
        return None

    data = resp.json()
    parts = data.get("candidates", [{}])[0].get("content", {}).get("parts", [])
    image_part = next((p for p in parts if "inlineData" in p), None)

    if not image_part:
        print("  [경고] 이미지 데이터 없음 → CSS 그라디언트 배경 사용")
        return None

    mime_type = image_part["inlineData"].get("mimeType", "image/jpeg")
    image_bytes = base64.b64decode(image_part["inlineData"]["data"])
    BG_PATH.parent.mkdir(parents=True, exist_ok=True)

    ext = ".jpg" if "jpeg" in mime_type else ".png"
    actual_bg = BG_PATH.with_suffix(ext)
    actual_bg.write_bytes(image_bytes)

    elapsed = time.time() - start
    print(f"  배경 생성 완료: {actual_bg.name} ({len(image_bytes):,} bytes, {elapsed:.1f}초)")
    return actual_bg


def build_html(bg_path: Path | None) -> Path:
    """HTML 오버레이 파일을 생성합니다."""
    print("[2/3] HTML 오버레이 생성 중...")

    if bg_path and bg_path.exists():
        bg_css = f"url('file://{bg_path.resolve()}')"
        bg_style = f"background-image: {bg_css}; background-size: cover; background-position: center;"
    else:
        # CSS 그라디언트 폴백
        bg_style = (
            "background: linear-gradient(135deg, #0a1628 0%, #0d2d3a 40%, #0a3d35 70%, #062620 100%);"
        )

    html = f"""<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1080">
<style>
  @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700;800;900&display=swap');

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

  body {{
    width: 1080px;
    height: 1080px;
    overflow: hidden;
    font-family: 'Pretendard', 'Noto Sans KR', 'Apple SD Gothic Neo', sans-serif;
  }}

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

  /* 배경 위에 깊이감 있는 오버레이 */
  .canvas::before {{
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(
      160deg,
      rgba(10,22,40,0.55) 0%,
      rgba(6,20,35,0.45) 50%,
      rgba(5,30,28,0.50) 100%
    );
    z-index: 0;
  }}

  /* 미묘한 그리드 패턴 오버레이 */
  .canvas::after {{
    content: '';
    position: absolute;
    inset: 0;
    background-image:
      linear-gradient(rgba(0,229,160,0.04) 1px, transparent 1px),
      linear-gradient(90deg, rgba(0,229,160,0.04) 1px, transparent 1px);
    background-size: 60px 60px;
    z-index: 0;
  }}

  .content {{
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    padding: 60px 72px 60px 72px;
    height: 100%;
    gap: 0;
  }}

  /* 상단 라벨 */
  .label {{
    font-size: {_SIZE_44PX}px;
    font-weight: 600;
    color: #7EC8E3;
    letter-spacing: 0.05em;
    margin-bottom: 40px;
    line-height: {_LH_1_2};
  }}

  /* 헤드라인 */
  .headline {{
    font-size: {_SIZE_88PX}px;
    font-weight: 800;
    color: #FFFFFF;
    line-height: {_LH_1_15};
    margin-bottom: 40px;
    letter-spacing: -0.02em;
    word-break: keep-all;
  }}

  /* 구분선 */
  .divider {{
    width: 200px;
    height: 2px;
    background: #00E5A0;
    margin-bottom: 40px;
    flex-shrink: 0;
  }}

  /* 혜택 블록 */
  .benefits {{
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-bottom: 40px;
  }}

  .sub-copy {{
    font-size: {_SIZE_72PX}px;
    font-weight: 700;
    color: #00E5A0;
    line-height: {_LH_1_2};
    letter-spacing: -0.02em;
  }}

  .supporting {{
    font-size: {_SUBHEAD_PX}px;
    font-weight: 600;
    color: #FFFFFF;
    line-height: {_LH_1_2};
    letter-spacing: -0.02em;
  }}

  /* 긴급 배지 */
  .urgent-badge {{
    font-size: {_CTA_PX}px;
    font-weight: 600;
    color: #FF3C3C;
    border: 1px solid #FF3C3C;
    background: rgba(255, 60, 60, 0.15);
    border-radius: 6px;
    padding: 8px 20px;
    display: inline-block;
    line-height: {_LH_1_4};
    margin-bottom: 40px;
  }}

  /* CTA 버튼 */
  .cta-btn {{
    font-size: {_SIZE_44PX}px;
    font-weight: 700;
    color: #0a1628;
    background: #00E5A0;
    border-radius: 50px;
    padding: 20px 56px;
    display: inline-block;
    line-height: {_LH_1_2};
    letter-spacing: -0.01em;
    cursor: pointer;
  }}
</style>
</head>
<body>
<div class="canvas">
  <div class="content">
    <!-- 상단 라벨 -->
    <div class="label">T.O.P 사업단</div>

    <!-- 헤드라인 -->
    <div class="headline">월급은 왜<br>제자리걸음?</div>

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

    <!-- 혜택 블록 -->
    <div class="benefits">
      <div class="sub-copy">신입 최대 1,000만원</div>
      <div class="supporting">경력직 직전연봉 50%</div>
    </div>

    <!-- 긴급 배지 -->
    <div class="urgent-badge">정착지원금 2026.7월 변경 예정</div>

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

    HTML_PATH.parent.mkdir(parents=True, exist_ok=True)
    HTML_PATH.write_text(html, encoding="utf-8")
    print(f"  HTML 저장: {HTML_PATH}")
    return HTML_PATH


def capture_image(html_path: Path) -> Path:
    """Playwright로 HTML을 1080x1080 PNG로 캡처합니다."""
    print("[3/3] Playwright 캡처 중...")

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

    with sync_playwright() as p:
        browser = p.chromium.launch(args=["--no-sandbox", "--disable-setuid-sandbox"])
        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(FINAL_PATH), type="png", clip={"x": 0, "y": 0, "width": 1080, "height": 1080})
            print(f"  캡처 완료: {FINAL_PATH}")
        finally:
            browser.close()

    return FINAL_PATH


def main():
    print("=" * 60)
    print("#13 CSS Gradient 배너 v2 생성 시작")
    print(f"출력: {FINAL_PATH}")
    print("=" * 60)

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

    # 2. HTML 오버레이 빌드
    html_path = build_html(bg_path)

    # 3. Playwright 캡처
    result_path = capture_image(html_path)

    # 4. 복사
    shutil.copy2(str(result_path), str(COPY_PATH))
    print(f"\n복사 완료: {COPY_PATH}")

    size_kb = result_path.stat().st_size / 1024
    print(f"\n생성 완료!")
    print(f"  sample-v2.png       : {result_path} ({size_kb:.0f} KB)")
    print(f"  13-css-gradient-v2.png: {COPY_PATH}")
    print("=" * 60)


if __name__ == "__main__":
    main()
