#!/usr/bin/env python3
"""Production Batch C — 5 컨셉 × 2 사이즈 = 10 배너 일괄 렌더링 (Playwright)"""

from pathlib import Path
from playwright.sync_api import sync_playwright

BASE = Path("/home/jay/workspace/output/meta-ads/batch-c")

BANNERS = [
    ("41-cannes-unedited-reality", "41-cannes-1200x628.html", 1200, 628),
    ("41-cannes-unedited-reality", "41-cannes-1200x1200.html", 1200, 1200),
    ("44-oneshow-hangul-monument", "44-hangul-1200x628.html", 1200, 628),
    ("44-oneshow-hangul-monument", "44-hangul-1200x1200.html", 1200, 1200),
    ("45-oneshow-finance-luxury", "45-finance-1200x628.html", 1200, 628),
    ("45-oneshow-finance-luxury", "45-finance-1200x1200.html", 1200, 1200),
    ("48-madstars-digital-interactive", "48-madstars-1200x628.html", 1200, 628),
    ("48-madstars-digital-interactive", "48-madstars-1200x1200.html", 1200, 1200),
    ("49-spikes-trust-protection", "49-spikes-1200x628.html", 1200, 628),
    ("49-spikes-trust-protection", "49-spikes-1200x1200.html", 1200, 1200),
]


def render_all():
    results = []
    errors = []

    with sync_playwright() as p:
        browser = p.chromium.launch()

        for concept, html_file, width, height in BANNERS:
            html_path = BASE / concept / html_file
            png_name = html_file.replace(".html", ".png")
            png_path = BASE / concept / png_name

            if not html_path.exists():
                errors.append(f"MISSING: {html_path}")
                continue

            try:
                page = browser.new_page(viewport={"width": width, "height": height})
                page.goto(f"file://{html_path.resolve()}", wait_until="networkidle")
                page.evaluate("() => document.fonts.ready")
                page.wait_for_timeout(2000)
                page.screenshot(
                    path=str(png_path),
                    type="png",
                    clip={"x": 0, "y": 0, "width": width, "height": height},
                )
                size_kb = png_path.stat().st_size / 1024
                print(f"OK: {concept}/{png_name} ({size_kb:.0f} KB)")
                results.append(str(png_path))
                page.close()
            except Exception as e:
                errors.append(f"ERROR: {concept}/{html_file} — {e}")
                print(f"FAIL: {concept}/{html_file} — {e}")

        browser.close()

    print(f"\n=== 렌더링 완료: {len(results)}/10 성공 ===")
    if errors:
        print("오류:")
        for e in errors:
            print(f"  - {e}")

    return results, errors


if __name__ == "__main__":
    render_all()
