"""
Gera 4 variacoes de icone para o app Self (Meta Business).
Requisitos: 1024x1024 PNG, sem canal alpha, quadrado, sem transparencia.
"""
from playwright.sync_api import sync_playwright
from PIL import Image
import os

OUTPUT_DIR = "/opt/mia/workspace/self/icones"
os.makedirs(OUTPUT_DIR, exist_ok=True)


def render_html(html: str, out_path: str, size: int):
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": size, "height": size}, device_scale_factor=1)
        page.set_content(html, wait_until="networkidle")
        # aguarda fontes carregarem completamente
        page.evaluate("document.fonts.ready")
        page.screenshot(
            path=out_path,
            clip={"x": 0, "y": 0, "width": size, "height": size},
            omit_background=False,
        )
        browser.close()


def flatten_no_alpha(path: str, bg_hex: str):
    """Remove canal alpha, garante RGB puro sobre fundo solido."""
    img = Image.open(path)
    if img.mode in ("RGBA", "LA", "P"):
        r, g, b = int(bg_hex[1:3], 16), int(bg_hex[3:5], 16), int(bg_hex[5:7], 16)
        bg = Image.new("RGB", img.size, (r, g, b))
        img_rgba = img.convert("RGBA")
        bg.paste(img_rgba, mask=img_rgba.split()[-1])
        bg.save(path, "PNG", optimize=True)
    else:
        img.convert("RGB").save(path, "PNG", optimize=True)


def make_thumbnail(src: str, dst: str, size: int = 40):
    img = Image.open(src).convert("RGB")
    img.thumbnail((size, size), Image.LANCZOS)
    img.save(dst, "PNG")


# ============================================================
# V1 - Fundo dourado + S serifado escuro (brand-first)
# ============================================================
V1_HTML = """
<!DOCTYPE html>
<html><head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,900&display=swap" rel="stylesheet">
<style>
  html, body { margin:0; padding:0; width:1024px; height:1024px; overflow:hidden; background:#d6c08a; }
  .wrap {
    width:1024px; height:1024px; background:#d6c08a;
    display:flex; align-items:center; justify-content:center;
    position:relative;
  }
  .s {
    font-family: 'Fraunces', serif;
    font-weight: 900;
    font-size: 780px;
    color: #11151c;
    line-height: 1;
    letter-spacing: -0.04em;
    margin-top: -30px;
    font-variation-settings: "opsz" 144;
  }
</style>
</head><body>
  <div class="wrap"><span class="s">S</span></div>
</body></html>
"""


# ============================================================
# V2 - Fundo escuro editorial + S dourado
# ============================================================
V2_HTML = """
<!DOCTYPE html>
<html><head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,900&display=swap" rel="stylesheet">
<style>
  html, body { margin:0; padding:0; width:1024px; height:1024px; overflow:hidden; background:#0f1117; }
  .wrap {
    width:1024px; height:1024px; background:#0f1117;
    display:flex; align-items:center; justify-content:center;
    position:relative;
  }
  /* leve textura editorial: uma borda dourada muito sutil no perimetro interno */
  .wrap::before {
    content:''; position:absolute; inset:60px;
    border: 3px solid rgba(214,192,138,0.18);
    border-radius: 0;
  }
  .s {
    font-family: 'Fraunces', serif;
    font-weight: 900;
    font-size: 780px;
    color: #d6c08a;
    line-height: 1;
    letter-spacing: -0.04em;
    margin-top: -30px;
    font-variation-settings: "opsz" 144;
  }
</style>
</head><body>
  <div class="wrap"><span class="s">S</span></div>
</body></html>
"""


# ============================================================
# V3 - Fundo dourado + monograma abstrato (S geometrico organico)
# Sem letra literal - marca grafica
# ============================================================
V3_HTML = """
<!DOCTYPE html>
<html><head>
<style>
  html, body { margin:0; padding:0; width:1024px; height:1024px; overflow:hidden; background:#d6c08a; }
  .wrap {
    width:1024px; height:1024px; background:#d6c08a;
    display:flex; align-items:center; justify-content:center;
  }
  svg { display:block; }
</style>
</head><body>
  <div class="wrap">
    <!-- Marca abstrata: dois arcos que se espelham formando um S / infinito editorial -->
    <svg width="720" height="720" viewBox="0 0 720 720" xmlns="http://www.w3.org/2000/svg">
      <!-- arco superior -->
      <path d="M 180 240
               C 180 130, 340 90, 460 150
               C 560 200, 560 300, 460 340
               L 260 380"
            fill="none" stroke="#11151c" stroke-width="88" stroke-linecap="square"/>
      <!-- arco inferior espelhado -->
      <path d="M 540 480
               C 540 590, 380 630, 260 570
               C 160 520, 160 420, 260 380
               L 460 340"
            fill="none" stroke="#11151c" stroke-width="88" stroke-linecap="square"/>
    </svg>
  </div>
</body></html>
"""


# ============================================================
# V4 - Gradiente dos dourados + S em relevo escuro
# ============================================================
V4_HTML = """
<!DOCTYPE html>
<html><head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,900&display=swap" rel="stylesheet">
<style>
  html, body { margin:0; padding:0; width:1024px; height:1024px; overflow:hidden; }
  .wrap {
    width:1024px; height:1024px;
    background: linear-gradient(135deg, #d6c08a 0%, #f1e2b5 100%);
    display:flex; align-items:center; justify-content:center;
    position:relative;
  }
  .s {
    font-family: 'Fraunces', serif;
    font-weight: 900;
    font-size: 780px;
    color: #11151c;
    line-height: 1;
    letter-spacing: -0.04em;
    margin-top: -30px;
    font-variation-settings: "opsz" 144;
  }
</style>
</head><body>
  <div class="wrap"><span class="s">S</span></div>
</body></html>
"""


VARIACOES = [
    ("v1_dourado_S",          V1_HTML, "#d6c08a"),
    ("v2_escuro_S_dourado",   V2_HTML, "#0f1117"),
    ("v3_abstrato_dourado",   V3_HTML, "#d6c08a"),
    ("v4_gradiente_editorial", V4_HTML, "#d6c08a"),
]


def main():
    resultados = []
    for nome, html, bg in VARIACOES:
        path_1024 = f"{OUTPUT_DIR}/{nome}.png"
        path_2048 = f"{OUTPUT_DIR}/{nome}@2x.png"
        path_thumb = f"{OUTPUT_DIR}/{nome}_thumb40.png"

        print(f"Renderizando {nome} @1024...")
        render_html(html, path_1024, 1024)
        flatten_no_alpha(path_1024, bg)

        print(f"Renderizando {nome} @2048...")
        render_html(html, path_2048, 2048)
        flatten_no_alpha(path_2048, bg)

        print(f"Miniatura {nome} @40...")
        make_thumbnail(path_1024, path_thumb, 40)

        # validacao
        img = Image.open(path_1024)
        assert img.size == (1024, 1024), f"{nome} nao e 1024x1024"
        assert img.mode == "RGB", f"{nome} tem canal alpha (mode={img.mode})"
        size_kb = os.path.getsize(path_1024) / 1024
        resultados.append((nome, path_1024, img.size, img.mode, size_kb))
        print(f"  OK: {img.size} {img.mode} {size_kb:.1f} KB")

    print("\n=== RESUMO ===")
    for r in resultados:
        print(r)


if __name__ == "__main__":
    main()
