from pathlib import Path
import shutil,sys,re,uuid,json
ROOT=Path(__file__).resolve().parent;B=ROOT.parent;SRC=ROOT/'verification_support/baseline';D=ROOT/'cad';D.mkdir(exist_ok=True)
sys.path.insert(0,str(ROOT/'verification_support'));from sexpr_forms import forms
stem='vacuum_control_evt_a5_logic_fet'
for name in [stem+'.kicad_pcb',stem+'.kicad_pro','Project.kicad_sym','sym-lib-table','fp-lib-table']:
 shutil.copy2(SRC/name,D/name)
for name in ['Vacuum_ESD.pretty','Vacuum_Shunt.pretty']:shutil.copytree(SRC/name,D/name,dirs_exist_ok=True)
s=(SRC/(stem+'.kicad_sch')).read_text()
for a,z,q in reversed(list(forms(s,'no_connect'))):
 if any('(at '+xy+')' in q for xy in ['704.85 110.49','704.85 113.03']):s=s[:a]+s[z:]
uid=str(uuid.uuid4());sheet='36ea6bd2-28ac-4378-9434-a0200a156ee5'
j=next(q for a,z,q in forms(s,'symbol') if '(lib_id ' in q and '(property "Reference" "J2"' in q)
j=j.replace('"J2"','"J5"').replace('4-WIRE PWM FAN','PANEL I2C 3V3 ONLY').replace('66c4fc12-58bb-4cf5-9441-fdcaf05448c5',uid)
# Move all instance/property positions together to isolated schematic area.
def move(m):return '(at %.2f %.2f %s)'%(float(m[1])+177.8,float(m[2])+101.6,float(m[3]))
j=re.sub(r'\(at\s+(-?[\d.]+)\s+(-?[\d.]+)\s+([\d.]+)\)',move,j)
def label(name,x,y):return '(label '+json.dumps(name)+' (at %.2f %.2f 0) (effects (font (size 1 1)) (justify left bottom)) (uuid "%s"))'%(x,y,uuid.uuid4())
extra=[j,label('PANEL_SCL',704.85,110.49),label('PANEL_SDA',704.85,113.03)]
for name,y in [('CTRL_3V3',196.85),('GND',201.93),('PANEL_SCL',207.01),('PANEL_SDA',212.09)]:extra.append(label(name,1092.2,y))
s=s.rstrip()[:-1]+'\n'+'\n'.join(extra)+'\n)\n'
s=s.replace('No sample/operation guide: J3 panel pins are configurable placeholders. Do not assume button count, speed steps, or display behavior.','A106: J3 KEY_IN=power key; USER_ADC=external plus/minus resistor ladder. J5=3V3/GND/software-I2C SCL(PA6)/SDA(PA7). Three-key/four-level behavior from D1 manual; display and fan profile remain unverified.')
# J5 uses an exact local 1.2mm-drill header footprint.
j_start=next((a,z) for a,z,q in forms(s,'symbol') if '(lib_id ' in q and '(property "Reference" "J5"' in q)
a,z=j_start
q=s[a:z].replace('Connector_PinHeader_2.54mm:PinHeader_1x04_P2.54mm_Vertical','Vacuum_Panel:PinHeader_1x04_P2.54mm_Drill1.2')
s=s[:a]+q+s[z:]
(D/(stem+'.kicad_sch')).write_text(s)
libdir=D/'Vacuum_Panel.pretty';libdir.mkdir(exist_ok=True)
fp=Path('/Applications/KiCad/KiCad.app/Contents/SharedSupport/footprints/Connector_PinHeader_2.54mm.pretty/PinHeader_1x04_P2.54mm_Vertical.kicad_mod').read_text().replace('(footprint "PinHeader_1x04_P2.54mm_Vertical"','(footprint "PinHeader_1x04_P2.54mm_Drill1.2"').replace('(drill 1)','(drill 1.2)')
(libdir/'PinHeader_1x04_P2.54mm_Drill1.2.kicad_mod').write_text(fp)
fpt=D/'fp-lib-table';q=fpt.read_text();q=q.rstrip()[:-1]+' (lib (name "Vacuum_Panel") (type "KiCad") (uri "${KIPRJMOD}/Vacuum_Panel.pretty") (options "") (descr "A106 exact header")))\n';fpt.write_text(q)

(ROOT/'schematic_change.json').write_text(json.dumps({'J5_uuid':uid,'sheet_uuid':sheet,'source_stem':stem,'J5_pin_nets':['/CTRL_3V3','/GND','/PANEL_SCL','/PANEL_SDA'],'MCU_pin13':'/PANEL_SCL','MCU_pin14':'/PANEL_SDA'},indent=2)+'\n')
