import re


def fix_pcb():
    with open("boardloaf-he/boardloafhe.kicad_pcb", "r") as f:
        pcb = f.read()

    # Replace Net-(DX-A) with Net-(SWX-VOUT)
    for i in range(1, 19):
        old_net = f"Net-(D{i}-A)"
        new_net = f"Net-(SW{i}-VOUT)"
        pcb = pcb.replace(f'"{old_net}"', f'"{new_net}"')

    with open("boardloaf-he/boardloafhe.kicad_pcb", "w") as f:
        f.write(pcb)


def fix_sch():
    with open("boardloaf-he/boardloafhe.kicad_sch", "r") as f:
        sch = f.read()

    # Rename the second SW3 to SW4
    # The second one is at y=101.346

    # We can just look for the block containing SW3 and 101.346
    parts = sch.split('(symbol (lib_id "project-specific-symbols:SLSS49E")')
    for idx, part in enumerate(parts):
        if 'Reference" "SW3"' in part and "101.346" in part:
            parts[idx] = part.replace('Reference" "SW3"', 'Reference" "SW4"')
            parts[idx] = parts[idx].replace('(reference "SW3")', '(reference "SW4")')

    sch = '(symbol (lib_id "project-specific-symbols:SLSS49E")'.join(parts)

    # Merge +3V3 and VCC
    sch = sch.replace("power:+3V3", "power:VCC")
    sch = sch.replace('"+3V3"', '"VCC"')
    sch = sch.replace('"+3V3_0_1"', '"VCC_0_1"')
    sch = sch.replace('"+3V3_1_1"', '"VCC_1_1"')

    with open("boardloaf-he/boardloafhe.kicad_sch", "w") as f:
        f.write(sch)


fix_pcb()
fix_sch()
print("Fixed files.")
