from pathlib import Path
import shutil,subprocess
R=Path(__file__).resolve().parent;B=R.parent;T=R/'firmware/固件/lamp_target';C=R/'firmware/固件/lamp_control';O=R/'host_test';O.mkdir(exist_ok=True)
shutil.copy2(R/'test_support/registers.h',O/'registers.h')
(O/'stm32g0xx.h').write_text('''#include "registers.h"
#undef GPIOA
#undef GPIOB
#undef GPIOC
#undef RCC
extern GPIO_TypeDef a,b,c;
extern RCC_TypeDef r;
#define GPIOA (&a)
#define GPIOB (&b)
#define GPIOC (&c)
#define RCC (&r)
#define __DSB() ((void)0)
''')
flags=['cc','-std=c11','-Wall','-Wextra','-Werror','-pedantic','-fsanitize=address,undefined','-g','-I'+str(O),'-I'+str(T/'include'),'-I'+str(C)]
subprocess.run(flags+[str(R/'test_ir_target.c'),str(T/'src/lamp_board_inputs.c'),str(T/'src/lamp_ir_filter.c'),str(C/'lamp_guard.c'),'-o',str(O/'test_ir_target')],check=True)
x=subprocess.run([str(O/'test_ir_target')],capture_output=True,text=True);(R/'IR_target_test.log').write_text(x.stdout+x.stderr);assert x.returncode==0,x.stderr;print(x.stdout)
# Synthetic wrong-pin control: verifies the tests reject PC14 being sampled
# instead of the A39 physical pad3 PC15. It is not a historical A37 binary.
s=(T/'src/lamp_board_inputs.c').read_text();needle='GPIOC->IDR & (1u<<15u)';assert needle in s
wrong=O/'wrong_PC14_sampler.c';wrong.write_text(s.replace(needle,'GPIOC->IDR & (1u<<14u)'))
subprocess.run(flags+[str(R/'test_ir_target.c'),str(wrong),str(T/'src/lamp_ir_filter.c'),str(C/'lamp_guard.c'),'-o',str(O/'test_wrong_pin')],check=True)
x=subprocess.run([str(O/'test_wrong_pin')],capture_output=True,text=True);assert x.returncode!=0 and 's.infrared_gpio_available && s.infrared_raw_high' in x.stderr,x.stderr
(R/'wrong_pin_negative.log').write_text('PASS: synthetic wrong-PC14 sampler rejected by physical PC15 raw-input assertion.\n'+x.stderr)
print('PASS: wrong-PC14 negative control rejected')
