#!/usr/bin/env python3
import argparse, hashlib, json, math, sys

def tokenize(text):
    i, n = 0, len(text)
    while i < n:
        c = text[i]
        if c.isspace():
            i += 1
            continue
        if c in "()":
            yield c
            i += 1
            continue
        if c == '"':
            i += 1
            out = []
            while i < n:
                c = text[i]
                if c == '"':
                    i += 1
                    break
                if c == "\\" and i + 1 < n:
                    out.append(text[i + 1])
                    i += 2
                else:
                    out.append(c)
                    i += 1
            else:
                raise ValueError("unterminated string")
            yield ("ATOM", "".join(out))
            continue
        j = i
        while j < n and (not text[j].isspace()) and text[j] not in "()":
            j += 1
        yield ("ATOM", text[i:j])
        i = j

def parse(text):
    stack, root = [], None
    for tok in tokenize(text):
        if tok == "(":
            node = []
            if stack:
                stack[-1].append(node)
            stack.append(node)
        elif tok == ")":
            if not stack:
                raise ValueError("unexpected close")
            node = stack.pop()
            if not stack:
                if root is not None:
                    raise ValueError("multiple top-level forms")
                root = node
        else:
            if not stack:
                raise ValueError("atom outside list")
            stack[-1].append(tok[1])
    if stack:
        raise ValueError("unclosed list")
    if root is None:
        raise ValueError("empty file")
    return root

def head(node):
    return node[0] if isinstance(node, list) and node and isinstance(node[0], str) else None

def child(node, name):
    if not isinstance(node, list):
        return None
    for x in node[1:]:
        if isinstance(x, list) and head(x) == name:
            return x
    return None

def scalar(node, name):
    x = child(node, name)
    return x[1] if x is not None and len(x) > 1 and isinstance(x[1], str) else None

def number(v):
    try:
        x = float(v)
        return x if math.isfinite(x) else None
    except Exception:
        return None

def metric(values):
    xs = sorted(x for x in values if x is not None)
    if not xs:
        return {"count": 0, "min": None, "max": None, "unique": []}
    uniq = []
    for x in xs:
        if not uniq or abs(x - uniq[-1]) > 1e-12:
            uniq.append(x)
    return {"count": len(xs), "min": xs[0], "max": xs[-1], "unique": uniq[:128]}

def main():
    ap = argparse.ArgumentParser(description="Deterministic structural probe for KiCad PCB files")
    ap.add_argument("board")
    ap.add_argument("--pretty", action="store_true")
    ns = ap.parse_args()
    data = open(ns.board, "rb").read()
    try:
        text = data.decode("utf-8")
    except UnicodeDecodeError as e:
        raise SystemExit("UTF-8 decode failed: %s" % e)
    root = parse(text)
    if head(root) != "kicad_pcb":
        raise SystemExit("not a kicad_pcb root")

    layers_node = child(root, "layers")
    layers = []
    if layers_node:
        for x in layers_node[1:]:
            if isinstance(x, list) and len(x) >= 3:
                layers.append({"id": x[0], "name": x[1], "type": x[2]})
    copper_layers = [x["name"] for x in layers if isinstance(x.get("name"), str) and x["name"].endswith(".Cu")]

    nets, widths, via_sizes, via_drills = [], [], [], []
    footprints = segments = vias = zones = 0

    for x in root[1:]:
        h = head(x)
        if h == "net" and len(x) >= 3:
            nets.append(str(x[2]))
        elif h in ("footprint", "module"):
            footprints += 1
        elif h == "segment":
            segments += 1
            widths.append(number(scalar(x, "width")))
        elif h == "via":
            vias += 1
            via_sizes.append(number(scalar(x, "size")))
            d = child(x, "drill")
            if d is not None and len(d) > 1:
                via_drills.append(number(d[1]))
        elif h == "zone":
            zones += 1

    result = {
        "schema": "deadbyte.kicad-pcb-probe.v1",
        "path": ns.board,
        "sha256": hashlib.sha256(data).hexdigest(),
        "bytes": len(data),
        "kicad": {"version": scalar(root, "version"), "generator": scalar(root, "generator")},
        "layers": layers,
        "copper_layers": copper_layers,
        "copper_layer_count": len(copper_layers),
        "nets": sorted(set(nets)),
        "counts": {"footprints": footprints, "segments": segments, "vias": vias, "zones": zones},
        "track_width_mm": metric(widths),
        "via_diameter_mm": metric(via_sizes),
        "via_drill_mm": metric(via_drills)
    }
    json.dump(result, sys.stdout, indent=2 if ns.pretty else None, sort_keys=True)
    sys.stdout.write("\n")

if __name__ == "__main__":
    main()
