"""Build the Amini Building logo assets for the English site.

The only artwork available is the combined lockup on the WordPress site:
an "Amini Building Materials Trading" mark on the left, a navy rule, and
the TUPY mark on the right, all sitting on a flat light-grey plate.

The new site's header and footer are dark navy, so this script:

  1. downloads that lockup,
  2. splits off the Amini half at the navy rule,
  3. keys the grey plate out to transparency, unpremultiplying the
     anti-aliased edge pixels so they do not carry a grey halo,
  4. writes the full-colour cut-out (for light backgrounds), and
  5. writes a gold-lifted one-colour version for dark backgrounds.

Step 5 exists because the left end of the Amini gradient is a dark brown
(around #5a3a20). On #04142c that is a contrast ratio of roughly 1.7:1 --
effectively invisible. The gold version keeps the gradient's direction but
raises its floor, so the whole mark reads on navy.
"""

import os
import urllib.request

from PIL import Image

SRC = "https://tupyfittings.com/wp-content/uploads/2026/01/abmt-tupy-logo.png"
OUT_DIR = "/home/abmtgrou/en.tupyfittings.com/media/brand"

GOLD_DARK = (168, 120, 45)
GOLD_LIGHT = (243, 205, 128)

report = []


def lum(px):
    return 0.299 * px[0] + 0.587 * px[1] + 0.114 * px[2]


req = urllib.request.Request(SRC, headers={"User-Agent": "Mozilla/5.0"})
raw = urllib.request.urlopen(req, timeout=60).read()
tmp = os.path.join(OUT_DIR, "_lockup-src.png")
if not os.path.isdir(OUT_DIR):
    os.makedirs(OUT_DIR)
open(tmp, "wb").write(raw)

img = Image.open(tmp).convert("RGBA")
W, H = img.size
report.append("source %dx%d" % (W, H))

# ---- 1. find the navy divider ------------------------------------------
px = img.load()
best_x, best_v = None, 1e9
for x in range(int(W * 0.40), int(W * 0.60)):
    tot = 0.0
    for y in range(0, H, 4):
        tot += lum(px[x, y])
    if tot < best_v:
        best_v, best_x = tot, x
report.append("divider at x=%d" % best_x)

amini = img.crop((0, 0, max(1, best_x - 6), H))

# ---- 2. key out the grey plate -----------------------------------------
# The lockup has a white margin around a light-grey plate, so keying a
# single colour left the plate behind. Key against both, per pixel.
plates = [(255, 255, 255), amini.getpixel((amini.size[0] - 3, amini.size[1] // 2))[:3]]
report.append("plates %r" % (plates,))

LO, HI = 12.0, 55.0
ap = amini.load()
w, h = amini.size
for y in range(h):
    for x in range(w):
        r, g, b, a = ap[x, y]
        bg = plates[0]
        d = 1e9
        for p in plates:
            pd = max(abs(r - p[0]), abs(g - p[1]), abs(b - p[2]))
            if pd < d:
                d, bg = pd, p
        if d <= LO:
            ap[x, y] = (r, g, b, 0)
        elif d < HI:
            f = (d - LO) / (HI - LO)
            na = int(round(255 * f))
            if na < 1:
                ap[x, y] = (r, g, b, 0)
                continue
            nr = int(round(bg[0] + (r - bg[0]) / f))
            ng = int(round(bg[1] + (g - bg[1]) / f))
            nb = int(round(bg[2] + (b - bg[2]) / f))
            ap[x, y] = (
                max(0, min(255, nr)),
                max(0, min(255, ng)),
                max(0, min(255, nb)),
                min(255, na),
            )
        else:
            ap[x, y] = (r, g, b, 255)

bbox = amini.getbbox()
amini = amini.crop(bbox)
report.append("cut-out %dx%d (bbox %r)" % (amini.size[0], amini.size[1], bbox))
amini.save(os.path.join(OUT_DIR, "amini-logo.png"))

# ---- 3. gold-lifted version for dark backgrounds ------------------------
gold = amini.copy()
gp = gold.load()
w, h = gold.size

lo, hi = 255.0, 0.0
for y in range(h):
    for x in range(w):
        if gp[x, y][3] > 200:
            v = lum(gp[x, y])
            lo = min(lo, v)
            hi = max(hi, v)
if hi - lo < 1:
    lo, hi = 0.0, 255.0
report.append("ink luminance %.1f..%.1f" % (lo, hi))

for y in range(h):
    for x in range(w):
        r, g, b, a = gp[x, y]
        if a == 0:
            continue
        t = (lum((r, g, b)) - lo) / (hi - lo)
        t = max(0.0, min(1.0, t))
        gp[x, y] = (
            int(round(GOLD_DARK[0] + (GOLD_LIGHT[0] - GOLD_DARK[0]) * t)),
            int(round(GOLD_DARK[1] + (GOLD_LIGHT[1] - GOLD_DARK[1]) * t)),
            int(round(GOLD_DARK[2] + (GOLD_LIGHT[2] - GOLD_DARK[2]) * t)),
            a,
        )
gold.save(os.path.join(OUT_DIR, "amini-logo-gold.png"))
report.append("gold %dx%d" % gold.size)

os.remove(tmp)
out = "\n".join(report)
open("/home/abmtgrou/en.tupyfittings.com/amini.out", "w").write(out + "\n")
print(out)