#!/usr/bin/env python3
"""Gera PDF com imagem + legenda por criativo para o Borrello aprovar."""
import base64
import json
from pathlib import Path

BASE = Path("/opt/mia/workspace/clientes/borrello/criativos_ig_lote2_2026-09-21")
LEG = json.load(open(BASE / "legendas.json"))

ESTATICOS = [
    ("01_cores_feng_shui_bagua", "Estático 01 — Cores do feng shui por área (baguá)"),
    ("02_3_erros_entrada_casa", "Estático 02 — 3 erros na entrada da casa"),
    ("03_sinais_energia_parada", "Estático 03 — Sinais de que sua casa tem energia parada"),
    ("04_rotina_limpeza_energetica", "Estático 04 — Rotina de limpeza energética simples"),
    ("05_plantas_prosperidade", "Estático 05 — Plantas que atraem prosperidade"),
]

CARROSSEL_SLIDES = [
    ("slide_01_capa.png", "Slide 1 — Capa"),
    ("slide_02_posicao_cama.png", "Slide 2 — Posição da cama"),
    ("slide_03_espelho.png", "Slide 3 — Espelho"),
    ("slide_04_cabeceira.png", "Slide 4 — Cabeceira"),
    ("slide_05_debaixo_cama.png", "Slide 5 — Debaixo da cama"),
    ("slide_06_cores.png", "Slide 6 — Cores"),
    ("slide_07_cta.png", "Slide 7 — CTA"),
]


def b64(path):
    return base64.b64encode(Path(path).read_bytes()).decode()


def esc(s):
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\n", "<br>")


html = ['<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><title>Lote 2 — Aprovacao</title>',
        '<style>',
        '@page { size: A4; margin: 20mm; }',
        'body { font-family: Georgia, "Times New Roman", serif; color:#1a1a1a; max-width:800px; margin:0 auto; padding:20px; }',
        'h1 { font-size:28px; margin-bottom:6px; }',
        '.subt { color:#666; font-size:14px; margin-bottom:32px; }',
        '.card { page-break-inside: avoid; page-break-after: always; padding:22px 0; border-top:2px solid #111; }',
        '.card h2 { font-size:20px; margin:0 0 14px 0; color:#111; }',
        '.card img { width:100%; max-width:520px; border-radius:8px; display:block; margin:0 auto 18px; box-shadow:0 2px 12px rgba(0,0,0,.15); }',
        '.legenda { background:#faf7f2; border-left:4px solid #e0b400; padding:18px 22px; border-radius:6px; font-size:14.5px; line-height:1.65; white-space:pre-line; }',
        '.legenda strong { display:block; font-size:11px; letter-spacing:1px; color:#8a6a00; margin-bottom:10px; font-family:Arial,sans-serif; }',
        '.grid7 { display:grid; grid-template-columns:repeat(2,1fr); gap:14px; margin-bottom:18px; }',
        '.grid7 figure { margin:0; }',
        '.grid7 img { width:100%; border-radius:6px; box-shadow:0 1px 6px rgba(0,0,0,.12); }',
        '.grid7 figcaption { font-size:11px; color:#555; text-align:center; margin-top:4px; font-family:Arial,sans-serif; }',
        '.hero { display:flex; align-items:center; gap:18px; margin-bottom:28px; padding:18px; background:#111; color:#fff; border-radius:10px; }',
        '.hero .dot { width:52px; height:52px; border-radius:50%; background:#f5c400; flex-shrink:0; }',
        '.hero h1 { color:#fff; margin:0; font-size:22px; }',
        '.hero p { margin:4px 0 0 0; font-size:13px; color:#ccc; font-family:Arial,sans-serif; }',
        '</style></head><body>',
        '<div class="hero"><div class="dot"></div><div>',
        '<h1>Lote 2 — Aprovação de criativos IG</h1>',
        '<p>Francisco Borrello · 5 estáticos + 1 carrossel · setembro/2026</p>',
        '</div></div>',
        '<p class="subt">Para cada criativo abaixo, revise a arte e a legenda. Aprove marcando "OK" ou aponte ajustes. As legendas foram escritas para o público 60+, com foco em conversa direta e engajamento.</p>',
        ]

for key, titulo in ESTATICOS:
    img_path = BASE / "estaticos" / f"{key}.png"
    img_b64 = b64(img_path)
    legenda = LEG["estaticos"][key]
    html.append(f'<div class="card"><h2>{titulo}</h2>')
    html.append(f'<img src="data:image/png;base64,{img_b64}" alt="{titulo}">')
    html.append(f'<div class="legenda"><strong>LEGENDA DO POST</strong>{esc(legenda)}</div>')
    html.append('</div>')

# Carrossel
html.append('<div class="card"><h2>Carrossel — Feng Shui no quarto (5 mudanças que qualquer um pode fazer)</h2>')
html.append('<div class="grid7">')
for fname, cap in CARROSSEL_SLIDES:
    img_path = BASE / "carrossel_quarto" / fname
    img_b64 = b64(img_path)
    html.append(f'<figure><img src="data:image/png;base64,{img_b64}"><figcaption>{cap}</figcaption></figure>')
html.append('</div>')
html.append(f'<div class="legenda"><strong>LEGENDA DO CARROSSEL</strong>{esc(LEG["carrossel_quarto"])}</div>')
html.append('</div>')

html.append('</body></html>')
html_str = "\n".join(html)

out_html = BASE / "lote2_aprovacao.html"
out_html.write_text(html_str)
print("HTML:", out_html)

# PDF via playwright
from playwright.sync_api import sync_playwright
out_pdf = BASE / "lote2_aprovacao_Borrello.pdf"
with sync_playwright() as p:
    b = p.chromium.launch()
    ctx = b.new_context()
    page = ctx.new_page()
    page.goto(f"file://{out_html}")
    page.pdf(path=str(out_pdf), format="A4", margin={"top":"18mm","bottom":"18mm","left":"15mm","right":"15mm"}, print_background=True)
    b.close()
print("PDF:", out_pdf, out_pdf.stat().st_size, "bytes")
