import os, re, subprocess, sys, json
from PIL import Image
import numpy as np
root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
A=np.array(Image.open(os.path.join(root,'mock.jpg')).convert('RGB')).astype(float)
def region_mae(path,box):
    B=np.array(Image.open(path).convert('RGB')).astype(float)
    x0,y0,x1,y1=box
    return float(np.abs(A[y0:y1,x0:x1]-B[y0:y1,x0:x1]).mean())
def run(label, css, box):
    html=open(os.path.join(root,'work/base.html')).read()
    html=html.replace('</head>', f'<style>{css}</style></head>')
    p=os.path.join(root,'work',label+'.html')
    open(p,'w').write(html)
    subprocess.run(['python3','tools/shot.py','--label',label,'--src',p],cwd=root,
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    mae=region_mae(os.path.join(root,'shots',label+'.png'),box)
    print(f'{label:18s} regionMAE {mae:6.3f}')
    return mae
CASES=[
 ('sub_roboto','.sub{font-family:"Roboto",Arial,sans-serif;font-size:.2922rem;letter-spacing:-.0088em;}'),
 ('sub_archivo','.sub{font-family:"Archivo",Arial,sans-serif;font-size:.3055rem;letter-spacing:-.0192em;}'),
 ('sub_inter','.sub{font-family:"Inter",Arial,sans-serif;font-size:.286rem;letter-spacing:-.0314em;}'),
 ('sub_instrument','.sub{font-family:"Instrument Sans",Arial,sans-serif;font-size:.286rem;letter-spacing:-.0071em;}'),
 ('sub_nimbus','.sub{font-family:"Nimbus Sans",Arial,sans-serif;font-size:.286rem;letter-spacing:.0008em;}'),
 ('sub_manrope','.sub{font-family:"Manrope",Arial,sans-serif;font-size:.286rem;letter-spacing:-.0069em;}'),
]
for label,css in CASES:
    run(label,css,(35,475,770,555))
