#!/usr/bin/env python3
"""Cell-2 인카다이렉트 × 관리자/조직 비전 배너 생성기.

Gemini API로 임원급 고층 오피스 야경 배경을 생성하고,
HTML/CSS + Playwright로 한글 텍스트를 정밀하게 오버레이합니다.

산출물:
  - /home/jay/workspace/output/banners/cell-2-incar-leader/meta-feed-1080x1080.html
  - /home/jay/workspace/output/banners/cell-2-incar-leader/meta-feed-1080x1080.png
  - /home/jay/workspace/output/banners/cell-2-incar-leader/google-resp-1200x628.html
  - /home/jay/workspace/output/banners/cell-2-incar-leader/google-resp-1200x628.png
"""

from __future__ import annotations

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

import requests
from playwright.sync_api import sync_playwright

# ─── 경로 설정 ────────────────────────────────────────────────────────────────

TOOL_DIR = Path(__file__).parent
sys.path.insert(0, str(TOOL_DIR))

import gcloud_auth  # noqa: E402

OUTPUT_DIR = Path("/home/jay/workspace/output/banners/cell-2-incar-leader")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

# ─── Gemini API 설정 ──────────────────────────────────────────────────────────

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
MODEL_ID = "gemini-2.0-flash-exp"
FALLBACK_MODEL_ID = "gemini-2.5-flash-preview-04-17"

# ─── 배경 프롬프트 ────────────────────────────────────────────────────────────

BG_PROMPT_1080 = (
    "Premium high-rise office interior at night, floor-to-ceiling windows showing "
    "city skyline with warm golden lights, dark elegant workspace, leather executive "
    "chair, warm ambient lighting from desk lamp, professional meeting room atmosphere, "
    "no people, cinematic, ultra-realistic photograph"
)

BG_PROMPT_1200 = (
    "Panoramic view of city skyline at night from executive office, floor-to-ceiling "
    "windows, golden city lights reflecting, dark premium interior visible on left side, "
    "warm desk lamp glow, corporate atmosphere, no people, ultra-realistic photograph, "
    "landscape format"
)

# ─── HTML 템플릿 (1080x1080) ──────────────────────────────────────────────────

HTML_1080 = """<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=1080">
  <style>
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Black.otf') format('opentype'); font-weight: 900; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-ExtraBold.otf') format('opentype'); font-weight: 800; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Bold.otf') format('opentype'); font-weight: 700; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-SemiBold.otf') format('opentype'); font-weight: 600; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Medium.otf') format('opentype'); font-weight: 500; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Regular.otf') format('opentype'); font-weight: 400; }}

    *, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; }}
    html, body {{ width: 1080px; height: 1080px; overflow: hidden; font-family: 'Pretendard', sans-serif; word-break: keep-all; }}

    .canvas {{ position: relative; width: 1080px; height: 1080px; overflow: hidden; }}
    .bg-image {{ position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: center; }}
    .dark-overlay {{ position: absolute; inset: 0; background: rgba(10, 22, 40, 0.58); }}

    /* 중앙 크림 반투명 패널 */
    .text-panel {{
      position: absolute;
      top: 50%; left: 50%;
      transform: translate(-50%, -50%);
      width: 860px;
      padding: 56px 48px;
      background: rgba(255, 248, 231, 0.82);
      border-radius: 12px;
      backdrop-filter: blur(4px);
      box-shadow: 0 8px 32px rgba(0,0,0,0.2);
      display: flex; flex-direction: column;
      align-items: center;
      gap: 24px; text-align: center;
    }}

    .badge {{
      display: inline-block;
      background: #C9A84C; color: #1A0E00;
      font-size: 40px; font-weight: 700;
      height: 52px; padding: 0 24px;
      border-radius: 6px;
      white-space: nowrap;
      letter-spacing: -0.03em;
      line-height: 52px;
    }}

    .headline {{
      font-size: 60px; font-weight: 700;
      color: #3E2723; line-height: 1.25;
      letter-spacing: -1.5px;
      white-space: nowrap;
    }}
    .headline .gold {{ color: #C9A84C; }}

    .gold-divider {{
      width: 100%;
      height: 2px;
      background: linear-gradient(to right, transparent, #C9A84C 20%, #C9A84C 80%, transparent);
      opacity: 0.60;
      flex-shrink: 0;
    }}

    .sub-copy {{
      font-size: 44px; font-weight: 500;
      color: #6B5010;
      white-space: nowrap;
      letter-spacing: -0.02em;
    }}

    .urgency {{
      font-size: 40px; font-weight: 500;
      color: #5C4410;
      letter-spacing: -0.02em;
      white-space: nowrap;
    }}

    .cta-btn {{
      display: inline-block;
      background: linear-gradient(135deg, #C9A84C 0%, #D4B87A 100%);
      color: #1A0E00;
      font-size: 48px; font-weight: 700;
      height: 76px; line-height: 76px;
      padding: 0 40px;
      min-width: 360px;
      width: auto;
      border-radius: 6px;
      box-shadow: 0 6px 24px rgba(201,168,76,0.45);
      white-space: nowrap;
      letter-spacing: -0.03em;
      text-align: center;
    }}
  </style>
</head>
<body>
  <div class="canvas">
    <img class="bg-image" src="{bg_url}" alt="background">
    <div class="dark-overlay"></div>
    <div class="text-panel">
      <span class="badge">인카금융서비스 TOP사업단</span>
      <p class="headline">지점장 이직, 89일이 <span class="gold">골든타임</span></p>
      <div class="gold-divider"></div>
      <p class="sub-copy">본부 5개 | 지점 10개 | 200명+ 조직</p>
      <p class="urgency">사무실 개설비 지원 | 1200% 룰 시행 전 지금</p>
      <div class="cta-btn">지점장 이직 상담받기 →</div>
    </div>
  </div>
</body>
</html>"""

# ─── HTML 템플릿 (1200x628) ───────────────────────────────────────────────────

HTML_1200 = """<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=1200">
  <style>
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Black.otf') format('opentype'); font-weight: 900; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-ExtraBold.otf') format('opentype'); font-weight: 800; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Bold.otf') format('opentype'); font-weight: 700; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-SemiBold.otf') format('opentype'); font-weight: 600; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Medium.otf') format('opentype'); font-weight: 500; }}
    @font-face {{ font-family: 'Pretendard'; src: url('file:///home/jay/.local/share/fonts/Pretendard/Pretendard-Regular.otf') format('opentype'); font-weight: 400; }}

    *, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; }}
    html, body {{ width: 1200px; height: 628px; overflow: hidden; font-family: 'Pretendard', sans-serif; word-break: keep-all; }}

    .canvas {{ position: relative; width: 1200px; height: 628px; overflow: hidden; }}
    .bg-image {{ position: absolute; right: 0; top: 0; width: 65%; height: 100%; object-fit: cover; object-position: center right; }}

    .gradient-overlay {{
      position: absolute; inset: 0;
      background: linear-gradient(
        to right,
        rgba(10,22,40,0.95) 0%,
        rgba(10,22,40,0.95) 40%,
        rgba(10,22,40,0.85) 52%,
        rgba(10,22,40,0.50) 68%,
        rgba(10,22,40,0.15) 82%,
        transparent 100%
      );
    }}

    /* 좌측 골드 세로 액센트바 */
    .accent-bar {{
      position: absolute;
      top: 80px; left: 0;
      width: 4px; height: 460px;
      background: linear-gradient(to bottom, #C9A84C, #D4B87A);
      border-radius: 2px;
    }}

    .text-area {{
      position: absolute;
      top: 0; left: 0;
      width: 62%; height: 100%;
      padding: 48px 56px 48px 60px;
      display: flex; flex-direction: column;
      justify-content: center;
      gap: 20px;
    }}

    .badge {{
      display: inline-block;
      background: #C9A84C; color: #1A0E00;
      font-size: 40px; font-weight: 700;
      height: 48px; line-height: 48px;
      padding: 0 20px;
      border-radius: 6px;
      white-space: nowrap;
      letter-spacing: -0.03em;
      align-self: flex-start;
      margin-bottom: 6px;
    }}

    .headline {{
      font-size: 58px; font-weight: 700;
      color: #FFF8E7; line-height: 1.2;
      letter-spacing: -1.2px;
      white-space: nowrap;
    }}
    .headline .gold {{ color: #C9A84C; }}

    .sub-copy {{
      font-size: 40px; font-weight: 500;
      color: #C9A84C;
      text-shadow: 0 1px 3px rgba(0,0,0,0.5);
      white-space: nowrap;
      letter-spacing: -0.02em;
    }}

    .urgency {{
      font-size: 40px; font-weight: 500;
      color: #C9A84C;
      text-shadow: 0 1px 3px rgba(0,0,0,0.5);
      white-space: nowrap;
      letter-spacing: -0.02em;
    }}

    .cta-btn {{
      display: inline-block;
      background: linear-gradient(135deg, #C9A84C 0%, #D4B87A 100%);
      color: #1A0E00;
      font-size: 44px; font-weight: 700;
      height: 56px; line-height: 56px;
      padding: 0 32px;
      min-width: 220px;
      width: auto;
      border-radius: 6px;
      box-shadow: 0 4px 16px rgba(201,168,76,0.35);
      white-space: nowrap;
      letter-spacing: -0.03em;
      align-self: flex-start;
      text-align: center;
      margin-top: 12px;
    }}
  </style>
</head>
<body>
  <div class="canvas">
    <img class="bg-image" src="{bg_url}" alt="background">
    <div class="gradient-overlay"></div>
    <div class="accent-bar"></div>
    <div class="text-area">
      <span class="badge">인카금융서비스 TOP사업단</span>
      <p class="headline">지점장 이직, 89일이 <span class="gold">골든타임</span></p>
      <p class="sub-copy">본부 5개 | 지점 10개 | 200명+ 조직</p>
      <p class="urgency">사무실 개설비 지원 | 1200% 룰 시행 전 지금</p>
      <div class="cta-btn">지점장 이직 상담받기 →</div>
    </div>
  </div>
</body>
</html>"""


# ─── Gemini 이미지 생성 ───────────────────────────────────────────────────────

def generate_bg_image(token: str, output_path: Path, prompt: str, label: str) -> Path:
    """Gemini API로 배경 이미지를 생성하고 저장합니다."""
    print(f"[배경:{label}] Gemini API 생성 중...")
    start = time.time()

    # imagen-3.0 시도 (고품질 이미지 전용)
    imagen_url = f"{GEMINI_API_BASE}/models/imagen-3.0-generate-002:predict"
    headers_json = {"Content-Type": "application/json"}
    # SA 토큰 인증
    headers_auth = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }
    imagen_payload = {
        "instances": [{"prompt": prompt}],
        "parameters": {
            "sampleCount": 1,
            "aspectRatio": "1:1" if "1080" in label else "16:9",
        }
    }

    # Gemini generateContent 방식
    gemini_url = f"{GEMINI_API_BASE}/models/gemini-2.5-flash-image:generateContent"
    gemini_payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
    }

    response = None
    used_model = ""

    # 우선순위: gemini-2.5-flash-image → gemini-3.1-flash-image-preview → gemini-3-pro-image-preview
    for try_model in ["gemini-2.5-flash-image", "gemini-3.1-flash-image-preview", "gemini-3-pro-image-preview"]:
        try_url = f"{GEMINI_API_BASE}/models/{try_model}:generateContent"
        try:
            print(f"[배경:{label}] {try_model} 시도...")
            response = requests.post(try_url, headers=headers_auth, json=gemini_payload, timeout=300)
            if response.ok:
                used_model = try_model
                break
            else:
                print(f"[배경:{label}] 실패 HTTP {response.status_code}: {response.text[:200]}")
                response = None
        except Exception as e:
            print(f"[배경:{label}] 예외: {e}")
            response = None

    if response is None or not response.ok:
        raise RuntimeError(f"[배경:{label}] 모든 모델 실패")

    print(f"[배경:{label}] 사용 모델: {used_model}")

    data = response.json()
    candidates = data.get("candidates", [])
    if not candidates:
        raise RuntimeError(f"응답에 candidates 없음: {json.dumps(data)[:300]}")

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

    if image_part is None:
        text_parts = [p.get("text", "") for p in parts if "text" in p]
        raise RuntimeError(f"이미지 데이터 없음. 텍스트: {text_parts[:2]}")

    mime_type = image_part["inlineData"].get("mimeType", "image/jpeg")
    image_bytes = base64.b64decode(image_part["inlineData"]["data"])

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

    elapsed = time.time() - start
    print(f"[배경:{label}] 완료: {final_path.name} ({len(image_bytes):,} bytes, {elapsed:.1f}초)")
    return final_path


# ─── Playwright HTML → PNG 캡처 ───────────────────────────────────────────────

def capture_html_to_png(
    html_content: str,
    bg_path: Path,
    html_output_path: Path,
    png_output_path: Path,
    width: int,
    height: int,
) -> None:
    """HTML 템플릿에 배경 이미지 URL을 삽입하고 Playwright로 PNG 캡처합니다."""
    bg_url = f"file://{bg_path.resolve()}"
    html_filled = html_content.format(bg_url=bg_url)

    # HTML 파일 저장 (산출물)
    html_output_path.write_text(html_filled, encoding="utf-8")
    print(f"[HTML] 저장: {html_output_path}")

    print(f"[캡처] Playwright로 {width}x{height} 캡처 중...")
    with sync_playwright() as p:
        browser = p.chromium.launch(args=["--no-sandbox", "--disable-gpu"])
        try:
            page = browser.new_page(viewport={"width": width, "height": height})
            page.goto(f"file://{html_output_path.resolve()}", wait_until="networkidle")
            # 폰트 로딩 대기
            page.wait_for_timeout(2500)
            page.screenshot(path=str(png_output_path), type="png", clip={
                "x": 0, "y": 0, "width": width, "height": height
            })
            print(f"[캡처] 저장 완료: {png_output_path}")
        finally:
            browser.close()


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

def main() -> None:
    print("=" * 60)
    print("Cell-2 인카다이렉트 × 관리자/조직 비전 배너 생성 시작")
    print("=" * 60)

    # 1. 인증 토큰 획득
    print("\n[인증] SA 토큰 획득 중...")
    try:
        token = gcloud_auth.get_access_token()
        print(f"[인증] 토큰 획득 성공 (길이: {len(token)} chars)")
    except Exception as e:
        print(f"[인증] 실패: {e}")
        raise SystemExit(1) from e

    # 2. 배경 이미지 생성: 1080x1080
    print("\n[배경] 1080x1080 배경 이미지 생성 중...")
    bg_path_1080_base = OUTPUT_DIR / "bg-cell2-1080"
    try:
        bg_path_1080 = generate_bg_image(token, bg_path_1080_base, BG_PROMPT_1080, "1080")
    except Exception as e:
        print(f"[배경:1080] 생성 실패: {e}")
        raise SystemExit(1) from e

    # 3. 배경 이미지 생성: 1200x628
    print("\n[배경] 1200x628 배경 이미지 생성 중...")
    bg_path_1200_base = OUTPUT_DIR / "bg-cell2-1200"
    try:
        bg_path_1200 = generate_bg_image(token, bg_path_1200_base, BG_PROMPT_1200, "1200")
    except Exception as e:
        print(f"[배경:1200] 생성 실패: {e}")
        raise SystemExit(1) from e

    # 4. 배너 1: meta-feed-1080x1080
    print("\n[배너 1] meta-feed-1080x1080 생성 중...")
    html_1080 = OUTPUT_DIR / "meta-feed-1080x1080.html"
    png_1080 = OUTPUT_DIR / "meta-feed-1080x1080.png"
    try:
        capture_html_to_png(
            html_content=HTML_1080,
            bg_path=bg_path_1080,
            html_output_path=html_1080,
            png_output_path=png_1080,
            width=1080,
            height=1080,
        )
        size_kb = png_1080.stat().st_size / 1024
        print(f"[배너 1] 완료: {png_1080} ({size_kb:.0f} KB)")
    except Exception as e:
        print(f"[배너 1] 실패: {e}")
        import traceback; traceback.print_exc()

    # 5. 배너 2: google-resp-1200x628
    print("\n[배너 2] google-resp-1200x628 생성 중...")
    html_1200 = OUTPUT_DIR / "google-resp-1200x628.html"
    png_1200 = OUTPUT_DIR / "google-resp-1200x628.png"
    try:
        capture_html_to_png(
            html_content=HTML_1200,
            bg_path=bg_path_1200,
            html_output_path=html_1200,
            png_output_path=png_1200,
            width=1200,
            height=628,
        )
        size_kb = png_1200.stat().st_size / 1024
        print(f"[배너 2] 완료: {png_1200} ({size_kb:.0f} KB)")
    except Exception as e:
        print(f"[배너 2] 실패: {e}")
        import traceback; traceback.print_exc()

    print("\n" + "=" * 60)
    print("Cell-2 배너 생성 완료")
    print(f"  배경 1080: {bg_path_1080}")
    print(f"  배경 1200: {bg_path_1200}")
    print(f"  배너 1 HTML: {html_1080}")
    print(f"  배너 1 PNG:  {png_1080}")
    print(f"  배너 2 HTML: {html_1200}")
    print(f"  배너 2 PNG:  {png_1200}")
    print("=" * 60)


if __name__ == "__main__":
    main()
