from pathlib import Path
import json,csv,math
from openpyxl import load_workbook
from openpyxl.styles import Font,PatternFill,Alignment
p=Path(__file__).parent
truth=json.loads((p/'duty_cycles.json').read_text());profile=json.loads((p/'profile.json').read_text());duty={'R':113,'G':0,'B':0,'W':142};assert sum(duty.values())==255
measurement={'target_CCT_K':1800,'actual_CCT_K':1798,'xy_measured':{'x':.549,'y':.4077},'duty_measured':duty,'source':'User Discord message 1564554639204941895','recorded_at':'2026-10-27T08:21:34.006Z','driver_and_measurement_conditions':'not independently recorded; retain user-provided result','status':'measured recipe for near-1800K output, no tolerance specification or CRI/R9 validation'}
(p/'measured_1800_confirmed.json').write_text(json.dumps(measurement,ensure_ascii=False,indent=2))
# Keep observed CCT distinct from requested target; do not mislabel a 1613K trial as an 1800K success.
profile['measured']=[{'cct':1798,'target_cct':1800,'duty_measured':duty,'xy_measured':measurement['xy_measured'],'source_message_id':'1564554639204941895'}]
profile['notes']=[v for v in profile['notes'] if 'Theory only' not in v]
profile['notes'].append('One measured recipe: target1800K, measured1798K, dutyR113 G0 B0 W142, xy0.5490/0.4077. Other12 nodes remain theoretical; no global bias fit applied.')
(p/'profile.json').write_text(json.dumps(profile,ensure_ascii=False,indent=2))
base=p/'PR3838NB_RGBW_13CCT_20261027.xlsx';out=p/'PR3838NB_RGBW_1800_Measured_Update_20261027.xlsx';w=load_workbook(base)
for row in w['修正值'].iter_rows(min_row=2):
 if row[0].value==1800:
  for i,c in enumerate(['R','G','B','W'],1):row[i].value=duty[c]
  row[5].value=255;row[6].value='用户实测配比：1798K，x0.5490/y0.4077；目标档1800K'
for row in w['百分比'].iter_rows(min_row=2):
 if row[0].value==1800:
  for i,c in enumerate(['R','G','B','W'],1):row[i].value=duty[c];row[i+5].value=duty[c]/255
  row[10].value='用户实测：1798K；此行为实测配比，其余理论估算'
notes=w['说明']
for row in notes.iter_rows(min_row=2):
 if row[0].value=='理论与修正':row[1].value='1800K档采用用户实测R113/G0/B0/W142，实测1798K、x0.5490/y0.4077；其余12档保持原理论值，不用单点外推整条曲线。计算值页保留原均衡策略理论配比。'
 if row[0].value=='色域':row[1].value='原理论13个目标在连续模型色域内；此结论描述理论可达性。新增1800档有用户实测坐标与1798K记录，未指定验收容差，不能据此作其他档位或其他条件的精度保证。'
 if row[0].value=='独立复核':row[1].value='独立复核页核对原理论均衡策略，非新增实测R113/G0/B0/W142的配方证明。新增实测与理论多解策略可以不同。'
 if row[0].value=='数值误差':row[1].value='独立复核页的误差是原理论模型值，非实测误差。本次新增实测1798K相对目标1800K低2K；x/y原始值如实记录，不自动声明符合某一公差。'
notes.append(['实测分配','1800档G/B为0，按用户真实配比保留，不强制四通道都非零。其余档未据此改成仅RW混光。'])
me=w.create_sheet('混光实测记录',1);me.append(['目标档/K','实际色温/K','R','G','B','W','合计','实测x','实测y','色温差/K','说明']);me.append([1800,1798,113,0,0,142,255,.549,.4077,-2,'用户实测，未声明驱动条件、公差或Ra/R9'])
compare=w['偏差分析'];compare.append(['本次新增实测点单独见“混光实测记录”；未对其他12档做偏差拟合。'])
for sheet in [me]:
 sheet.freeze_panes='A2';sheet.auto_filter.ref=sheet.dimensions
 for c in sheet[1]:c.fill=PatternFill('solid',fgColor='24476A');c.font=Font(bold=True,color='FFFFFF')
 for col in sheet.columns:sheet.column_dimensions[col[0].column_letter].width=18
 sheet.column_dimensions['K'].width=65
 for row in sheet:
  for c in row:c.alignment=Alignment(vertical='top',wrap_text=True)
w.save(out)
csvfile=p/'PR3838NB_RGBW_1800_Measured_Update_20261027.csv'
with csvfile.open('w',encoding='utf-8-sig',newline='') as f:
 cw=csv.writer(f);cw.writerow(['目标档/K','R','G','B','W','合计','配比来源','实测色温/K','实测x','实测y'])
 for r in truth['results']:
  measured=r['CCT']==1800;v=duty if measured else r;cw.writerow([r['CCT'],*[v[c] for c in duty],255,'用户实测' if measured else '理论估算',1798 if measured else '',.549 if measured else '',.4077 if measured else ''])
reread=load_workbook(out,data_only=True)
assert tuple(list(reread['修正值'].values)[1][1:5])==(113,0,0,142)
for row,th in zip(list(reread['修正值'].values)[1:],truth['results']):
 assert sum(row[1:5])==255
 if row[0]!=1800:assert tuple(row[1:5])==tuple(th[c] for c in duty)
assert tuple(list(reread['计算值'].values)[1][1:5])==(174,25,1,55)
print('Verified new measured recipe retained; 12 other nodes unchanged; original theoretical sheet preserved.')
print(out)
