#!/usr/bin/env python3
"""Step 2: Playwright로 HTML 템플릿 렌더링 → sample.png 생성 (concept #19)"""

from pathlib import Path
from playwright.sync_api import sync_playwright

BASE = Path("/home/jay/workspace/output/meta-ads/concept-catalog/19-persona-card")
TEMPLATE = BASE / "template.html"
BG = BASE / "bg.png"
OUTPUT = BASE / "sample.png"


def main():
    print(f"[1] 템플릿: {TEMPLATE}")
    print(f"[2] 배경:   {BG}")
    print(f"[3] 출력:   {OUTPUT}")

    if not TEMPLATE.exists():
        raise FileNotFoundError(f"template.html 없음: {TEMPLATE}")
    if not BG.exists():
        raise FileNotFoundError(f"bg.png 없음: {BG}")

    bg_file_url = f"file://{BG.resolve()}"

    with sync_playwright() as p:
        browser = p.chromium.launch(
            args=[
                "--disable-web-security",
                "--allow-file-access-from-files",
                "--no-sandbox",
            ]
        )
        context = browser.new_context(
            viewport={"width": 1080, "height": 1080},
        )
        page = context.new_page()

        # 파일 URL로 로드 (crossOrigin canvas 허용)
        template_url = f"file://{TEMPLATE.resolve()}"
        page.goto(template_url, wait_until="networkidle", timeout=30000)

        # BG 경로를 window에 주입하고 프로필 이미지 적용
        page.evaluate(f"""() => {{
            window.BG_PATH = "{bg_file_url}";
            // 스크립트 재실행 (window.BG_PATH 설정 후)
            var img = new Image();
            img.crossOrigin = 'anonymous';
            img.onload = function() {{
                var iw = img.naturalWidth;
                var ih = img.naturalHeight;
                // 인물 시작: 행 171 (16.7%), 끝: 853 (83.3%)
                // 얼굴 중심부: 약 17~50% 구간을 크롭
                // cropY = ih*0.165 (인물 시작점), cropH = 패널너비*0.95
                var profiles = [
                    {{ id: 'img1', sx: 0,        sy: 0, sw: iw/3, sh: ih, cropY: ih*0.165 }},
                    {{ id: 'img2', sx: iw/3,     sy: 0, sw: iw/3, sh: ih, cropY: ih*0.165 }},
                    {{ id: 'img3', sx: iw*2/3,   sy: 0, sw: iw/3, sh: ih, cropY: ih*0.165 }},
                ];
                profiles.forEach(function(p) {{
                    var canvas = document.createElement('canvas');
                    var size = 280;
                    canvas.width = size;
                    canvas.height = size;
                    var ctx = canvas.getContext('2d');
                    var cropY = p.cropY;
                    var cropH = p.sw * 0.95;
                    ctx.drawImage(img, p.sx, cropY, p.sw, cropH, 0, 0, size, size);
                    var el = document.getElementById(p.id);
                    if (el) el.src = canvas.toDataURL('image/jpeg', 0.95);
                }});
            }};
            img.src = "{bg_file_url}";
        }}""")

        # 렌더링 완료 대기 (폰트 + 이미지 로드)
        page.wait_for_timeout(3000)

        page.screenshot(path=str(OUTPUT), type="png", clip={"x": 0, "y": 0, "width": 1080, "height": 1080})
        print(f"[4] 스크린샷 저장 완료")

        browser.close()

    size_kb = OUTPUT.stat().st_size / 1024
    print(f"[5] 완료: {OUTPUT} ({size_kb:.0f} KB)")


if __name__ == "__main__":
    main()
