#!/usr/bin/env python3
"""컨셉 #06 다크 프리미엄 - 배경 생성 + HTML 오버레이 합성"""

import base64
import os
import sys
from pathlib import Path

import requests

# ─── 경로 설정 ───────────────────────────────────────────────────────────────
OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/concept-catalog/06-dark-premium")
BG_PATH = OUTPUT_DIR / "bg.png"
TEMPLATE_PATH = OUTPUT_DIR / "template.html"
FINAL_PATH = OUTPUT_DIR / "sample.png"

# ─── API 설정 ──────────────────────────────────────────────────────────────────
GEMINI_API_KEY = None

def get_api_key():
    """GEMINI_API_KEY 로드"""
    # 1. 환경변수
    key = os.environ.get("GEMINI_API_KEY")
    if key:
        return key
    # 2. .env 파일
    env_path = Path("/home/jay/workspace/.env")
    if env_path.exists():
        for line in env_path.read_text().splitlines():
            if line.startswith("GEMINI_API_KEY="):
                return line.split("=", 1)[1].strip().strip('"')
    return None


# ─── STEP 1: Gemini로 배경 이미지 생성 ─────────────────────────────────────────
def generate_background(api_key: str) -> bool:
    """Gemini API로 배경 이미지 생성"""
    print("[Step 1] Gemini API로 배경 이미지 생성 중...")

    prompt = (
        "Ultra premium dark navy financial background. "
        "Deep midnight blue gradient from very dark navy #0A1628 at edges to slightly lighter #1a1a2e at center. "
        "Extremely subtle tiny gold dust particles scattered throughout, barely visible. "
        "Abstract geometric thin gold hairline lines in lower third only — very faint diagonal grid pattern. "
        "Luxury financial institution aesthetic. "
        "No text, no numbers, no logos, no faces, no objects, no charts. "
        "Pure abstract dark background. "
        "Extremely refined and sophisticated. "
        "Slight vignette darkening at all four corners. "
        "1080x1080 square format. "
        "Photorealistic ultra high quality render."
    )

    # 이미지 생성 지원 모델 시도 순서
    models_to_try = [
        "gemini-2.5-flash-image",
        "gemini-3-pro-image-preview",
        "gemini-3.1-flash-image-preview",
    ]

    url = f"https://generativelanguage.googleapis.com/v1beta/models/{models_to_try[0]}:generateContent?key={api_key}"
    print(f"  모델: {models_to_try[0]}")

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

    resp = None
    for model_id in models_to_try:
        try_url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_id}:generateContent?key={api_key}"
        print(f"  시도 중: {model_id}")
        try:
            resp = requests.post(try_url, json=payload, timeout=120)
            if resp.status_code in (403, 404):
                print(f"  -> {resp.status_code} 접근 불가, 다음 모델 시도...")
                continue
            resp.raise_for_status()
            print(f"  -> 성공: {model_id}")
            break
        except requests.HTTPError:
            continue
        except Exception as e:
            print(f"  -> 오류: {e}")
            continue

    if resp is None or resp.status_code != 200:
        print(f"[오류] 모든 모델 실패")
        return False

    data = resp.json()
    candidates = data.get("candidates", [])
    if not candidates:
        print(f"[오류] candidates 없음: {data}")
        return False

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

    if not image_part:
        text_parts = [p.get("text", "") for p in parts if "text" in p]
        print(f"[오류] 이미지 파트 없음. 텍스트: {text_parts}")
        return False

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

    # mime type에 따라 확장자 결정
    if "png" in mime_type:
        save_path = BG_PATH
    else:
        save_path = OUTPUT_DIR / "bg.jpg"

    save_path.write_bytes(img_bytes)
    print(f"[완료] 배경 저장: {save_path} ({len(img_bytes):,} bytes, {mime_type})")
    return True


# ─── STEP 2: HTML 템플릿 생성 ──────────────────────────────────────────────────
def create_html_template(bg_path: Path) -> None:
    """HTML 오버레이 템플릿 생성"""
    print("[Step 2] HTML 오버레이 템플릿 생성 중...")

    bg_url = f"file://{bg_path.resolve()}"

    html = f"""<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1080">
<title>컨셉 #06 다크 프리미엄</title>
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable.min.css">
<style>
  * {{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }}

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

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

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

  /* 배경 위 그라디언트 오버레이 - 가독성 향상 */
  .bg-overlay {{
    position: absolute;
    inset: 0;
    background: linear-gradient(
      135deg,
      rgba(10, 22, 40, 0.82) 0%,
      rgba(10, 22, 40, 0.65) 50%,
      rgba(26, 26, 46, 0.55) 100%
    );
  }}

  /* 메인 콘텐츠 컨테이너 */
  .content {{
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
    padding: 72px 80px 64px 80px;
  }}

  /* ── 상단 영역 (15%) ── */
  .section-top {{
    height: 162px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    gap: 16px;
  }}

  .top-line {{
    width: 48px;
    height: 1px;
    background: #D4A855;
  }}

  .brand-label {{
    font-size: 13px;
    font-weight: 500;
    letter-spacing: 0.35em;
    color: #D4A855;
    text-transform: uppercase;
  }}

  /* ── 중상단 영역 (38%) ── */
  .section-mid-top {{
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 18px;
    padding-top: 8px;
  }}

  .sub-tag {{
    font-size: 15px;
    font-weight: 500;
    letter-spacing: 0.22em;
    color: #D4A855;
    text-transform: uppercase;
  }}

  .headline {{
    display: flex;
    flex-direction: column;
    gap: 6px;
  }}

  .headline-line {{
    font-size: 46px;
    font-weight: 700;
    line-height: 1.2;
    color: #F0F4F8;
    letter-spacing: -0.01em;
  }}

  .divider-line {{
    width: 100%;
    height: 1px;
    background: rgba(212, 168, 85, 0.25);
    margin: 6px 0;
  }}

  .emphasis-block {{
    display: flex;
    flex-direction: column;
    gap: 6px;
  }}

  .emphasis-number {{
    font-size: 64px;
    font-weight: 800;
    line-height: 1.0;
    color: #D4A855;
    letter-spacing: -0.02em;
  }}

  .emphasis-desc {{
    font-size: 15px;
    font-weight: 400;
    color: #8899AA;
    letter-spacing: 0.05em;
  }}

  /* ── 중하단 영역 (30%) - 데이터 바 ── */
  .section-data {{
    height: 220px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 28px;
  }}

  .data-section-label {{
    font-size: 11px;
    font-weight: 500;
    letter-spacing: 0.25em;
    color: rgba(136, 153, 170, 0.6);
    text-transform: uppercase;
    margin-bottom: -8px;
  }}

  .bar-item {{
    display: flex;
    flex-direction: column;
    gap: 10px;
  }}

  .bar-header {{
    display: flex;
    justify-content: space-between;
    align-items: baseline;
  }}

  .bar-label {{
    font-size: 14px;
    font-weight: 500;
    color: #8899AA;
    letter-spacing: 0.02em;
  }}

  .bar-value {{
    font-size: 18px;
    font-weight: 700;
    color: #D4A855;
    letter-spacing: 0.01em;
  }}

  .bar-track {{
    width: 100%;
    height: 8px;
    background: rgba(212, 168, 85, 0.12);
    border-radius: 4px;
    overflow: hidden;
  }}

  .bar-fill-1 {{
    height: 100%;
    width: 80%;
    background: linear-gradient(to right, #B5965A, #D4A855);
    border-radius: 4px;
  }}

  .bar-fill-2 {{
    height: 100%;
    width: 90%;
    background: linear-gradient(to right, #B5965A, #D4A855, #E8C070);
    border-radius: 4px;
  }}

  /* ── 하단 영역 (17%) ── */
  .section-bottom {{
    height: 130px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    gap: 20px;
  }}

  .cta-divider {{
    width: 100%;
    height: 1px;
    background: rgba(212, 168, 85, 0.2);
  }}

  .cta-row {{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }}

  .cta-button {{
    display: inline-flex;
    align-items: center;
    padding: 14px 44px;
    border: 1px solid #D4A855;
    border-radius: 2px;
    font-size: 15px;
    font-weight: 600;
    letter-spacing: 0.12em;
    color: #D4A855;
    background: transparent;
    text-decoration: none;
    cursor: pointer;
  }}

  .cta-arrow {{
    margin-left: 10px;
    font-size: 13px;
    opacity: 0.7;
  }}

  .footnote {{
    font-size: 11px;
    font-weight: 400;
    color: rgba(136, 153, 170, 0.65);
    letter-spacing: 0.04em;
    line-height: 1.5;
  }}

</style>
</head>
<body>
<div class="canvas">
  <!-- 배경 이미지 -->
  <div class="bg"></div>
  <!-- 오버레이 -->
  <div class="bg-overlay"></div>

  <!-- 메인 콘텐츠 -->
  <div class="content">

    <!-- 상단: 브랜드 아이덴티티 -->
    <div class="section-top">
      <div class="top-line"></div>
      <div class="brand-label">T.O.P &nbsp;사업단</div>
    </div>

    <!-- 중상단: 헤드라인 + 강조 수치 -->
    <div class="section-mid-top">
      <div class="sub-tag">경력직 정착지원금</div>

      <div class="headline">
        <div class="headline-line">당신의 경력이 드디어</div>
        <div class="headline-line">제대로 평가받습니다</div>
      </div>

      <div class="divider-line"></div>

      <div class="emphasis-block">
        <div class="emphasis-number">직전연봉 50%</div>
        <div class="emphasis-desc">경력직 정착지원금 지원 한도</div>
      </div>
    </div>

    <!-- 중하단: 데이터 시각화 바 -->
    <div class="section-data">
      <div class="data-section-label">지원금 비교</div>

      <!-- Bar 1: 신입 -->
      <div class="bar-item">
        <div class="bar-header">
          <span class="bar-label">신입 정착지원금</span>
          <span class="bar-value">최대 1,000만원</span>
        </div>
        <div class="bar-track">
          <div class="bar-fill-1"></div>
        </div>
      </div>

      <!-- Bar 2: 경력직 -->
      <div class="bar-item">
        <div class="bar-header">
          <span class="bar-label">경력직 정착지원금</span>
          <span class="bar-value">직전연봉 50%</span>
        </div>
        <div class="bar-track">
          <div class="bar-fill-2"></div>
        </div>
      </div>
    </div>

    <!-- 하단: CTA -->
    <div class="section-bottom">
      <div class="cta-divider"></div>
      <div class="cta-row">
        <div class="cta-button">
          지금 상담 신청하기
          <span class="cta-arrow">→</span>
        </div>
      </div>
      <div class="footnote">
        ⚠ 2026.7월 조건 변경 예정 &nbsp;|&nbsp; 코스닥 상장사 인카금융서비스
      </div>
    </div>

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

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


# ─── STEP 3: Playwright로 최종 합성 ────────────────────────────────────────────
def capture_final() -> bool:
    """Playwright로 HTML을 PNG로 캡처"""
    print("[Step 3] Playwright로 최종 이미지 캡처 중...")

    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        print("[오류] playwright가 설치되어 있지 않습니다.")
        return False

    template_url = f"file://{TEMPLATE_PATH.resolve()}"

    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(args=["--no-sandbox", "--disable-setuid-sandbox"])
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            page.goto(template_url, wait_until="networkidle", timeout=15000)
            # 폰트 로딩 대기
            page.wait_for_timeout(2500)
            page.screenshot(path=str(FINAL_PATH), type="png", clip={"x": 0, "y": 0, "width": 1080, "height": 1080})
            browser.close()

        size_kb = FINAL_PATH.stat().st_size / 1024
        print(f"[완료] 최종 이미지 저장: {FINAL_PATH} ({size_kb:.0f} KB)")
        return True

    except Exception as e:
        print(f"[오류] Playwright 캡처 실패: {e}")
        return False


# ─── MAIN ─────────────────────────────────────────────────────────────────────
def main():
    print("=" * 60)
    print("컨셉 #06 다크 프리미엄 생성 시작")
    print("=" * 60)

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

    # API 키 로드
    api_key = get_api_key()
    if not api_key:
        print("[오류] GEMINI_API_KEY를 찾을 수 없습니다.")
        sys.exit(1)
    print(f"[인증] API 키 로드 완료 (길이: {len(api_key)} chars)")

    # Step 1: 배경 생성
    bg_ok = generate_background(api_key)

    # Step 2: HTML 생성 (배경 실패해도 fallback으로 진행)
    actual_bg = BG_PATH if BG_PATH.exists() else OUTPUT_DIR / "bg.jpg"
    if not actual_bg.exists():
        # 배경 없으면 CSS 그라디언트 fallback
        actual_bg = None
    create_html_template(actual_bg or BG_PATH)

    # Step 3: 최종 캡처
    final_ok = capture_final()

    print("\n" + "=" * 60)
    print("생성 결과")
    print("=" * 60)
    print(f"  배경 이미지: {'OK' if bg_ok else 'SKIP'} → {OUTPUT_DIR}/bg.*")
    print(f"  HTML 템플릿: OK → {TEMPLATE_PATH}")
    print(f"  최종 이미지: {'OK' if final_ok else 'FAIL'} → {FINAL_PATH}")

    if final_ok:
        print("\n[SUCCESS] 컨셉 #06 생성 완료!")
    else:
        print("\n[PARTIAL] 일부 단계 실패. 파일을 확인해 주세요.")


if __name__ == "__main__":
    main()
