import re
import sys


def parse_sexp(string):
    """Simple s-expression parser."""
    sexp = [[]]
    word = ""
    in_str = False
    for char in string:
        if char == '"':
            in_str = not in_str
            word += char
        elif in_str:
            word += char
        elif char == "(":
            sexp.append([])
        elif char == ")":
            if word:
                sexp[-1].append(word)
                word = ""
            temp = sexp.pop()
            sexp[-1].append(temp)
        elif char in (" ", "\n", "\t", "\r"):
            if word:
                sexp[-1].append(word)
                word = ""
        else:
            word += char
    return sexp[0][0]


with open("boardloaf-he/netlist_fixed.xml", "r") as f:
    data = f.read()

parsed = parse_sexp(data)

components = {}
nets = {}

# parsed is roughly: ['export', ['version', '...'], ['design', ...], ['components', ['comp', ...]], ['nets', ['net', ...]]]
for item in parsed:
    if not isinstance(item, list):
        continue

    if item[0] == "components":
        for comp in item[1:]:
            if comp[0] == "comp":
                ref = ""
                value = ""
                footprint = ""
                for attr in comp[1:]:
                    if attr[0] == "ref":
                        ref = attr[1].strip('"')
                    elif attr[0] == "value":
                        value = attr[1].strip('"')
                    elif attr[0] == "footprint":
                        footprint = attr[1].strip('"')
                components[ref] = {"value": value, "footprint": footprint, "nets": {}}

    elif item[0] == "nets":
        for net in item[1:]:
            if net[0] == "net":
                net_name = ""
                for attr in net[1:]:
                    if attr[0] == "name":
                        net_name = attr[1].strip('"')
                for attr in net[1:]:
                    if attr[0] == "node":
                        ref = ""
                        pin = ""
                        for n_attr in attr[1:]:
                            if n_attr[0] == "ref":
                                ref = n_attr[1].strip('"')
                            elif n_attr[0] == "pin":
                                pin = n_attr[1].strip('"')
                        if ref in components:
                            components[ref]["nets"][pin] = net_name

for ref, data in components.items():
    if "RP2040" in data["value"] or "RP2040" in data["footprint"] or ref == "U1":
        print(f"--- MCU: {ref} ---")
        for pin, net in data["nets"].items():
            if "unconnected" not in net:
                print(f"  Pin {pin}: {net}")

    if "74HC4051" in data["value"] or "74HC4051" in data["footprint"]:
        print(f"--- MUX: {ref} ---")
        for pin, net in data["nets"].items():
            print(f"  Pin {pin}: {net}")

    if "SLSS49E" in data["value"] or "SS49E" in data["value"] or ref.startswith("SW"):
        # Check first SW just to see its pins
        if ref in ("SW1", "SW2"):
            print(f"--- Sensor: {ref} ---")
            for pin, net in data["nets"].items():
                print(f"  Pin {pin}: {net}")

print("--- Sensor Power Check ---")
sw_issues = []
for ref, data in components.items():
    if ref.startswith("SW"):
        # In typical SOT23 SS49E, Pin 1=VCC, Pin 2=GND, Pin 3=OUT or similar
        # We need to verify what this footprint expects. Let's print all SW net connections
        pins = data["nets"]
        vcc = False
        gnd = False
        for p, n in pins.items():
            if n == "+3V3":
                vcc = True
            if n == "GND":
                gnd = True
        if not (vcc and gnd):
            sw_issues.append((ref, pins))
if not sw_issues:
    print("All SW components have +3V3 and GND connected.")
else:
    print("SW components missing proper power:", sw_issues)
