import re, subprocess, numpy as np
from PIL import Image
ROOT='/home/ubuntu/standalone/builds/27-aesop-3'
p=ROOT+'/src/styles.css'
base=open(p).read()
a=np.asarray(Image.open(ROOT+'/mock.jpg').convert('RGB')).astype(float)
def run(s,lab):
    open(p,'w').write(s)
    subprocess.run(['python3','tools/shot.py','--label',lab],cwd=ROOT,
                   stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    b=np.asarray(Image.open(ROOT+f'/shots/{lab}.png').convert('RGB')).astype(float)
    return np.abs(a-b).mean(2)
def sweep(cls, nat, tgt, reg, ws):
    lsb,top,w0,h0 = nat; tx,ty,tw,th = tgt
    best=None
    for w in ws:
        f=tw/(w0+w); g=th/(h0+w)
        left=tx-(lsb-w/2)*f
        topoff=(h0-(h0-w/2)*g)  # offsets differ for S due to prior origin; treat S base below
        if cls=='.l-s':
            topoff=(h0-(h0-w/2)*g) - (h0-69)  # placeholder
        rule=(f"{cls} {{ left: {left/100:.5f}rem; top: {topoff/100:.5f}rem; "
              f"transform: scaleX({f:.5f}) scaleY({g:.5f}); transform-origin: left top;"
              + (f" -webkit-text-stroke: {w/100:.3f}rem;" if w else "") + " }")
        s=re.sub(re.escape(cls)+r" \{[^}]*\}", rule, base)
        d=run(s,'sw')
        x0,y0,x1,y1=reg
        e=d[y0:y1,x0:x1].mean(); tot=d.mean()
        print(f"{cls} w={w:2d} f={f:.4f} g={g:.4f} left={left:.2f} top={topoff:.2f} region={e:.3f} total={tot:.3f}")
        if best is None or e<best[1]: best=(w,e,rule,tot)
    print('BEST',cls,best)
    return best
print('--- S')
sweep('.l-s',(22,69,331,366),(28,322,378,363),(28,322,406,684),[0,4,8,12,16,20])
print('--- N')
sweep('.l-n',(38,75,353,354),(987,328,380,354),(987,322,1367,684),[0,4,8,12,16,20])
open(p,'w').write(base)
