"""
Refaz V3: monograma abstrato mais elegante.
Ideia: dois arcos espelhados (top-right e bottom-left) que sugerem um S
com respiro editorial, tipo assinatura Chanel/YSL.
"""
from playwright.sync_api import sync_playwright
from PIL import Image
import os

OUTPUT_DIR = "/opt/mia/workspace/self/icones"

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;
  }
</style>
</head><body>
  <div class="wrap">
    <!--
      Monograma editorial: linha continua em S, tipo assinatura.
      Traco grosso, terminacoes retas, forma orgânica mas geometrica.
    -->
    <svg width="640" height="720" viewBox="0 0 640 720" xmlns="http://www.w3.org/2000/svg">
      <path d="M 560 130
               C 560 60, 460 20, 320 20
               C 180 20, 80 90, 80 190
               C 80 290, 180 320, 320 360
               C 460 400, 560 430, 560 530
               C 560 630, 460 700, 320 700
               C 180 700, 80 660, 80 590"
            fill="none"
            stroke="#11151c"
            stroke-width="80"
            stroke-linecap="butt"
            stroke-linejoin="miter"/>
    </svg>
  </div>
</body></html>
"""


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")
        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):
    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")


nome = "v3_abstrato_dourado"
bg = "#d6c08a"
path_1024 = f"{OUTPUT_DIR}/{nome}.png"
path_2048 = f"{OUTPUT_DIR}/{nome}@2x.png"
path_thumb = f"{OUTPUT_DIR}/{nome}_thumb40.png"

render_html(V3_HTML, path_1024, 1024)
flatten_no_alpha(path_1024, bg)
render_html(V3_HTML, path_2048, 2048)
flatten_no_alpha(path_2048, bg)
make_thumbnail(path_1024, path_thumb, 40)

img = Image.open(path_1024)
print(f"V3 refeito: {img.size} {img.mode} {os.path.getsize(path_1024)/1024:.1f}KB")
