#!/usr/bin/env python3
"""M2 배너 재렌더링 — 배경 이미지 재생성 없이 HTML 오버레이만 Playwright로 캡처."""

from __future__ import annotations

import sys
import time
from pathlib import Path

from playwright.sync_api import sync_playwright

# gen_m2_*.py가 있는 디렉터리를 path에 추가
OUTPUT_DIR = Path("/home/jay/workspace/output/google-ads/banners/m2")
sys.path.insert(0, str(OUTPUT_DIR))

# 각 스크립트에서 build_html 함수 import
from gen_m2_1 import build_html_1200x628 as m1_wide, build_html_1080x1080 as m1_sq  # noqa: E402
from gen_m2_2 import build_html_1200x628 as m2_wide, build_html_1080x1080 as m2_sq  # noqa: E402
from gen_m2_3 import build_html_1200x628 as m3_wide, build_html_1080x1080 as m3_sq  # noqa: E402


def capture(html_content: str, output_path: Path, width: int, height: int) -> None:
    html_file = output_path.parent / f"_tmp_{output_path.stem}.html"
    html_file.write_text(html_content, encoding="utf-8")
    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_file.resolve()}", wait_until="networkidle")
            page.wait_for_timeout(3000)
            page.screenshot(path=str(output_path), type="png",
                            clip={"x": 0, "y": 0, "width": width, "height": height})
            print(f"  [OK] {output_path} ({output_path.stat().st_size:,} bytes)")
        finally:
            browser.close()


def main() -> None:
    t0 = time.time()
    print("=" * 60)
    print("M2 배너 재렌더링 시작")
    print("=" * 60)

    tasks = [
        # (build_fn, bg_path, output_path, w, h)
        (m1_wide, OUTPUT_DIR / "m2-1-bg.jpg", OUTPUT_DIR / "m2-1-1200x628.png", 1200, 628),
        (m1_sq,   OUTPUT_DIR / "m2-1-bg.jpg", OUTPUT_DIR / "m2-1-1080x1080.png", 1080, 1080),
        (m2_wide, OUTPUT_DIR / "m2-2-bg.jpg", OUTPUT_DIR / "m2-2-1200x628.png", 1200, 628),
        (m2_sq,   OUTPUT_DIR / "m2-2-bg.jpg", OUTPUT_DIR / "m2-2-1080x1080.png", 1080, 1080),
        (m3_wide, OUTPUT_DIR / "m2-3-bg.jpg", OUTPUT_DIR / "m2-3-1200x628.png", 1200, 628),
        (m3_sq,   OUTPUT_DIR / "m2-3-bg.jpg", OUTPUT_DIR / "m2-3-1080x1080.png", 1080, 1080),
    ]

    for build_fn, bg_path, out_path, w, h in tasks:
        if not bg_path.exists():
            print(f"  [SKIP] 배경 없음: {bg_path}")
            continue
        print(f"\n렌더링: {out_path.name} ({w}x{h})")
        html = build_fn(str(bg_path.resolve()))
        capture(html, out_path, w, h)

    print(f"\n총 소요: {time.time()-t0:.1f}초")
    print("완료!")


if __name__ == "__main__":
    main()
