main
John Lauer Land and record reviewed diode vias; reject colliding heatsink mounting pattern f197072
"""Reject proposed mount drills against existing tracks/vias and conservative pad envelopes.

This read-only screen excludes pours (which require native refill) and is not DRC.
"""
import hashlib
import json
import math
from pathlib import Path

from shapely.geometry import LineString, Point
import sexp

root = Path(__file__).resolve().parents[1]
board = root / 'kicad/adom-custom-electronic-load.kicad_pcb'
tree = sexp.parse(board.read_text())
holes = [(120, 53), (153, 53), (120, 86), (153, 86)]
obstacles = []
for segment in sexp.find(tree, 'segment'):
    points = [tuple(map(float, sexp.first(segment, key)[1:3])) for key in ('start', 'end')]
    shape = LineString(points).buffer(float(sexp.first(segment, 'width')[1]) / 2)
    obstacles.append(('track', str(sexp.first(segment, 'net')[1]), shape))
for via in sexp.find(tree, 'via'):
    shape = Point(*map(float, sexp.first(via, 'at')[1:3])).buffer(float(sexp.first(via, 'size')[1]) / 2)
    obstacles.append(('via', str(sexp.first(via, 'net')[1]), shape))
for fp in sexp.find(tree, 'footprint'):
    ref = next(p[2] for p in sexp.find(fp, 'property') if p[1] == 'Reference')
    at = list(map(float, sexp.first(fp, 'at')[1:]))
    angle = math.radians(at[2] if len(at) > 2 else 0)
    for pad in sexp.find(fp, 'pad'):
        x, y = map(float, sexp.first(pad, 'at')[1:3])
        px = at[0] + x * math.cos(angle) + y * math.sin(angle)
        py = at[1] - x * math.sin(angle) + y * math.cos(angle)
        width, height = map(float, sexp.first(pad, 'size')[1:3])
        # Circumscribed circle deliberately over-rejects rectangular/oval pads.
        shape = Point(px, py).buffer(math.hypot(width, height) / 2)
        obstacles.append(('pad-envelope', f'{ref}.{pad[1]}', shape))
rows = []
for x, y in holes:
    conflicts = []
    for kind, label, shape in obstacles:
        clearance = Point(x, y).distance(shape) - 1.35
        if clearance < .25:
            conflicts.append({'kind': kind, 'label': label, 'clearanceMm': round(clearance, 4)})
    rows.append({'centerMm': [x, y], 'conflicts': conflicts})
report = {
    'boardSha256': hashlib.sha256(board.read_bytes()).hexdigest(),
    'sinkXY': [116.5, 49.5, 156.5, 89.5],
    'assumedHardwareDiameterMm': 5, 'assumedDrillDiameterMm': 2.7,
    'assumedCopperClearanceMm': .25,
    'status': 'rejected' if any(r['conflicts'] for r in rows) else 'requires-native-review',
    'holes': rows,
    'limitations': ['Candidate hardware not selected', 'Pad circles are conservative',
                    'Pours, copper graphics, slots and arcs not included; native DRC still required',
                    'No board geometry changed; no thermal or mechanical qualification'],
}
(root / 'mechanical/cooling-drill-screen.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))