#!/usr/bin/env python3
"""Pre-route the SELV signal nets of the FirebaseOTA carrier.

The EasyEDA autorouter (the workflow README_RevA.md prescribes) drops vias
and bottom-layer tracks with clearance smaller than the DRC rule, which is
what the "Hole to Track / Hole to TH Pad" errors after import are made of.
This script routes every non-mains multi-pad net ourselves, on both layers,
with margins that satisfy check_board_v2.py *and* EasyEDA's6.9 mil rule:

  * >= 0.5 mm to foreign pads (our track-pad rule)
  * >= 0.3 mm to foreign tracks and foreign via copper (track-track rule)
  * >= 1.0 mm to mounting holes / cut-outs / board edge
  * >= 8.0 mm to mains copper on BOTH layers (mains-to-SELV creepage;
    the autorouter does not know this rule at all)

Mains nets (AC_L / AC_L_F / AC_N / L1..L4) are never routed here - see the
L1-L4 note in README_RevA.md: there is no on-board path for L1..L4 that
keeps 8 mm from the SSR row's SELV pins, so those stay ratlines.

Congestion handling: the board has a few single-cell seams (e.g. the gap
east of J1's even pad column).  When a net cannot reach a target because a
*previously routed signal track* seals the pocket, that track is ripped up
and both nets are routed again (bounded retries; pre-existing copper is
never ripped).

Usage (pipeline order):
    python3 generate_easyeda_v2.py [--revb]
    python3 route_selv.py [src.json]          # in-place, refuses to re-route
    python3 check_board_v2.py [src.json]

Deterministic: fixed grid, fixed net order - rerunning reproduces the file
byte-for-byte from a fresh generate.
"""
from __future__ import annotations

import heapq
import json
import math
import os
import re
import sys

U = 1.0 / 0.254                 # canvas units per mm
HERE = os.path.dirname(os.path.abspath(__file__))
STEP = 0.254                    # routing grid, mm
TRACK_W = 0.254                 # signal track width, mm
VIA_D = 0.9                     # via pad diameter, mm (annulus0.2)
VIA_DRILL = 0.5                 # via drill, mm - EasyEDA DRC requires
                                # the hole to be0.5..10 mm
CLR_PAD = 0.5                   # track to foreign pad copper (check rule)
CLR_TRACK = 0.3                 # track to foreign track/via copper
CLR_HOLE = 1.0                  # track to mounting hole / cut-out / edge
HOLE2HOLE = 0.254                # drill to drill (file rule hole2Hole=1
                                 # -> x10 mil ->0.254 mm), net-agnostic
CLR_MAINS = 8.0                 # SELV to mains copper, both layers
VIA_COST = 12                   # grid cells
NARROW_W = 1.2                  # cells closer than this to a pad/hole cost
SSR_ZONE = 4.3                   # moulding zone carved open around SSR pads
NARROW_K = 6.0                  # extra A* cost per mm of tightness
MAX_ATTEMPTS = 12               # reroutes per net before giving up

MAINS_NETS = {"AC_L", "AC_L_F", "AC_N", "L1", "L2", "L3", "L4"}
# rail nets: routed first, never ripped (ripping them makes the big GND/5V
# trees churn and starves every other net's retry budget)
POWER_NETS = {"GND", "5V", "3V3", "5V_RAW"}


def u(mm: float) -> float:
    return round(mm * U, 3)


def u_up(mm: float) -> float:
    """Canvas value rounded UP: a via hole of exactly0.5 mm must not sink
    below EasyEDA's0.5..10 mm floor through0.984252->0.984 rounding."""
    import math as _m
    return _m.ceil(mm * U * 1000 - 1e-9) / 1000


def _pad_from_fields(f, ref="?", pkg=""):
    """Pad fields are identical in both dialects:
    PAD~shape~x~y~w~h~layer~net~pin~hole..."""
    return {
        "ref": ref, "num": f[8], "net": f[7], "pkg": pkg,
        "x": float(f[2]) / U, "y": float(f[3]) / U,
        "w": float(f[4]) / U, "h": float(f[5]) / U,
        "tht": f[6] == "11",
        "hr": (float(f[9]) / U if len(f) > 9 and f[9] else 0.0),
        "shape": f[1],
    }


def parse(doc):
    pads, tracks, holes, regions = [], [], [], []
    for s in doc["shape"]:
        if s.startswith("TRACK~"):
            f = s.split("~")
            nums = [float(v) / U for v in f[4].split()]
            pts = [(nums[i], nums[i + 1]) for i in range(0, len(nums) - 1, 2)]
            tracks.append({"layer": f[2], "net": f[3],
                           "w": float(f[1]) / U, "pts": pts,
                           "_shape": s})
        elif s.startswith("VIA~"):
            f = s.split("~")
            holes.append({"x": float(f[1]) / U, "y": float(f[2]) / U,
                          "r": float(f[5]) / U, "net": f[4], "via": True})
        elif s.startswith("HOLE~"):
            f = s.split("~")
            holes.append({"x": float(f[1]) / U, "y": float(f[2]) / U,
                          "r": float(f[3]) / U, "net": "", "via": False})
        elif s.startswith("SOLIDREGION~"):
            f = s.split("~")
            nums = [float(v) / U for v in f[3].split()]
            xs, ys = nums[0::2], nums[1::2]
            regions.append((min(xs), min(ys), max(xs), max(ys)))
        elif s.startswith("PAD~"):
            # flat dialect (platform pcb.json): PAD~shape~x~y~w~h~layer~net~pin...
            pads.append(_pad_from_fields(s.split("~"), ref="?"))
        elif s.startswith("LIB~"):
            ref = ""
            pkg = ""
            pm = re.search(r"package`([^`]+)", s.split("#@$")[0])
            if pm:
                pkg = pm.group(1)
            for c in s.split("#@$")[1:]:
                f = c.split("~")
                if f[0] == "TEXT" and f[1] == "P" and not ref:
                    ref = f[10] if len(f) > 10 else "?"
                elif f[0] == "PAD":
                    pads.append(_pad_from_fields(f, ref=ref, pkg=pkg))
            if pkg == "ESP32-WROOM-32E":
                lm = re.match(r"LIB~([-\d.]+)~([-\d.]+)", s)
                if lm:
                    # antenna keep-out band (KiCad/Espressif land pattern)
                    wx, wy = float(lm.group(1)) / U, float(lm.group(2)) / U
                    regions.append((wx - 9.0, wy - 15.74, wx + 9.0, wy - 9.8))
    return pads, tracks, holes, regions


class Router:
    def __init__(self, doc):
        self.doc = doc
        self.pads, self.tracks, self.holes, self.regions = parse(doc)
        self.nx = int(130 / STEP) + 1
        self.ny = int(70 / STEP) + 1
        self.max_gid = max(
            (int(m.group(1)) for s in doc["shape"]
             for m in [re.search(r"gge(\d+)$", s.split("~")[-1])] if m),
            default=0)
        self.new_shapes = []
        self.report = []
        self.last_fail = None
        self.history = {}       # cell -> congestion penalty (negotiated routing)
        self.rips = 0
        self.budget = 80000
        self.budget_boosts = {}
        self.budget_for = {}        # per-net budget (boosts must survive re-pop)
        # board edge + keep-out regions: identical for every net, build once
        self.edge = [self.blank(), self.blank()]
        self.edge_no_via = self.blank()
        for ix in range(self.nx):
            for iy in range(self.ny):
                if not self.inside_board(ix, iy):
                    self.edge[0][ix][iy] = self.edge[1][ix][iy] = True
        for (x0, y0, x1, y1) in self.regions:
            self.stamp_rect(self.edge[0], x0, y0, x1, y1, CLR_HOLE)
            self.stamp_rect(self.edge[1], x0, y0, x1, y1, CLR_HOLE)
            self.stamp_rect(self.edge_no_via, x0, y0, x1, y1,
                            CLR_HOLE + VIA_D / 2)
        # static width map (mm to the nearest pad/hole/mains obstacle):
        # used as a COST only - through-traffic prefers wide corridors so
        # the single-cell gates (e.g. east of J1's column) stay free for
        # the final approach of the nets that actually live there.
        self.width = self._build_width()

    def gid(self):
        self.max_gid += 1
        return f"gge{self.max_gid}"

    # ---------- rasterising helpers (mm -> grid) ----------
    def gx(self, x):
        return int(round(x / STEP))

    def inside_board(self, ix, iy):
        x, y = ix * STEP, iy * STEP
        # rounded rect130x70 r5, shrunk by CLR_HOLE (check only the
        # corner the cell actually sits in)
        m = CLR_HOLE
        if not (m <= x <= 130 - m and m <= y <= 70 - m):
            return False
        r = 5.0
        if x < r and y < r:
            return math.hypot(x - r, y - r) <= r - m
        if x > 130 - r and y < r:
            return math.hypot(x - (130 - r), y - r) <= r - m
        if x < r and y > 70 - r:
            return math.hypot(x - r, y - (70 - r)) <= r - m
        if x > 130 - r and y > 70 - r:
            return math.hypot(x - (130 - r), y - (70 - r)) <= r - m
        return True

    def stamp_circle(self, grid, cx, cy, r, val=True):
        if r <= 0:
            return
        i0, i1 = self.gx(cx - r), self.gx(cx + r)
        j0, j1 = self.gx(cy - r), self.gx(cy + r)
        r2 = r * r
        for ix in range(max(0, i0), min(self.nx, i1 + 1)):
            dx = ix * STEP - cx
            for iy in range(max(0, j0), min(self.ny, j1 + 1)):
                dy = iy * STEP - cy
                if dx * dx + dy * dy <= r2:
                    grid[ix][iy] = val

    def stamp_rect(self, grid, x0, y0, x1, y1, grow, val=True):
        i0, i1 = self.gx(x0 - grow), self.gx(x1 + grow)
        j0, j1 = self.gx(y0 - grow), self.gx(y1 + grow)
        for ix in range(max(0, i0), min(self.nx, i1 + 1)):
            for iy in range(max(0, j0), min(self.ny, j1 + 1)):
                grid[ix][iy] = val

    def stamp_track(self, grid, pts, w, grow, val=True):
        half = w / 2 + grow
        for a, b in zip(pts, pts[1:]):
            n = max(1, int(math.dist(a, b) / (STEP / 2)))
            for k in range(n + 1):
                t = k / n
                self.stamp_circle(grid, a[0] + (b[0] - a[0]) * t,
                                  a[1] + (b[1] - a[1]) * t, half, val)

    @staticmethod
    def seg_dist(p, a, b):
        ax, ay = a
        bx, by = b
        dx, dy = bx - ax, by - ay
        L = dx * dx + dy * dy
        if L == 0:
            return math.hypot(p[0] - ax, p[1] - ay)
        t = max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / L))
        return math.hypot(p[0] - (ax + t * dx), p[1] - (ay + t * dy))

    def blank(self):
        return [[False] * self.ny for _ in range(self.nx)]

    def _build_width(self):
        from collections import deque
        blocked, _ = self.build_masks("")   # everything foreign: cost model
        dist = [[-1] * self.ny for _ in range(self.nx)]
        dq = deque()
        for ix in range(self.nx):
            row_b, row_d = blocked[0][ix], dist[ix]
            for iy in range(self.ny):
                if row_b[iy]:
                    row_d[iy] = 0
                    dq.append((ix, iy))
        while dq:
            ix, iy = dq.popleft()
            d0 = dist[ix][iy]
            for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nx_, ny_ = ix + dx, iy + dy
                if (0 <= nx_ < self.nx and 0 <= ny_ < self.ny
                        and dist[nx_][ny_] < 0):
                    dist[nx_][ny_] = d0 + 1
                    dq.append((nx_, ny_))
        return [[d * STEP for d in row] for row in dist]

    def narrow_cost(self, cell):
        w = self.width[cell[0]][cell[1]]
        if w >= NARROW_W:
            return 0.0
        return (NARROW_W - w) * NARROW_K

    # ---------- per-net obstacle maps ----------
    def build_masks(self, net):
        """(blocked[2], no_via) for routing `net`. index0=top,1=bottom."""
        blocked = [[c[:] for c in layer] for layer in self.edge]
        no_via = [r[:] for r in self.edge_no_via]
        half = TRACK_W / 2

        # holes (mounting / cut-outs / vias) - both layers
        for h in self.holes:
            if h["net"] == net and h.get("via"):
                # own via: its copper may be reused, but a NEW via drill
                # must keep hole2Hole (EasyEDA checks it net-agnostically)
                self.stamp_circle(no_via, h["x"], h["y"],
                                  h["r"] + HOLE2HOLE + VIA_DRILL / 2 + half)
                continue
            g = CLR_HOLE if not h.get("via") else CLR_PAD
            r = h["r"] + g + half
            self.stamp_circle(blocked[0], h["x"], h["y"], r)
            self.stamp_circle(blocked[1], h["x"], h["y"], r)
            self.stamp_circle(no_via, h["x"], h["y"], r + VIA_D / 2)

        # pads: foreign = obstacle with clearance; own centre = reachable
        for p in self.pads:
            if p["net"] == net:
                if not p["tht"]:             # SMD: no via inside/near it
                    self.stamp_rect(no_via, p["x"] - p["w"] / 2,
                                    p["y"] - p["h"] / 2,
                                    p["x"] + p["w"] / 2, p["y"] + p["h"] / 2,
                                    VIA_D / 2 + 0.4)
                elif p["hr"]:
                    # own THT pad: copper stays reachable, but no new drill
                    # may land inside/next to the pad's own hole
                    self.stamp_circle(no_via, p["x"], p["y"],
                                      p["hr"] + HOLE2HOLE
                                      + VIA_DRILL / 2 + half)
                continue
            r = max(p["w"], p["h"]) / 2 + CLR_PAD + half
            self.stamp_circle(blocked[0], p["x"], p["y"], r)
            self.stamp_circle(blocked[1], p["x"], p["y"], r)
            self.stamp_circle(no_via, p["x"], p["y"], r + VIA_D / 2)
            if not p["tht"]:
                blocked[1][self.gx(p["x"])][self.gx(p["y"])] = True

        # existing tracks
        for t in self.tracks:
            if t["net"] == net:
                continue
            li = 0 if t["layer"] == "1" else 1 if t["layer"] == "2" else None
            if li is None:
                continue                     # silk / outline handled above
            g = CLR_MAINS if t["net"] in MAINS_NETS else CLR_TRACK
            self.stamp_track(blocked[li], t["pts"], t["w"], g + half)
            if t["net"] in MAINS_NETS:       # mains keep-out on both layers
                other = 1 - li
                self.stamp_track(blocked[other], t["pts"], t["w"],
                                 CLR_MAINS + half)
            self.stamp_track(no_via, t["pts"], t["w"], g + VIA_D / 2)

        # mains pads:8 mm halo on both layers
        for p in self.pads:
            if p["net"] not in MAINS_NETS or p["net"] == net:
                continue
            r = max(p["w"], p["h"]) / 2 + CLR_MAINS + half
            # the SSR module's own input pads (SSR_Kx_*) sit inside its
            # COM/NO halo by construction - the moulding is the barrier
            # (same exemption check_board_v2 applies to pads); skip them
            for q in self.pads:
                if q["net"] == net and q["net"].startswith("SSR_"):
                    if math.hypot(q["x"] - p["x"], q["y"] - p["y"]) < 7.0:
                        r = 0
                        break
            if r <= 0:
                continue
            self.stamp_circle(blocked[0], p["x"], p["y"], r)
            self.stamp_circle(blocked[1], p["x"], p["y"], r)
            self.stamp_circle(no_via, p["x"], p["y"], r + VIA_D / 2)

        # own pads: make the centre cell reachable on their layer(s).
        # SSR_* inputs sit inside their module's COM/NO halo by
        # construction (the moulding is the barrier - the same exemption
        # check_board_v2 applies to pads), so carve that zone open.
        carved = False
        for p in self.pads:
            if p["net"] != net:
                continue
            if p["net"].startswith("SSR_"):
                # val=False: CLEAR the halos inside the moulding zone
                # (the previous call stamped them - it sealed the pad!)
                self.stamp_circle(blocked[0], p["x"], p["y"], SSR_ZONE, False)
                self.stamp_circle(blocked[1], p["x"], p["y"], SSR_ZONE, False)
                carved = True
            for li in (0, 1) if p["tht"] else (0,):
                blocked[li][self.gx(p["x"])][self.gx(p["y"])] = False
        if carved:
            # the punch may only clear MAINS HALOS: restore every other
            # obstacle it crossed (neighbouring SSR pads, channel stubs,
            # holes, tracks) so the opened zone cannot short anything.
            for p in self.pads:
                if p["net"] == net or p["net"] in MAINS_NETS:
                    continue
                r = max(p["w"], p["h"]) / 2 + CLR_PAD + half
                self.stamp_circle(blocked[0], p["x"], p["y"], r)
                self.stamp_circle(blocked[1], p["x"], p["y"], r)
            for h in self.holes:
                if h["net"] == net and h.get("via"):
                    continue
                g = CLR_HOLE if not h.get("via") else CLR_PAD
                r = h["r"] + g + half
                self.stamp_circle(blocked[0], h["x"], h["y"], r)
                self.stamp_circle(blocked[1], h["x"], h["y"], r)
            for t in self.tracks:
                if t["net"] == net:
                    continue
                li = 0 if t["layer"] == "1" else 1 if t["layer"] == "2" else None
                if li is None:
                    continue
                g = CLR_MAINS if t["net"] in MAINS_NETS else CLR_TRACK
                self.stamp_track(blocked[li], t["pts"], t["w"], g + half)
                if t["net"] in MAINS_NETS:
                    self.stamp_track(blocked[1 - li], t["pts"], t["w"],
                                     CLR_MAINS + half)
        # ...but never onto a mains pad itself (re-block their discs after
        # the carve so a route cannot short into the mains moulding)
        for p in self.pads:
            if p["net"] not in MAINS_NETS:
                continue
            r = max(p["w"], p["h"]) / 2 + CLR_PAD + half
            self.stamp_circle(blocked[0], p["x"], p["y"], r)
            self.stamp_circle(blocked[1], p["x"], p["y"], r)
            self.stamp_circle(no_via, p["x"], p["y"], r + VIA_D / 2)
        return blocked, no_via

    # ---------- component bookkeeping ----------
    @staticmethod
    def gx_static(v):
        return int(round(v / STEP))

    @staticmethod
    def _pad_cell_ok(p, ix, iy):
        """True when the cell's centre lies INSIDE the pad's real shape.

        The bounding box is not enough: an ELLIPSE's bbox corners have no
        copper, so a path seeded there starts outside the pad and stops
        short of it (EasyEDA then reports the pad disconnected)."""
        cx, cy = ix * STEP, iy * STEP
        dx, dy = abs(cx - p["x"]), abs(cy - p["y"])
        if p.get("shape") == "RECT":
            return dx <= p["w"] / 2 and dy <= p["h"] / 2
        rx, ry = p["w"] / 2, p["h"] / 2
        if rx <= 0 or ry <= 0:
            return False
        return (dx / rx) ** 2 + (dy / ry) ** 2 <= 1.0

    @classmethod
    def _pad_cells_of(cls, p):
        out = set()
        i0, i1 = cls.gx_static(p["x"] - p["w"] / 2), cls.gx_static(p["x"] + p["w"] / 2)
        j0, j1 = cls.gx_static(p["y"] - p["h"] / 2), cls.gx_static(p["y"] + p["h"] / 2)
        for ix in range(i0, i1 + 1):
            for iy in range(j0, j1 + 1):
                if cls._pad_cell_ok(p, ix, iy):
                    for li in ((0, 1) if p["tht"] else (0,)):
                        out.add((ix, iy, li))
        return out

    def add_pad_to_comp(self, comp, p):
        comp.update(self._pad_cells_of(p))

    def track_cells(self, t):
        li = 0 if t["layer"] == "1" else 1 if t["layer"] == "2" else None
        if li is None:
            return []
        cells = []
        for a, b in zip(t["pts"], t["pts"][1:]):
            n = max(1, int(math.dist(a, b) / (STEP / 2)))
            for k in range(n + 1):
                f = k / n
                cells.append((self.gx(a[0] + (b[0] - a[0]) * f),
                              self.gx(a[1] + (b[1] - a[1]) * f), li))
        return cells

    # ---------- A* on (ix, iy, layer) ----------
    def dijkstra(self, blocked, no_via, comp, goal_xy, goal_tht):
        gx, gy = goal_xy
        if not (0 <= gx < self.nx and 0 <= gy < self.ny):
            return None
        dist = {}
        prev = {}
        pq = []
        counter = 0

        def h(ix, iy):
            return math.hypot(ix - gx, iy - gy)

        for s in comp:
            if blocked[s[2]][s[0]][s[1]]:
                continue
            dist[s] = 0
            heapq.heappush(pq, (h(s[0], s[1]), counter, s))
            counter += 1
        if not pq:
            return None
        seen = set()
        goal_node = None
        pops = 0
        BUDGET = self.budget
        while pq:
            f, _, node = heapq.heappop(pq)
            if node in seen:
                continue
            seen.add(node)
            pops += 1
            if pops > BUDGET:
                return None                    # give up (treated as blocked)
            ix, iy, li = node
            d = dist[node]
            if (ix, iy) == (gx, gy) and (goal_tht or li == 0):
                goal_node = node
                break
            for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nx_, ny_ = ix + dx, iy + dy
                if not (0 <= nx_ < self.nx and 0 <= ny_ < self.ny):
                    continue
                if blocked[li][nx_][ny_]:
                    continue
                n2 = (nx_, ny_, li)
                nd = (d + 1 + self.history.get(n2, 0)
                      + self.narrow_cost(n2))
                if nd < dist.get(n2, 1 << 60):
                    dist[n2] = nd
                    prev[n2] = node
                    heapq.heappush(pq, (nd + h(nx_, ny_), counter, n2))
                    counter += 1
            ol = 1 - li
            if (not blocked[ol][ix][iy] and not no_via[ix][iy]
                    and not blocked[li][ix][iy]):
                n2 = (ix, iy, ol)
                nd = d + VIA_COST + self.history.get(n2, 0)
                if nd < dist.get(n2, 1 << 60):
                    dist[n2] = nd
                    prev[n2] = node
                    heapq.heappush(pq, (nd + h(ix, iy), counter, n2))
                    counter += 1
        if goal_node is None:
            return None
        path = []
        node = goal_node
        while node is not None:
            path.append(node)
            node = prev.get(node)
        path.reverse()
        return path

    # ---------- per-net routing ----------
    def _components(self, cells):
        """Connected copper components (8-neighbour same layer; a layer
        change only where both layers have copper - i.e. at a via or a
        through-hole pad)."""
        cells = set(cells)
        seen = set()
        comps = []
        for start in sorted(cells):
            if start in seen:
                continue
            comp = {start}
            seen.add(start)
            stack = [start]
            while stack:
                ix, iy, li = stack.pop()
                #4-connectivity only: a diagonal corner touch has zero
                # copper overlap (EasyEDA would report it disconnected)
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    n = (ix + dx, iy + dy, li)
                    if n in cells and n not in seen:
                        seen.add(n)
                        comp.add(n)
                        stack.append(n)
                n = (ix, iy, 1 - li)
                if n in cells and n not in seen:
                    seen.add(n)
                    comp.add(n)
                    stack.append(n)
            comps.append(comp)
        return comps

    def _pad_cells(self, pads):
        out = set()
        for p in pads:
            out |= self._pad_cells_of(p)
        return out

    def route_net(self, net, pads):
        blocked, no_via = self.build_masks(net)
        copper = set()
        for t in self.tracks:
            if t["net"] == net:
                copper.update(self.track_cells(t))
        # Pad cells bridge their layers (THT); components are computed over
        # copper+own pads so a net that was split by a rip-up is seen as
        # SEPARATE islands - targets outside the seed island must be routed
        # again to rejoin it (the old code skipped them because "some comp
        # cell exists", which left nets fragmented while EasyEDA reported
        # "disconnected").
        islands = self._components(copper | self._pad_cells(pads))
        seed = max(islands, key=len) if islands else set()
        remaining = list(pads)
        if not seed:
            self.add_pad_to_comp(seed, remaining.pop(0))
        paths = []
        while remaining:
            target = remaining.pop(0)
            gx, gy = self.gx(target["x"]), self.gx(target["y"])
            if any((gx, gy, li) in seed
                   for li in ((0, 1) if target["tht"] else (0,))):
                self.add_pad_to_comp(seed, target)
                continue                      # already in the seed island
            path = self.dijkstra(blocked, no_via, seed, (gx, gy),
                                 target["tht"])
            if path is None:
                self.last_fail = target
                self.report.append((net, f"FAILED to reach {target['ref']}."
                                         f"{target['num']}"))
                return False
            paths.append(path)
            for node in path:
                seed.add(node)
            self.add_pad_to_comp(seed, target)
        if paths:
            self.emit(net, paths)
        self.report.append((net, f"routed {len(paths)} connection(s)"))
        return True

    def emit(self, net, paths):
        for path in paths:
            runs = []
            cur_layer = path[0][2]
            cur = [(path[0][0], path[0][1])]
            for node in path[1:]:
                if node[2] != cur_layer:
                    runs.append((cur_layer, cur, (node[0], node[1])))
                    cur_layer = node[2]
                    cur = [(node[0], node[1])]
                else:
                    cur.append((node[0], node[1]))
            runs.append((cur_layer, cur, None))
            prev_via = None
            for li, cells, via_at in runs:
                pts = [(round(ix * STEP, 3), round(iy * STEP, 3))
                       for ix, iy in cells]
                pts = self.simplify(pts)
                if prev_via is not None and pts:
                    pts = [prev_via] + pts
                if len(pts) >= 2:
                    shape = (f"TRACK~{u(TRACK_W)}~{1 if li == 0 else 2}~{net}~"
                             + " ".join(f"{u(x)} {u(y)}" for x, y in pts)
                             + f"~{self.gid()}")
                    self.new_shapes.append(shape)
                    self.tracks.append({"layer": "1" if li == 0 else "2",
                                        "net": net, "w": TRACK_W,
                                        "pts": list(pts), "_shape": shape,
                                        "_mine": True})
                if via_at is not None:
                    vx = round(via_at[0] * STEP, 3)
                    vy = round(via_at[1] * STEP, 3)
                    shape = (f"VIA~{u(vx)}~{u(vy)}~{u(VIA_D)}~{net}~"
                             f"{u_up(VIA_DRILL / 2)}~{self.gid()}")
                    self.new_shapes.append(shape)
                    self.holes.append({"x": vx, "y": vy, "r": VIA_DRILL / 2,
                                       "net": net, "via": True,
                                       "_shape": shape, "_mine": True})
                    prev_via = (vx, vy)
                else:
                    prev_via = None

    @staticmethod
    def simplify(pts):
        if len(pts) <= 2:
            return pts
        out = [pts[0]]
        for i in range(1, len(pts) - 1):
            ax, ay = out[-1]
            bx, by = pts[i]
            cx, cy = pts[i + 1]
            if (bx - ax) * (cy - ay) == (by - ay) * (cx - ax):
                continue                      # collinear: drop middle
            out.append(pts[i])
        out.append(pts[-1])
        return out

    # ---------- rip-up support ----------
    def find_blockers(self, net, pads, allow_power=False):
        """The single worst foreign signal track sealing a target's pocket."""
        target = self.last_fail
        if target is None:
            return set()
        blocked, no_via = self.build_masks(net)
        half = TRACK_W / 2
        while True:
            gx, gy = self.gx(target["x"]), self.gx(target["y"])
            # flood the pocket the goal sits in
            pocket = set()
            stack = []
            for li in ((0, 1) if target["tht"] else (0,)):
                if not blocked[li][gx][gy]:
                    stack.append((gx, gy, li))
            pocket.update(stack)
            while stack:
                ix, iy, li = stack.pop()
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    n2 = (ix + dx, iy + dy, li)
                    if (0 <= n2[0] < self.nx and 0 <= n2[1] < self.ny
                            and n2 not in pocket
                            and not blocked[li][n2[0]][n2[1]]):
                        pocket.add(n2)
                        stack.append(n2)
                n2 = (ix, iy, 1 - li)
                if (n2 not in pocket and not blocked[1 - li][ix][iy]
                        and not no_via[ix][iy]):
                    pocket.add(n2)
                    stack.append(n2)
            # boundary cells (free cell's blocked neighbours)
            boundary = set()
            for ix, iy, li in pocket:
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    n2 = (ix + dx, iy + dy, li)
                    if (0 <= n2[0] < self.nx and 0 <= n2[1] < self.ny
                            and n2 not in pocket
                            and blocked[li][n2[0]][n2[1]]):
                        boundary.add(n2)
            scores = {}
            for t in self.tracks:
                if t["net"] == net:
                    continue
                if t.get("layer") not in ("1", "2") or not t["net"]:
                    continue                   # outline/silk: not copper
                if t["net"] in MAINS_NETS:
                    continue                   # never rip mains copper
                if t["net"] in POWER_NETS and not allow_power:
                    continue                   # power last resort only
                reach = t["w"] / 2 + CLR_TRACK + half
                covered = 0
                for bx, iy, li in boundary:
                    p = (bx * STEP, iy * STEP)
                    if any(self.seg_dist(p, t["pts"][k], t["pts"][k + 1])
                           <= reach
                           for k in range(len(t["pts"]) - 1)):
                        covered += 1
                if covered:
                    scores[t["net"]] = scores.get(t["net"], 0) + covered
            if not scores:
                return set()
            # one rip per failure: the track that seals the most boundary
            return {max(scores, key=scores.get)}

    def rip(self, nets):
        rm = set()
        keep = []
        for t in self.tracks:
            # mains copper is never ripped; pre-existing SELV stubs and
            # power trees ARE rip-able as a last resort (they are always
            # re-queued and rerouted; verification refuses to save unless
            # every pad reconnects)
            if (t["net"] in nets and t["net"] not in MAINS_NETS
                    and t.get("layer") in ("1", "2") and t.get("_shape")):
                rm.add(t["_shape"])
                for cell in self.track_cells(t):
                    self.history[cell] = self.history.get(cell, 0) + 2
            else:
                keep.append(t)
        self.tracks = keep
        keep_h = []
        for h in self.holes:
            if h.get("_mine") and h["net"] in nets:
                rm.add(h["_shape"])
            else:
                keep_h.append(h)
        self.holes = keep_h
        self.new_shapes = [s for s in self.new_shapes if s not in rm]
        self.doc["shape"] = [s for s in self.doc["shape"] if s not in rm]
        self.rips += 1
        self.report.append((", ".join(sorted(nets)),
                            f"ripped up to clear a passage ({len(rm)} shapes)"))
        return len(rm)

    # ---------- driver ----------
    def run(self):
        nets = {}
        for p in self.pads:
            if p["net"] and p["net"] not in MAINS_NETS:
                nets.setdefault(p["net"], []).append(p)
        route_nets = {n: ps for n, ps in nets.items() if len(ps) >= 2}
        order = sorted(route_nets, key=lambda n: (len(route_nets[n]), n))
        order = ([n for n in order if n in POWER_NETS]
                 + [n for n in order if n not in POWER_NETS])
        queue = list(order)
        attempts = {}
        fails = {}
        permanent = set()
        guard = 0
        while queue and guard < 900:
            guard += 1
            net = queue.pop(0)
            if net in permanent or net not in route_nets:
                continue
            attempts[net] = attempts.get(net, 0) + 1
            self.budget = self.budget_for.get(net, 120000)
            if attempts[net] > MAX_ATTEMPTS:
                permanent.add(net)
                self.report.append((net, "PERMANENTLY BLOCKED (retry cap)"))
                continue
            if self.route_net(net, route_nets[net]):
                attempts[net] = 0    # success refunds the retry budget
                fails.pop(net, None)
                self.budget_for.pop(net, None)
                self.budget_boosts.pop(net, None)
                continue
            fails[net] = fails.get(net, 0) + 1
            if self.rips >= 300:
                permanent.add(net)
                self.report.append((net, "rip budget exhausted"))
                continue
            # flood analysis shows most "failures" are search-budget
            # aborts (an open path exists) - boost the budget FIRST and
            # only start ripping once two boosts did not help. The boost
            # must live in budget_for: self.budget is re-read on every
            # queue pop, so mutating it here was a no-op before.
            boosts = self.budget_boosts.get(net, 0)
            if boosts < 1:
                self.budget_boosts[net] = boosts + 1
                self.budget_for[net] = self.budget_for.get(net, 120000) * 4
                queue.insert(0, net)
                self.report.append(
                    (net, f"retrying with bigger search budget "
                          f"({self.budget_for[net] // 1000}k)"))
                continue
            # two failures on the same net: the seal is probably a power
            # track (GND trunk /5V tree) - allow ripping it from then on
            blockers = self.find_blockers(
                net, route_nets[net], allow_power=fails[net] >= 2)
            if not blockers:
                blockers = self.find_blockers(net, route_nets[net],
                                              allow_power=True)
            if not blockers:
                permanent.add(net)            # pre-existing copper walls it
                self.report.append((net, "no rip-able blocker found"))
                continue
            self.rip(blockers)
            # the failed net re-runs FIRST and claims the freed passage;
            # the blocker re-routes later, pushed off its old path by the
            # history penalty accumulated during the rip.
            queue.insert(0, net)
            for b in sorted(blockers):
                if b not in permanent:
                    attempts[b] = 0            # ripped = fresh start
                    queue.append(b)
        # anything ripped must have been re-routed when re-queued; verify
        routed_ok = not permanent
        for net in sorted(route_nets):
            copper = set()
            for t in self.tracks:
                if t["net"] == net:
                    copper.update(self.track_cells(t))
            comps = self._components(copper | self._pad_cells(route_nets[net]))
            if len(comps) != 1:
                routed_ok = False
                if net not in permanent:
                    self.report.append(
                        (net, f"INCOMPLETE: {len(comps)} separate copper "
                              f"islands (EasyEDA would flag these)"))
        if self.new_shapes:
            self.doc["shape"].extend(self.new_shapes)
        return routed_ok


def route_doc(doc):
    """Route every non-mains multi-pad net of `doc` in place.

    Library API (used by the platform's student.py for pcb.json).
    Returns (ok, report, n_tracks, n_vias).
    """
    r = Router(doc)
    ok = r.run()
    n_tr = sum(1 for s in r.new_shapes if s.startswith("TRACK~"))
    n_via = sum(1 for s in r.new_shapes if s.startswith("VIA~"))
    return ok, r.report, n_tr, n_via


def main():
    src = (sys.argv[1] if len(sys.argv) > 1
           else os.path.join(HERE, "FirebaseOTA_3x6_RevA_easyeda.json"))
    if not os.path.isabs(src):
        src = os.path.join(HERE, src)
    with open(src, encoding="utf-8") as fh:
        doc = json.load(fh)
    if any(isinstance(s, str) and s.startswith("TRACK~")
           and s.split("~")[3] not in ("", "AC_L", "AC_L_F", "AC_N")
           and s.split("~")[3] not in ("SSR_K1_AN", "SSR_K1_CAT", "SSR_K2_AN",
                                       "SSR_K2_CAT", "SSR_K3_AN", "SSR_K3_CAT",
                                       "SSR_K4_AN", "SSR_K4_CAT", "5V_RAW",
                                       "5V", "GND", "10", "")
           for s in doc["shape"]):
        print("refusing: file already contains routed signal nets")
        sys.exit(1)
    ok, report, n_tr, n_via = route_doc(doc)
    for net, msg in report:
        print(f"  {net:16} {msg}")
    print(f"{os.path.basename(src)}: +{n_tr} tracks, +{n_via} vias "
          f"({'all nets routed' if ok else 'INCOMPLETE'})")
    if not ok:
        print("NOT saved (regenerate first if this was a partial run)")
        sys.exit(1)
    with open(src, "w", encoding="utf-8") as fh:
        json.dump(doc, fh, indent=2, ensure_ascii=False)
    print("saved")


if __name__ == "__main__":
    main()
