"""Create a KiCad 10 board from a kicad-cli netlist: outline, fixed + packed placement, nets, GND/thermal pours."""
import json, math, os, sys
sys.path.insert(0, os.path.dirname(__file__))
import pcbnew
from sexp import parse, find, unq

spec = json.load(open(sys.argv[1]))
K = r"C:\Program Files\KiCad\10.0\share\kicad\footprints"
MM = pcbnew.FromMM
V = lambda x, y: pcbnew.VECTOR2I(MM(x), MM(y))

tree = parse(open(spec['netlist'], encoding='utf-8').read())
comps = {}
for c in find(find(tree, 'components')[0], 'comp'):
    ref = unq(find(c, 'ref')[0][1])
    props = {unq(find(p, 'name')[0][1]): (unq(find(p, 'value')[0][1]) if find(p, 'value') else '') for p in find(c, 'property')}
    # Custom symbol fields (MPN, Manufacturer, ...) are copied to the footprint so DRC parity stays clean.
    extra = {}
    for fl in find(c, 'fields'):
        for f in find(fl, 'field'):
            k = unq(find(f, 'name')[0][1])
            if k != 'Footprint' and len(f) > 2:
                extra[k] = unq(f[2])
    comps[ref] = dict(value=unq(find(c, 'value')[0][1]), fp=unq(find(c, 'footprint')[0][1]),
                      uuid=unq(find(c, 'tstamps')[0][1]), dnp='dnp' in props, fields=extra,
                      no_bom='exclude_from_bom' in props)
pinnet = {}
netnames = []
for n in find(find(tree, 'nets')[0], 'net'):
    name = unq(find(n, 'name')[0][1]); netnames.append(name)
    for node in find(n, 'node'):
        pinnet[(unq(find(node, 'ref')[0][1]), unq(find(node, 'pin')[0][1]))] = name

b = pcbnew.BOARD()
b.SetCopperLayerCount(spec['layers'])
tb = b.GetTitleBlock()
tb.SetTitle(spec['title']); tb.SetRevision('A'); tb.SetDate('2026-11-03'); tb.SetCompany('MBARI')
nets = {}
for name in netnames:
    ni = pcbnew.NETINFO_ITEM(b, name); b.Add(ni); nets[name] = ni


def edge_line(a, c):
    s = pcbnew.PCB_SHAPE(b, pcbnew.SHAPE_T_SEGMENT); s.SetStart(V(*a)); s.SetEnd(V(*c))
    s.SetLayer(pcbnew.Edge_Cuts); s.SetWidth(MM(0.1)); b.Add(s)


def edge_arc(a, m, c):
    s = pcbnew.PCB_SHAPE(b, pcbnew.SHAPE_T_ARC); s.SetArcGeometry(V(*a), V(*m), V(*c))
    s.SetLayer(pcbnew.Edge_Cuts); s.SetWidth(MM(0.1)); b.Add(s)


circle = spec.get('circle')          # [cx, cy, radius] -> round board instead of a rounded rectangle
if circle:
    ccx, ccy, cr = circle
    s = pcbnew.PCB_SHAPE(b, pcbnew.SHAPE_T_CIRCLE); s.SetCenter(V(ccx, ccy)); s.SetEnd(V(ccx + cr, ccy))
    s.SetLayer(pcbnew.Edge_Cuts); s.SetWidth(MM(0.1)); b.Add(s)
    x0, y0, x1, y1 = ccx - cr, ccy - cr, ccx + cr, ccy + cr
else:
    x0, y0, x1, y1, r = spec['outline']
    k = r * (1 - math.sqrt(0.5))
    edge_line((x0 + r, y0), (x1 - r, y0)); edge_arc((x1 - r, y0), (x1 - k, y0 + k), (x1, y0 + r))
    edge_line((x1, y0 + r), (x1, y1 - r)); edge_arc((x1, y1 - r), (x1 - k, y1 - k), (x1 - r, y1))
    edge_line((x1 - r, y1), (x0 + r, y1)); edge_arc((x0 + r, y1), (x0 + k, y1 - k), (x0, y1 - r))
    edge_line((x0, y1 - r), (x0, y0 + r)); edge_arc((x0, y0 + r), (x0 + k, y0 + k), (x0 + r, y0))

fps = {}
for ref, c in comps.items():
    lib, name = c['fp'].split(':')
    path = os.path.join(spec['projlib'], lib + '.pretty') if lib in spec.get('projlibs', []) else os.path.join(K, lib + '.pretty')
    fp = pcbnew.FootprintLoad(path, name)
    assert fp, c['fp']
    fp.SetFPID(pcbnew.LIB_ID(lib, name))
    fp.SetReference(ref); fp.SetValue(c['value'])
    fp.SetExcludedFromBOM(c['no_bom'])     # follow the symbol (e.g. TestPoint pads used as wire pads stay in the BOM)
    for k, v in c['fields'].items():
        fp.SetField(k, v)
        fp.GetField(k).SetVisible(False)
    fp.SetPath(pcbnew.KIID_PATH('/' + c['uuid']))
    if c['dnp']:
        fp.SetDNP(True)
    for pad in fp.Pads():
        n = pinnet.get((ref, pad.GetNumber()))
        if n:
            pad.SetNet(nets[n])
    b.Add(fp); fps[ref] = fp


def courtyard(fp):
    cy = fp.GetCourtyard(pcbnew.B_CrtYd if fp.IsFlipped() else pcbnew.F_CrtYd)
    bb = cy.BBox() if cy.OutlineCount() else fp.GetBoundingBox(False)
    return pcbnew.ToMM(bb.GetX()), pcbnew.ToMM(bb.GetY()), pcbnew.ToMM(bb.GetRight()), pcbnew.ToMM(bb.GetBottom())


def orient(fp, rot, side):
    """Set rotation (as seen from the top) and board side ('F' or 'B'); bottom parts are mirrored left-right."""
    fp.SetOrientationDegrees(rot)
    if side == 'B' and not fp.IsFlipped():
        fp.Flip(fp.GetPosition(), pcbnew.FLIP_DIRECTION_LEFT_RIGHT)


placed = set()
for ref, f in spec['fixed'].items():
    x, y, rot = f[:3]
    fp = fps[ref]; fp.SetPosition(V(x, y)); orient(fp, rot, f[3] if len(f) > 3 else 'F'); placed.add(ref)

GAP = spec.get('gap', 0.5)
KEEP = spec.get('edge_keep', 0.25)          # courtyard keep-in from a round board edge


def chord(y0, y1):
    """x-range allowed for a row spanning y0..y1 on a round board (None = rectangular board)."""
    if not circle:
        return -1e9, 1e9
    R = cr - KEEP
    dy = max(abs(y0 - ccy), abs(y1 - ccy))
    if dy >= R:
        return None
    h = math.sqrt(R * R - dy * dy)
    return ccx - h, ccx + h


overflow = []
for reg in spec['regions']:
    rx0, ry0, rx1, ry1 = reg['box']
    side = reg.get('side', 'F')
    items = []
    for ref in reg['refs']:
        fp = fps[ref]; fp.SetPosition(V(0, 0)); orient(fp, reg.get('rot', {}).get(ref, 0), side)
        cx0, cy0, cx1, cy1 = courtyard(fp)
        items.append((ref, cx0, cy0, cx1 - cx0, cy1 - cy0))
    if reg.get('sort', True):
        items.sort(key=lambda t: -t[4])
    up = reg.get('up', False)            # pack rows from the bottom of the box upwards
    cy, i = (ry1 if up else ry0), 0
    while i < len(items):
        h = items[i][4]
        if up:
            cy -= h                       # cy is the top of the row being tried
        if cy + h > ry1 + 1e-6 or cy < ry0 - 1e-6:
            break
        lim = chord(cy, cy + h)
        xl, xr = (max(rx0, lim[0]), min(rx1, lim[1])) if lim else (0, -1)
        row = []
        cx = xl
        while i < len(items) and items[i][4] <= h + 1e-6 and cx + items[i][3] <= xr + 1e-6:
            row.append((items[i], cx)); cx += items[i][3] + GAP; i += 1
        if not row:                      # row too narrow here (round edge)
            if up:                       # moving further up only gets narrower
                break
            cy += 0.25                   # move down, away from the edge, and retry
            continue
        shift = (xr - (cx - GAP)) / 2 if reg.get('center', True) else 0   # centre the row in its chord
        for (ref, ox, oy, w, hh), x in row:
            # rows packed upwards are bottom-aligned, rows packed downwards top-aligned
            yy = cy + h - hh if up else cy
            fps[ref].SetPosition(V(round(x + shift - ox, 2), round(yy - oy, 2))); placed.add(ref)
        cy = cy - GAP if up else cy + h + GAP
    left = [t[0] for t in items[i:]]
    for k, ref in enumerate(left):       # park what didn't fit off the board so the layout can still be inspected
        fps[ref].SetPosition(V(x1 + 8 + 6 * (len(overflow) + k), y0)); placed.add(ref)
    overflow.extend(left)
    print(f'region {reg["name"]}: ' + (f'OVERFLOW, parked {left}' if left else f'ok, used to y={cy:.1f} ({ry0}..{ry1})'))
if overflow:
    print('PLACEMENT OVERFLOW:', overflow)
missing = set(fps) - placed
assert not missing, f'unplaced: {missing}'

for z in spec['zones']:
    zone = pcbnew.ZONE(b)
    zone.SetLayer(getattr(pcbnew, z['layer']))
    zone.SetNet(nets.get(z['net']) or nets['/' + z['net']])
    m = z.get('inset', 0.5)
    o = zone.Outline(); o.NewOutline()
    if circle and 'box' not in z:
        zr = cr - m
        pts = [(ccx + zr * math.cos(2 * math.pi * i / 72), ccy + zr * math.sin(2 * math.pi * i / 72)) for i in range(72)]
    else:
        zx0, zy0, zx1, zy1 = z.get('box', [x0 + m, y0 + m, x1 - m, y1 - m])
        pts = [(zx0, zy0), (zx1, zy0), (zx1, zy1), (zx0, zy1)]
    for px, py in pts:
        o.Append(MM(px), MM(py))
    zone.SetLocalClearance(MM(0.3)); zone.SetMinThickness(MM(0.25))
    zone.SetPadConnection(pcbnew.ZONE_CONNECTION_FULL if z.get('solid') else pcbnew.ZONE_CONNECTION_THERMAL)
    zone.SetAssignedPriority(z.get('priority', 0))
    zone.SetIslandRemovalMode(pcbnew.ISLAND_REMOVAL_MODE_ALWAYS)   # no floating copper islands
    b.Add(zone)
pcbnew.ZONE_FILLER(b).Fill(b.Zones())
pcbnew.SaveBoard(spec['out'], b)
print('saved', spec['out'], len(fps), 'footprints', len(nets), 'nets')
