#!/usr/bin/env python3
"""Pretty render of the board: copper by net colour, pads, drills, labels."""
import importlib.util, sys, numpy as np
from PIL import Image, ImageDraw, ImageFont
spec = importlib.util.spec_from_file_location("bb", "bodyboard.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
import fab
b = m.b
r = fab.Router(b, grid=0.25)
for n in m.ORDER: r.route_net(n, m.WIDTH.get(n, m.SIG), verbose=False)

SC = 11          # px per mm
W, H = int(b.w * SC), int(b.h * SC)
COL = {"+12V": (240, 120, 70), "GND": (60, 80, 110), "BUS": (120, 200, 230),
       "+5V": (240, 190, 90), "+3V3": (150, 220, 150), "+3V3M": (150, 220, 150),
       "V12F": (235, 150, 90), "IDSENSE": (255, 215, 160), "IDSENSEX": (255, 215, 160)}
def colour(n):
    if n in COL: return COL[n]
    if n.startswith("ID"): return (250, 220, 120)
    if n.startswith("S"): return (200, 160, 240)
    return (180, 200, 215)

img = Image.new("RGB", (W, H), (14, 20, 30)); d = ImageDraw.Draw(img)
d.rectangle([2, 2, W - 3, H - 3], outline=(80, 95, 120), width=2)
pm = b.pour_mask()
if pm is not None:
    a = np.zeros((H, W, 3), np.uint8)
    small = np.array(Image.fromarray((pm * 255).astype(np.uint8)).resize((W, H)))
    a[small > 100] = (34, 46, 64)
    img = Image.fromarray(np.maximum(np.array(img), a)); d = ImageDraw.Draw(img)
X = lambda x: x * SC
Y = lambda y: H - y * SC
for sh in b.copper:
    c = colour(sh.net); p = sh.p
    if sh.kind == "trace":
        pts = [(X(x), Y(y)) for x, y in p["pts"]]
        d.line(pts, fill=c, width=max(1, int(p["w"] * SC)), joint="curve")
    elif sh.kind == "rect":
        d.rectangle([X(p["x"] - p["w"]/2), Y(p["y"] + p["h"]/2),
                     X(p["x"] + p["w"]/2), Y(p["y"] - p["h"]/2)], fill=c)
    else:
        rr = p["d"] / 2
        d.ellipse([X(p["x"] - rr), Y(p["y"] + rr), X(p["x"] + rr), Y(p["y"] - rr)], fill=c)
for x, y, dia in b.drills:
    rr = dia / 2
    d.ellipse([X(x - rr), Y(y + rr), X(x + rr), Y(y - rr)], fill=(14, 20, 30))
try: f = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 11)
except Exception: f = None
for x, y, s, size in b.silk:
    d.text((X(x) - len(s) * 3, Y(y)), s, fill=(225, 232, 242), font=f)
img.save("bodyboard_render.png")
print("wrote bodyboard_render.png", img.size, f"{len(b.parts)} parts")
