#!/usr/bin/env python3
"""
Google Display Ad Generator - Angle A (정착지원금)
Design: #45 One Show 금융 럭셔리
Renders HTML templates with Playwright, resizes 300x250 with PIL.
"""

import os
import sys
from pathlib import Path
from playwright.sync_api import sync_playwright
from PIL import Image

OUTPUT_DIR = Path("/home/jay/workspace/output/google-ads/angle-A/production")
TEMPLATE_DIR = Path("/home/jay/workspace/output/google-ads/angle-A/templates")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
TEMPLATE_DIR.mkdir(parents=True, exist_ok=True)

# ─────────────────────────────────────────────
# HTML Templates
# ─────────────────────────────────────────────

HTML_1200x628 = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@400;700;900&family=Noto+Sans+KR:wght@400;700;900&display=swap" rel="stylesheet">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { width: 1200px; height: 628px; overflow: hidden; background: #0D0D0D; }

  .container {
    position: relative;
    width: 1200px;
    height: 628px;
    background: linear-gradient(135deg, #0D0D0D 0%, #1A1510 50%, #0D0D0D 100%);
    display: flex;
    flex-direction: row;
    align-items: stretch;
  }

  /* Subtle radial glow center-left */
  .container::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 30%;
    transform: translate(-50%, -50%);
    width: 600px;
    height: 600px;
    background: radial-gradient(ellipse, rgba(197,165,90,0.07) 0%, transparent 70%);
    pointer-events: none;
  }

  .gold-line-top {
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 4px;
    background: linear-gradient(90deg, transparent 0%, #C5A55A 30%, #C5A55A 70%, transparent 100%);
    z-index: 10;
  }
  .gold-line-bottom {
    position: absolute;
    bottom: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent 0%, rgba(197,165,90,0.4) 30%, rgba(197,165,90,0.4) 70%, transparent 100%);
    z-index: 10;
  }

  /* Tag top-right */
  .tag {
    position: absolute;
    top: 32px;
    right: 60px;
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 22px;
    font-weight: 400;
    color: rgba(255,255,255,0.35);
    letter-spacing: 0.12em;
    z-index: 5;
  }

  /* Left panel — headline */
  .left-panel {
    position: relative;
    width: 580px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 60px 48px 60px 60px;
    z-index: 5;
  }

  .eyebrow {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 22px;
    font-weight: 400;
    color: #C5A55A;
    letter-spacing: 0.25em;
    margin-bottom: 28px;
    text-transform: uppercase;
  }

  .headline {
    font-family: 'Noto Serif KR', serif;
    font-size: 84px;
    font-weight: 700;
    color: #FFFFFF;
    line-height: 1.25;
    letter-spacing: -0.02em;
  }

  /* Vertical divider */
  .vertical-divider {
    width: 1px;
    background: linear-gradient(to bottom, transparent, rgba(197,165,90,0.5) 30%, rgba(197,165,90,0.5) 70%, transparent);
    flex-shrink: 0;
    align-self: stretch;
    margin: 60px 0;
  }

  /* Right panel — accent + CTA */
  .right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 60px 60px 60px 64px;
    z-index: 5;
  }

  .accent-label {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 26px;
    font-weight: 400;
    color: rgba(255,255,255,0.5);
    letter-spacing: 0.08em;
    margin-bottom: 14px;
  }

  .accent-number {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 72px;
    font-weight: 900;
    color: #C5A55A;
    line-height: 1.05;
    letter-spacing: -0.03em;
    margin-bottom: 16px;
    white-space: nowrap;
    background: linear-gradient(180deg, #E8D5A0 0%, #C5A55A 55%, #A8893C 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }

  .sub-text {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 52px;
    font-weight: 700;
    color: rgba(255,255,255,0.75);
    line-height: 1.1;
    letter-spacing: -0.01em;
    margin-bottom: 44px;
  }

  .cta-block {
    margin-top: auto;
  }

  .cta-divider {
    width: 100%;
    height: 1px;
    background: rgba(255,255,255,0.2);
    margin-bottom: 20px;
  }

  .cta-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 36px;
    color: #FFFFFF;
    white-space: nowrap;
  }
  .cta-brand { font-weight: 700; }
  .cta-separator { color: rgba(255,255,255,0.4); margin: 0 12px; }
  .cta-action { font-weight: 400; color: rgba(255,255,255,0.8); }
  .cta-arrow { color: #C5A55A; font-size: 40px; margin-left: 16px; }

  /* Decorative corner */
  .corner-tl {
    position: absolute;
    top: 24px; left: 24px;
    width: 32px; height: 32px;
    border-top: 2px solid rgba(197,165,90,0.5);
    border-left: 2px solid rgba(197,165,90,0.5);
  }
  .corner-br {
    position: absolute;
    bottom: 24px; right: 24px;
    width: 32px; height: 32px;
    border-bottom: 2px solid rgba(197,165,90,0.5);
    border-right: 2px solid rgba(197,165,90,0.5);
  }
</style>
</head>
<body>
<div class="container">
  <div class="gold-line-top"></div>
  <div class="gold-line-bottom"></div>
  <div class="corner-tl"></div>
  <div class="corner-br"></div>
  <div class="tag">T.O.P 사업단</div>

  <div class="left-panel">
    <div class="eyebrow">T.O.P 사업단 정착지원</div>
    <div class="headline">열심히는<br>하는데,<br>소득은<br>제자리?</div>
  </div>

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

  <div class="right-panel">
    <div class="accent-label">신입 정착지원금</div>
    <div class="accent-number">최대 1,000만원</div>
    <div class="sub-text">신입 정착지원금</div>
    <div class="cta-block">
      <div class="cta-divider"></div>
      <div class="cta-row">
        <span>
          <span class="cta-brand">T.O.P 사업단</span>
          <span class="cta-separator">|</span>
          <span class="cta-action">지금 신청하기</span>
        </span>
        <span class="cta-arrow">→</span>
      </div>
    </div>
  </div>
</div>
</body>
</html>"""


HTML_1200x1200 = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@400;700;900&family=Noto+Sans+KR:wght@400;700;900&display=swap" rel="stylesheet">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { width: 1200px; height: 1200px; overflow: hidden; background: #0D0D0D; }

  .container {
    position: relative;
    width: 1200px;
    height: 1200px;
    background: linear-gradient(160deg, #0D0D0D 0%, #1C1710 40%, #150F09 70%, #0D0D0D 100%);
  }

  /* Radial glow */
  .glow {
    position: absolute;
    top: 45%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 900px;
    height: 900px;
    background: radial-gradient(ellipse, rgba(197,165,90,0.06) 0%, transparent 65%);
    pointer-events: none;
  }

  /* Gold top line */
  .gold-line {
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 5px;
    background: linear-gradient(90deg, transparent 0%, #C5A55A 25%, #E8D5A0 50%, #C5A55A 75%, transparent 100%);
    z-index: 10;
  }

  /* Decorative corners */
  .corner { position: absolute; width: 48px; height: 48px; }
  .corner-tl { top: 36px; left: 36px; border-top: 2px solid rgba(197,165,90,0.6); border-left: 2px solid rgba(197,165,90,0.6); }
  .corner-tr { top: 36px; right: 36px; border-top: 2px solid rgba(197,165,90,0.6); border-right: 2px solid rgba(197,165,90,0.6); }
  .corner-bl { bottom: 36px; left: 36px; border-bottom: 2px solid rgba(197,165,90,0.6); border-left: 2px solid rgba(197,165,90,0.6); }
  .corner-br { bottom: 36px; right: 36px; border-bottom: 2px solid rgba(197,165,90,0.6); border-right: 2px solid rgba(197,165,90,0.6); }

  /* Tag */
  .tag {
    position: absolute;
    top: 40px; right: 72px;
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 28px;
    font-weight: 400;
    color: rgba(255,255,255,0.3);
    letter-spacing: 0.15em;
    z-index: 5;
  }

  /* Top section: headline */
  .top-block {
    position: absolute;
    top: 120px;
    left: 72px; right: 72px;
    z-index: 5;
  }

  .eyebrow {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 26px;
    font-weight: 400;
    color: #C5A55A;
    letter-spacing: 0.3em;
    margin-bottom: 36px;
    text-transform: uppercase;
  }

  .headline {
    font-family: 'Noto Serif KR', serif;
    font-size: 84px;
    font-weight: 700;
    color: #FFFFFF;
    line-height: 1.3;
    letter-spacing: -0.02em;
  }

  /* Horizontal divider */
  .h-divider {
    position: absolute;
    top: 50%;
    left: 72px; right: 72px;
    height: 1px;
    background: linear-gradient(90deg, transparent, rgba(197,165,90,0.4) 20%, rgba(197,165,90,0.4) 80%, transparent);
    transform: translateY(-50%);
    z-index: 5;
  }

  /* Center: accent number block */
  .center-block {
    position: absolute;
    top: 50%;
    left: 72px; right: 72px;
    transform: translateY(-8%);
    z-index: 5;
    text-align: center;
  }

  .accent-label {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 32px;
    font-weight: 400;
    color: rgba(255,255,255,0.45);
    letter-spacing: 0.2em;
    margin-bottom: 20px;
  }

  .accent-number {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 144px;
    font-weight: 900;
    color: #C5A55A;
    line-height: 1.0;
    letter-spacing: -0.04em;
    background: linear-gradient(180deg, #E8D5A0 0%, #C5A55A 50%, #A8893C 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin-bottom: 24px;
  }

  .sub-text {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 64px;
    font-weight: 700;
    color: rgba(255,255,255,0.75);
    letter-spacing: 0.02em;
  }

  /* Bottom CTA */
  .bottom-block {
    position: absolute;
    bottom: 72px;
    left: 72px; right: 72px;
    z-index: 5;
  }

  .cta-divider {
    width: 100%;
    height: 1px;
    background: rgba(255,255,255,0.2);
    margin-bottom: 28px;
  }

  .cta-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 40px;
    color: #FFFFFF;
  }
  .cta-brand { font-weight: 700; }
  .cta-separator { color: rgba(255,255,255,0.35); margin: 0 16px; }
  .cta-action { font-weight: 400; color: rgba(255,255,255,0.7); }
  .cta-arrow { color: #C5A55A; font-size: 48px; }

  /* Small decorative dots */
  .dot-row {
    position: absolute;
    bottom: 148px;
    left: 72px;
    display: flex;
    gap: 10px;
    z-index: 5;
  }
  .dot {
    width: 6px; height: 6px;
    border-radius: 50%;
    background: rgba(197,165,90,0.5);
  }
  .dot:first-child { background: #C5A55A; }
</style>
</head>
<body>
<div class="container">
  <div class="glow"></div>
  <div class="gold-line"></div>

  <div class="corner corner-tl"></div>
  <div class="corner corner-tr"></div>
  <div class="corner corner-bl"></div>
  <div class="corner corner-br"></div>

  <div class="tag">T.O.P 사업단</div>

  <div class="top-block">
    <div class="eyebrow">T.O.P 사업단 정착지원</div>
    <div class="headline">열심히는 하는데,<br>소득은 제자리?</div>
  </div>

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

  <div class="center-block">
    <div class="accent-label">신입 정착지원금</div>
    <div class="accent-number">최대 1,000만원</div>
    <div class="sub-text">신입 정착지원금</div>
  </div>

  <div class="dot-row">
    <div class="dot"></div>
    <div class="dot"></div>
    <div class="dot"></div>
  </div>

  <div class="bottom-block">
    <div class="cta-divider"></div>
    <div class="cta-row">
      <span>
        <span class="cta-brand">T.O.P 사업단</span>
        <span class="cta-separator">|</span>
        <span class="cta-action">지금 신청하기</span>
      </span>
      <span class="cta-arrow">→</span>
    </div>
  </div>
</div>
</body>
</html>"""


# 300x250 rendered at 2x (600x500) then resized
HTML_600x500 = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@400;700;900&family=Noto+Sans+KR:wght@400;700;900&display=swap" rel="stylesheet">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { width: 600px; height: 500px; overflow: hidden; background: #0D0D0D; }

  .container {
    position: relative;
    width: 600px;
    height: 500px;
    background: linear-gradient(145deg, #0D0D0D 0%, #1A1510 55%, #0D0D0D 100%);
  }

  .glow {
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    width: 500px; height: 500px;
    background: radial-gradient(ellipse, rgba(197,165,90,0.08) 0%, transparent 65%);
    pointer-events: none;
  }

  /* Gold top line */
  .gold-line {
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 4px;
    background: linear-gradient(90deg, transparent 0%, #C5A55A 25%, #E8D5A0 50%, #C5A55A 75%, transparent 100%);
    z-index: 10;
  }

  /* Corners */
  .corner { position: absolute; width: 20px; height: 20px; }
  .corner-tl { top: 16px; left: 16px; border-top: 1.5px solid rgba(197,165,90,0.55); border-left: 1.5px solid rgba(197,165,90,0.55); }
  .corner-tr { top: 16px; right: 16px; border-top: 1.5px solid rgba(197,165,90,0.55); border-right: 1.5px solid rgba(197,165,90,0.55); }
  .corner-bl { bottom: 16px; left: 16px; border-bottom: 1.5px solid rgba(197,165,90,0.55); border-left: 1.5px solid rgba(197,165,90,0.55); }
  .corner-br { bottom: 16px; right: 16px; border-bottom: 1.5px solid rgba(197,165,90,0.55); border-right: 1.5px solid rgba(197,165,90,0.55); }

  /* Tag */
  .tag {
    position: absolute;
    top: 22px; right: 24px;
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 18px;
    font-weight: 400;
    color: rgba(255,255,255,0.3);
    letter-spacing: 0.1em;
    z-index: 5;
  }

  /* Top block */
  .top-block {
    position: absolute;
    top: 56px;
    left: 24px; right: 24px;
    z-index: 5;
  }

  .eyebrow {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 18px;
    font-weight: 400;
    color: #C5A55A;
    letter-spacing: 0.2em;
    margin-bottom: 14px;
  }

  .headline {
    font-family: 'Noto Serif KR', serif;
    font-size: 42px;
    font-weight: 700;
    color: #FFFFFF;
    line-height: 1.3;
    letter-spacing: -0.02em;
  }

  /* Center block */
  .center-block {
    position: absolute;
    top: 50%;
    left: 24px; right: 24px;
    transform: translateY(-20%);
    z-index: 5;
    text-align: center;
  }

  .accent-number {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 64px;
    font-weight: 900;
    line-height: 1.0;
    letter-spacing: -0.03em;
    background: linear-gradient(180deg, #E8D5A0 0%, #C5A55A 60%, #A8893C 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin-bottom: 10px;
  }

  .sub-text {
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 32px;
    font-weight: 700;
    color: rgba(255,255,255,0.7);
    letter-spacing: 0.01em;
  }

  /* Bottom CTA */
  .bottom-block {
    position: absolute;
    bottom: 24px;
    left: 24px; right: 24px;
    z-index: 5;
  }

  .cta-divider {
    width: 100%;
    height: 1px;
    background: rgba(255,255,255,0.2);
    margin-bottom: 14px;
  }

  .cta-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: 'Noto Sans KR', sans-serif;
    font-size: 20px;
    color: #FFFFFF;
  }
  .cta-brand { font-weight: 700; }
  .cta-separator { color: rgba(255,255,255,0.35); margin: 0 8px; }
  .cta-action { font-weight: 400; color: rgba(255,255,255,0.7); }
  .cta-arrow { color: #C5A55A; font-size: 22px; }
</style>
</head>
<body>
<div class="container">
  <div class="glow"></div>
  <div class="gold-line"></div>

  <div class="corner corner-tl"></div>
  <div class="corner corner-tr"></div>
  <div class="corner corner-bl"></div>
  <div class="corner corner-br"></div>

  <div class="tag">T.O.P 사업단</div>

  <div class="top-block">
    <div class="eyebrow">T.O.P 사업단</div>
    <div class="headline">열심히는<br>하는데,<br>소득은 제자리?</div>
  </div>

  <div class="center-block">
    <div class="accent-number">최대 1,000만원</div>
    <div class="sub-text">신입 정착지원금</div>
  </div>

  <div class="bottom-block">
    <div class="cta-divider"></div>
    <div class="cta-row">
      <span>
        <span class="cta-brand">T.O.P 사업단</span>
        <span class="cta-separator">|</span>
        <span class="cta-action">지금 신청하기</span>
      </span>
      <span class="cta-arrow">→</span>
    </div>
  </div>
</div>
</body>
</html>"""


def write_template(filename: str, content: str) -> Path:
    path = TEMPLATE_DIR / filename
    path.write_text(content, encoding="utf-8")
    print(f"  [template] wrote {path}")
    return path


def render_ad(page, html_path: Path, out_path: Path, width: int, height: int):
    page.set_viewport_size({"width": width, "height": height})
    page.goto(f"file://{html_path}", wait_until="networkidle", timeout=30000)
    # Extra wait to let web fonts fully load
    page.wait_for_timeout(2500)
    page.screenshot(path=str(out_path), full_page=False, clip={"x": 0, "y": 0, "width": width, "height": height})
    print(f"  [render]   {out_path} ({width}x{height})")


def resize_300x250(src_path: Path, dst_path: Path):
    img = Image.open(src_path)
    resized = img.resize((300, 250), Image.LANCZOS)
    resized.save(dst_path, "PNG", optimize=True)
    print(f"  [resize]   {dst_path} (300x250, from 600x500)")


def main():
    print("\n=== Angle A Display Ads Generator ===\n")

    # 1. Write HTML templates
    print("[1/3] Writing HTML templates...")
    tpl_1200x628  = write_template("display-1200x628.html",  HTML_1200x628)
    tpl_1200x1200 = write_template("display-1200x1200.html", HTML_1200x1200)
    tpl_600x500   = write_template("display-600x500.html",   HTML_600x500)

    # 2. Render with Playwright
    print("\n[2/3] Rendering with Playwright...")

    # Intermediate path for the 2x small banner
    tmp_600x500 = OUTPUT_DIR / "display-300x250-2x.png"

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=[
                "--no-sandbox",
                "--disable-setuid-sandbox",
                "--disable-dev-shm-usage",
                "--font-render-hinting=none",
            ]
        )
        context = browser.new_context(
            device_scale_factor=1,
        )
        page = context.new_page()

        render_ad(page, tpl_1200x628,  OUTPUT_DIR / "display-1200x628.png",  1200, 628)
        render_ad(page, tpl_1200x1200, OUTPUT_DIR / "display-1200x1200.png", 1200, 1200)
        render_ad(page, tpl_600x500,   tmp_600x500,                           600,  500)

        context.close()
        browser.close()

    # 3. Resize 300x250 with PIL
    print("\n[3/3] Resizing small banner with PIL...")
    resize_300x250(tmp_600x500, OUTPUT_DIR / "display-300x250.png")

    # Clean up intermediate file
    tmp_600x500.unlink(missing_ok=True)

    print("\n=== Done! Output files: ===")
    for f in sorted(OUTPUT_DIR.glob("*.png")):
        size_kb = f.stat().st_size / 1024
        print(f"  {f}  ({size_kb:.1f} KB)")
    print()


if __name__ == "__main__":
    main()
