#!/usr/bin/env python3
"""Render a top-view PNG preview of the EasyEDA carrier board JSON."""

from __future__ import annotations

import json
import math
import os
import sys

from PIL import Image, ImageDraw, ImageFont

U = 1.0 / 0.254
SCALE = 9.0          # pixels per millimetre
MARGIN = 42
HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "FirebaseOTA_3x6_RevA_easyeda.json")
DST = os.path.join(HERE, "preview_top.png")
if len(sys.argv) > 1:
    _p = sys.argv[1]
    SRC = _p if os.path.isabs(_p) else os.path.join(HERE, _p)
    if len(sys.argv) > 2:
        _o = sys.argv[2]
        DST = _o if os.path.isabs(_o) else os.path.join(HERE, _o)
    elif "RevB" in os.path.basename(SRC):
        DST = os.path.join(HERE, "preview_top_revb.png")
REV = "Rev B wroom" if "RevB" in os.path.basename(SRC) else "Rev A"


def mm(v: float) -> float:
    return v / U


def font(size_px: int):
    for path in (
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    ):
        try:
            return ImageFont.truetype(path, size_px)
        except OSError:
            continue
    return ImageFont.load_default()


def main() -> None:
    doc = json.load(open(SRC, encoding="utf-8"))
    bw = mm(doc["BBox"]["width"])
    bh = mm(doc["BBox"]["height"])
    img = Image.new("RGB", (int(bw * SCALE) + 2 * MARGIN,
                            int(bh * SCALE) + 2 * MARGIN + 26), "#101418")
    d = ImageDraw.Draw(img)

    def px(x: float, y: float) -> tuple[float, float]:
        return MARGIN + x * SCALE, MARGIN + y * SCALE

    # board body
    d.rounded_rectangle([MARGIN, MARGIN, MARGIN + bw * SCALE, MARGIN + bh * SCALE],
                        radius=5 * SCALE, fill="#14361f", outline="#9be7a8", width=2)

    # collect
    pads, holes, tracks, silk, texts, cutouts, libs = [], [], [], [], [], [], []

    for s in doc["shape"]:
        kind = s.split("~", 1)[0]
        f = s.split("~")
        if kind == "TRACK":
            width, layer, net = float(f[1]), int(f[2]), f[3]
            nums = list(map(float, f[4].split()))
            pts = [(mm(nums[i]), mm(nums[i + 1])) for i in range(0, len(nums), 2)]
            tracks.append((width, layer, net, pts))
        elif kind == "HOLE":
            # field is the radius; drawing wants the diameter
            holes.append((mm(float(f[1])), mm(float(f[2])),
                          mm(float(f[3])) * 2))
        elif kind == "SOLIDREGION":
            nums = list(map(float, f[3].split()))
            cutouts.append([(mm(nums[i]), mm(nums[i + 1])) for i in range(0, len(nums), 2)])
        elif kind == "TEXT":
            texts.append((mm(float(f[2])), mm(float(f[3])), f[10], int(f[9])))
        elif kind == "LIB":
            x, y = mm(float(f[1])), mm(float(f[2]))
            ref = f[3].split("`")
            name = ref[1] if len(ref) > 1 else "?"
            libs.append((name, x, y))
            for child in s.split("#@$")[1:]:
                cf = child.split("~")
                ck = cf[0]
                if ck == "PAD":
                    pads.append((mm(float(cf[2])), mm(float(cf[3])),
                                 mm(float(cf[4])), mm(float(cf[5])),
                                 int(cf[6]), cf[7], cf[8],
                                 mm(float(cf[9])), cf[1]))
                elif ck == "TRACK":
                    nums = list(map(float, cf[4].split()))
                    pts = [(mm(nums[i]), mm(nums[i + 1])) for i in range(0, len(nums), 2)]
                    silk.append(pts)
                elif ck == "CIRCLE":
                    silk.append(("circle", mm(float(cf[1])), mm(float(cf[2])),
                                 mm(float(cf[3]))))

    # cutouts
    for poly in cutouts:
        d.polygon([px(x, y) for x, y in poly], fill="#101418")

    # PCB tracks (copper)
    for width, layer, net, pts in tracks:
        if layer == 10:
            d.line([px(x, y) for x, y in pts], fill="#d7ffe0", width=max(1, int(width * SCALE)))
        elif layer == 1:
            d.line([px(x, y) for x, y in pts], fill="#f05b4f", width=max(1, int(width * SCALE)))
        elif layer == 2:
            d.line([px(x, y) for x, y in pts], fill="#3f7cff", width=max(1, int(width * SCALE)))

    # silk
    for item in silk:
        if isinstance(item, tuple) and item and item[0] == "circle":
            _, x, y, r = item
            d.ellipse([px(x - r, y - r), px(x + r, y + r)], outline="#e8e26a", width=2)
        else:
            d.line([px(x, y) for x, y in item], fill="#e8e26a", width=1)

    # pads
    for x, y, w, h, layer, net, num, drill, shape in pads:
        fill = "#f2b134" if net else "#c9c9c9"
        if shape == "RECT":
            d.rectangle([px(x - w / 2, y - h / 2), px(x + w / 2, y + h / 2)],
                        fill=fill, outline="#ffd98a")
        else:
            d.ellipse([px(x - w / 2, y - h / 2), px(x + w / 2, y + h / 2)],
                      fill=fill, outline="#ffd98a")
        if drill > 0:
            d.ellipse([px(x - drill / 2, y - drill / 2), px(x + drill / 2, y + drill / 2)],
                      fill="#101418")

    # NPTH holes
    for x, y, dia in holes:
        d.ellipse([px(x - dia / 2, y - dia / 2), px(x + dia / 2, y + dia / 2)],
                  fill="#101418", outline="#8899aa")

    # text
    for x, y, s, size in texts:
        try:
            d.text(px(x, y), s, font=font(max(8, int(size * 0.254 * SCALE))), fill="#f3f3d0")
        except Exception:
            pass

    # component anchors
    for name, x, y in libs:
        if name and not name.startswith("ESP32-DEVKIT"):
            d.ellipse([px(x - 0.7, y - 0.7), px(x + 0.7, y + 0.7)], fill="#ffffff")

    title = f"FirebaseOTA 3x6 carrier - {REV} - 130 x 70 mm - top view"
    d.text((MARGIN, 10), title, font=font(18), fill="#e6edf3")
    d.text((MARGIN, MARGIN + bh * SCALE + 6),
           "red = top copper   blue = bottom copper   yellow = silk   gold = pads   dark = drills/cutouts",
           font=font(12), fill="#8b98a5")

    img.save(DST)
    print(f"wrote {DST} ({img.width} x {img.height})")


if __name__ == "__main__":
    main()
