#!/usr/bin/env python3
"""Make a TRANSPARENT-background version of a chip's shaded iso PNG so it can be
overlaid on any canvas (e.g. the symbol centre) without an ugly box.

Usage:  occt-iso.py <iso.png> <out.png>

chip-thumbnailer renders the iso on a uniform slate background; we sample that
background colour from the corners and feather it to transparent (distance-based
alpha), which keeps clean anti-aliased chip edges. Requires numpy + Pillow.
"""
import sys
import numpy as np
from PIL import Image

def main():
    src, out = sys.argv[1], sys.argv[2]
    img = np.asarray(Image.open(src).convert("RGB"), dtype=np.float64)
    h, w, _ = img.shape
    # Background colour = median of the four corners (robust to a stray pixel).
    corners = np.array([img[2, 2], img[2, w-3], img[h-3, 2], img[h-3, w-3]])
    bg = np.median(corners, axis=0)
    dist = np.sqrt(((img - bg) ** 2).sum(axis=2))
    # Feather: dist<=T0 → transparent, dist>=T1 → opaque.
    T0, T1 = 16.0, 44.0
    alpha = np.clip((dist - T0) / (T1 - T0), 0.0, 1.0)
    rgba = np.dstack([img, alpha * 255.0]).astype(np.uint8)
    Image.fromarray(rgba, "RGBA").save(out)
    print(f"OK: transparent iso → {out}")

if __name__ == "__main__":
    main()
