from pathlib import Path
import json,math,re,csv,sys
R=Path(__file__).resolve().parent;c=json.loads((R/'curve_source.json').read_text());rows=[]
a,b,cc,d=c['forward_coefficients']
for tc in range(125,-41,-1):
 k=tc+273.15;ohm=c['R25_ohm']*math.exp(a+b/k+cc/k**2+d/k**3)
 raw=round(4095*ohm/(10000+ohm));rows.append((raw,tc*100,ohm))
assert len({x[0] for x in rows})==166 and all(a[0]<b[0] for a,b in zip(rows,rows[1:]))
p=R/'firmware/固件/lamp_target/src/lamp_ntc.c';s=p.read_text()
array='static const point curve[]={\n'+''.join(f'    {{{raw}u,{temp}}},\n' for raw,temp,ohm in rows)+'};'
generated=re.sub(r'static const point curve\[\]=\{.*?\};',lambda m:array,s,flags=re.S)
if '--check' in sys.argv:
 assert generated==s,'curve differs from manufacturer-coefficient generator'
 with (R/'nominal_curve.csv').open() as f:stored=list(csv.DictReader(f))
 assert len(stored)==len(rows)
 for old,(raw,temp,ohm) in zip(stored,rows):
  assert int(old['ADC_raw_rounded'])==raw and int(old['temperature_centiC'])==temp and abs(float(old['nominal_ohm_from_manufacturer_equation'])-ohm)<1e-8
 print('PASS:166 curve knots reproduce from stored manufacturer coefficients')
else:
 p.write_text(generated)
 with (R/'nominal_curve.csv').open('w',newline='') as f:
  w=csv.writer(f);w.writerow(['ADC_raw_rounded','temperature_centiC','nominal_ohm_from_manufacturer_equation']);w.writerows(rows)
