# Extrai cores exatas do logo e gera versão com fundo transparente.
# Uso: uv run --with pillow python extrair_logo.py <logo.png> <pasta-saida>
import sys
from collections import Counter
from PIL import Image

src, outdir = sys.argv[1], sys.argv[2].rstrip("/")
img = Image.open(src).convert("RGBA")
w, h = img.size
px = img.load()

# cores dominantes (ignora branco/transparente), agrupadas
c = Counter()
for y in range(0, h, 2):
    for x in range(0, w, 2):
        r, g, b, a = px[x, y]
        if a > 200 and not (r > 240 and g > 240 and b > 240):
            c[(r // 16 * 16, g // 16 * 16, b // 16 * 16)] += 1
print("Cores dominantes do logo (aproximadas):")
for (r, g, b), n in c.most_common(6):
    print(f"  #{r:02X}{g:02X}{b:02X}  ({n} px)")

# pixels exatos mais saturados/escuros por família (afinar manualmente se precisar)
best = {}
for y in range(h):
    for x in range(w):
        r, g, b, a = px[x, y]
        if a < 250:
            continue
        lum = (r + g + b) / 3
        sat = max(r, g, b) - min(r, g, b)
        if sat > 40 and lum < 150:
            k = "escura-saturada"
            if k not in best or lum < best[k][3]:
                best[k] = (r, g, b, lum)
        if sat > 50 and lum >= 150:
            k = "clara-saturada"
            if k not in best or sat > (max(best[k][:3]) - min(best[k][:3])):
                best[k] = (r, g, b, lum)
print("Cores exatas sugeridas:")
for k, (r, g, b, _) in best.items():
    print(f"  {k}: #{r:02X}{g:02X}{b:02X}")

# versão transparente (remove fundo quase-branco com borda suave)
out = Image.new("RGBA", (w, h))
op = out.load()
for y in range(h):
    for x in range(w):
        r, g, b, a = px[x, y]
        lum = (r + g + b) / 3
        if lum > 245:
            op[x, y] = (r, g, b, 0)
        elif lum > 225:
            op[x, y] = (r, g, b, int((245 - lum) / 20 * 255))
        else:
            op[x, y] = (r, g, b, a)
dest = f"{outdir}/logo-transparente.png"
out.save(dest)
print(f"✅ versão transparente salva: {dest} ({w}x{h})")
