"""Immagine di anteprima del sito (Open Graph, 1200x630), nello stile delle copertine dei caroselli.

    python3 codice/og.py nome "archivio/.../foto.jpg" [--posizione "50% 60%"] [--sito]

Scrive out/og/<nome>.png e out/og/<nome>.jpg. Con --sito copia il jpg in sito/static/og-bg-perspective.jpg,
cioè l'anteprima di default di home e pagine elenco (le schede dei giochi usano la loro foto).
Stile agganciato a slide.py (.cop): foto a tutta pagina, sfumatura dal nero che sale dal basso,
occhiello ambra #E0A340, nome in Bebas Neue, riga grigia in Inter. Margini 64 come le slide.
Si rende con Chrome come le slide, perché i font stanno in woff2 e Pillow non li legge.
"""
import os, shutil, subprocess, sys
from PIL import Image
import slide

W, H = 1200, 630
SITO = os.path.join(slide.BASE, "sito", "static", "og-bg-perspective.jpg")


def og(nome, foto, posizione="50% 50%"):
    html = f"""<!doctype html><html lang="it"><head><meta charset="utf-8"><link rel="stylesheet" href="{slide.FONT}/locale.css">
<style>body{{margin:0;width:{W}px;height:{H}px;background:#000;font-family:Inter,system-ui,sans-serif;color:#fff;overflow:hidden;-webkit-font-smoothing:antialiased;position:relative}}
.foto{{position:absolute;inset:0;width:{W}px;height:{H}px;object-fit:cover;object-position:{posizione}}}
.sf{{position:absolute;left:0;right:0;bottom:0;height:530px;background:linear-gradient(to top,rgba(0,0,0,.95),rgba(0,0,0,.84) 34%,rgba(0,0,0,.55) 58%,rgba(0,0,0,0))}}
.testo{{position:absolute;left:64px;right:64px;bottom:52px}}
.occh{{font-size:28px;letter-spacing:.16em;text-transform:uppercase;color:#E0A340;font-weight:700;line-height:1}}
.tit{{font-family:'Bebas Neue',sans-serif;font-size:164px;line-height:.86;letter-spacing:.014em;margin-top:22px}}
.riga{{display:flex;align-items:center;gap:22px;margin-top:22px;font-size:28px;color:#c9c9c9;font-weight:500;line-height:1}}
.filetto{{width:64px;height:4px;background:#E0A340}}</style></head><body>
<img class="foto" src="{os.path.abspath(foto)}">
<div class="sf"></div>
<div class="testo">
 <div class="occh">Giochi da tavolo, visti dal tavolo</div>
 <div class="tit">bg_perspective</div>
 <div class="riga"><span class="filetto"></span><span>bg-perspective.it</span></div>
</div>
</body></html>"""
    os.makedirs(slide.HTML, exist_ok=True)
    out = os.path.join(slide.BASE, "out", "og"); os.makedirs(out, exist_ok=True)
    h = os.path.join(slide.HTML, f"og_{nome}.html")
    with open(h, "w", encoding="utf-8") as f: f.write(html)
    png = os.path.join(out, f"{nome}.png")
    subprocess.run([slide.CHROME, "--headless", "--disable-gpu", "--hide-scrollbars", "--force-device-scale-factor=1",
                    f"--window-size={W},{H}", "--virtual-time-budget=4000", f"--screenshot={png}", f"file://{h}"],
                   check=True, capture_output=True)
    jpg = png[:-4] + ".jpg"
    im = Image.open(png).convert("RGB")
    if im.size != (W, H):
        raise ValueError(f"{png}: {im.size}, atteso {W}x{H}")
    im.save(jpg, quality=88, optimize=True, progressive=True)
    return jpg


if __name__ == "__main__":
    args = sys.argv[1:]
    sito = "--sito" in args
    if sito: args.remove("--sito")
    pos = "50% 50%"
    if "--posizione" in args:
        i = args.index("--posizione"); pos = args[i + 1]; del args[i:i + 2]
    nome, foto = args
    jpg = og(nome, foto, pos)
    if sito:
        shutil.copyfile(jpg, SITO)
        print(SITO)
    print(jpg)
