"""Derives APP2 semantic tokens the colour script does not: milestone chips (fill + letter + text + tint),
focus override, and writes tokens/semantic.css + tokens/milestones.json. Reads tokens/tokens.json. Re-run after color_system.py."""
import json,sys,importlib.util,itertools
spec=importlib.util.spec_from_file_location('cs',sys.argv[1]);cs=importlib.util.module_from_spec(spec);spec.loader.exec_module(cs)
T=json.load(open('tokens/tokens.json'))['pe']['color']
def ramp(n): return {k:v['$value'] for k,v in T[n].items() if isinstance(v,dict) and '$value' in v}
SURF={'light':'#FFFFFF','dark':'#152240'}   # cards: V5 white card on canvas; dark = surface-raised
NAVY='#0B1734';WHITE='#FFFFFF'
out={};css_l=[];css_d=[]
for m,letter in [('lead','L'),('prospect','P'),('approved','A'),('completed','C'),('invoiced','I')]:
    r=ramp(m);rec={'letter':letter}
    for mode,surf in SURF.items():
        # Recognisable fill (AccuLynx-like brightness); the LETTER carries meaning (>=4.5:1), and on light
        # surfaces a 1.5px ring in a darker step gives the chip edge >=3:1 (WCAG 1.4.11).
        prefer=(['300','400'] if m=='lead' else ['400','300','500']) if mode=='light' else ['300','400']
        best=None
        for st in prefer:
            f=r[st]; lc=max([(cs.contrast(NAVY,f),NAVY),(cs.contrast(WHITE,f),WHITE)])
            if lc[0]>=4.5:
                ring=next((r[x] for x in ['500','600','700','800'] if cs.contrast(r[x],surf)>=3),r['700']) if mode=='light' else f
                best=(st,f,lc[1],round(lc[0],2),round(cs.contrast(ring,surf),2),ring);break
        assert best,(m,mode)
        txt=next(r[s] for s in (['500','600','700','800'] if mode=='light' else ['200','300','400']) if cs.contrast(r[s],surf)>=4.5)
        tint=r['50'] if mode=='light' else r['900']
        rec[mode]={'fill_step':best[0],'fill':best[1],'on_fill':best[2],'on_fill_contrast':best[3],'ring':best[5],'ring_vs_surface':best[4],'text':txt,'text_contrast':round(cs.contrast(txt,surf),2),'tint':tint}
        (css_l if mode=='light' else css_d).extend([f'  --pe-ms-{m}: {best[1]};',f'  --pe-ms-{m}-on: {best[2]};',f'  --pe-ms-{m}-ring: {best[5]};',f'  --pe-ms-{m}-text: {txt};',f'  --pe-ms-{m}-tint: {tint};'])
    out[m]=rec
# CVD worst pair between the five light fills
fills=[out[m]['light']['fill'] for m in out]
def dE(a,b,kind):
    sim=getattr(cs,'simulate',None)
    A=cs.lin_rgb2oklab(*(cs.lin(c) for c in cs.hex2rgb(a)));B=cs.lin_rgb2oklab(*(cs.lin(c) for c in cs.hex2rgb(b)))
    return 100*((A[0]-B[0])**2+(A[1]-B[1])**2+(A[2]-B[2])**2)**.5
pairs={f'{a}/{b}':round(dE(a,b,'n'),1) for a,b in itertools.combinations(fills,2)}
out['_normal_vision_min_deltaE_ok']=min(pairs.values());out['_note']='Milestone never by colour alone: letter always printed in the chip; label text beside it in lists.'
json.dump(out,open('tokens/milestones.json','w'),indent=1)
focus={'light':'#176CC5','dark':'#6FA8F5'}
for mode,s in [('light',css_l),('dark',css_d)]:
    s.append(f'  --pe-focus: {focus[mode]}; /* override: V5 measured #176CC5; red focus would read as an error */')
    s.append(f'  --pe-card: {SURF[mode]};')
nl="\n"
css=(':root, [data-mode="light"] {'+nl+nl.join(css_l)+nl+'}'+nl+'[data-mode="dark"] {'+nl+nl.join(css_d)+nl+'}'+nl
     +'@media (prefers-color-scheme: dark) { :root:not([data-mode="light"]) {'+nl+nl.join(css_d)+nl+'} }'+nl)
css="/* generated by tokens/derive_semantic.py — do not edit */\n"+css
open('tokens/semantic.css','w').write(css)
for m in ['lead','prospect','approved','completed','invoiced']: print(m,out[m]['light'],'| dark',out[m]['dark']['fill'],out[m]['dark']['on_fill'])
print('fo',focus,'contrast focus light vs canvas',round(cs.contrast('#176CC5','#F3F5F9'),2),'dark',round(cs.contrast('#6FA8F5','#0B1734'),2))
print(pairs)
