#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reescrita: injeta a nova imagem 1200x628 no post 5 mitos (que tem
container Elementor com aspect adaptavel) e verifica se todos os
elementos importantes aparecem inteiros em desktop e mobile.
"""
import base64
from pathlib import Path
from playwright.sync_api import sync_playwright

POST_PUB = "https://franciscoborrello.com.br/feng-shui/5-mitos-sobre-feng-shui-que-voce-ainda-acredita/"

OUT = Path("/opt/mia/workspace/temp/wp_preview_screenshots")
OUT.mkdir(parents=True, exist_ok=True)

NOVAS = {
    "01_entrada": "/opt/mia/workspace/clientes/borrello/blog/artigos_v1_2026-09-18/featured_images/featured_01_entrada.jpg",
    "02_quarto": "/opt/mia/workspace/clientes/borrello/blog/artigos_v1_2026-09-18/featured_images/featured_02_quarto.jpg",
    "03_plantas": "/opt/mia/workspace/clientes/borrello/blog/artigos_v1_2026-09-18/featured_images/featured_03_plantas.jpg",
    "04_animais": "/opt/mia/workspace/clientes/borrello/blog/artigos_v1_2026-09-18/featured_images/featured_04_animais.jpg",
    "05_bagua": "/opt/mia/workspace/clientes/borrello/blog/artigos_v1_2026-09-18/featured_images/featured_05_bagua.jpg",
}

UA_D = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
UA_M = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"


def inject_and_shot(page, img_path, dest):
    """Substitui a featured image do post + força aspect ratio 1200/628."""
    b64 = base64.b64encode(Path(img_path).read_bytes()).decode()
    data_url = f"data:image/jpeg;base64,{b64}"

    js = """
    (dataUrl) => {
        // pega a featured (widget Elementor theme-post-featured-image)
        const wrap = document.querySelector('.elementor-widget-theme-post-featured-image, .elementor-widget-image');
        const img = document.querySelector('.elementor-widget-theme-post-featured-image img, .attachment-large.wp-post-image, .wp-post-image, img.attachment-full');
        if (img) {
            img.src = dataUrl;
            img.srcset = '';
            img.removeAttribute('srcset');
            img.setAttribute('width', '1200');
            img.setAttribute('height', '628');
            // força aspect e evita distorção do fill
            img.style.aspectRatio = '1200 / 628';
            img.style.height = 'auto';
        }
        return img ? 1 : 0;
    }
    """
    r = page.evaluate(js, data_url)
    page.wait_for_timeout(1500)
    page.screenshot(path=str(dest), full_page=False)
    return r


def run():
    with sync_playwright() as p:
        b = p.chromium.launch()

        for slug, img_path in NOVAS.items():
            print(f"\n=== {slug} ===")

            for label, viewport, ua, mob, dsf in [
                ("desktop", {"width": 1440, "height": 900}, UA_D, False, 1),
                ("mobile", {"width": 390, "height": 844}, UA_M, True, 2),
            ]:
                ctx = b.new_context(
                    viewport=viewport, user_agent=ua,
                    is_mobile=mob, device_scale_factor=dsf,
                )
                page = ctx.new_page()
                try:
                    page.goto(POST_PUB, wait_until="networkidle", timeout=45000)
                    page.wait_for_timeout(1500)
                    dest = OUT / f"WP2_{label}_{slug}.png"
                    r = inject_and_shot(page, img_path, dest)
                    print(f"  {label} imgs={r} shot={dest.name}")
                except Exception as e:
                    print(f"  {label} ERRO: {e}")
                finally:
                    page.close()
                    ctx.close()

        b.close()


if __name__ == "__main__":
    run()
