import json,re,urllib.request,concurrent.futures,hashlib,time
from pathlib import Path
from fontTools.ttLib import TTFont
from PIL import Image,ImageDraw,ImageFont,features
ROOT=Path(__file__).resolve().parents[2]
IN=ROOT.parent/'English-Invitation-Ultra-Design-Brief-2026-10-07'
OUT=Path(__file__).parent
FONT=ROOT/'fonts'
initial=json.loads((IN/'research/english-font-candidate-index.json').read_text(encoding='utf-8-sig'))['candidates']
new=[('Lora','lora'),('Source Sans 3','sourcesans3'),('Source Serif 4','sourceserif4'),('Crimson Pro','crimsonpro'),('Castoro','castoro'),('Alegreya','alegreya'),('Newsreader','newsreader'),('Fraunces','fraunces'),('Literata','literata'),('Spectral','spectral'),('Libre Franklin','librefranklin'),('IBM Plex Serif','ibmplexserif'),('Cormorant SC','cormorantsc'),('Gelasio','gelasio')]
entries=[dict(x,prior=True) for x in initial]+[{'name':n,'metadataUrl':f'https://raw.githubusercontent.com/google/fonts/main/ofl/{p}/METADATA.pb','prior':False} for n,p in new]
def fetch(url):
    req=urllib.request.Request(url,headers={'User-Agent':'InvitationTypographyResearch/1.0'})
    for i in range(3):
        try:
            with urllib.request.urlopen(req,timeout=35) as r:return r.read()
        except Exception:
            if i==2:raise
            time.sleep(.4)
def one(e):
    p=FONT/e['name'];p.mkdir(parents=True,exist_ok=True)
    out=dict(e);errors=[]
    try:
        meta=fetch(e['metadataUrl']);(p/'METADATA.pb').write_bytes(meta)
        m=meta.decode();e['designer']=re.search(r'designer: "([^"]+)"',m).group(1)
        base=e['metadataUrl'].rsplit('/',1)[0]
        filenames=list(dict.fromkeys(re.findall(r'filename: "([^"]+)"',m)))
        for fn in filenames:
            (p/fn).write_bytes(fetch(base+'/'+urllib.parse.quote(fn)))
        for fn in ['OFL.txt','DESCRIPTION.en_us.html']:
            try:(p/fn).write_bytes(fetch(base+'/'+fn))
            except Exception as ex:errors.append(fn+': '+str(ex))
        out.update(designer=e['designer'],available_files=filenames,source_opened=True)
    except Exception as ex:errors.append(str(ex));out['source_opened']=False
    out['errors']=errors
    fonts=[]
    for f in p.glob('*.ttf'):
        t=TTFont(f)
        def n(i):
            vals=[x.toUnicode() for x in t['name'].names if x.nameID==i]
            return vals[0] if vals else None
        feats={}
        for table in ['GSUB','GPOS']:
            if table in t and t[table].table.FeatureList:
                feats[table]=sorted(set(x.FeatureTag for x in t[table].table.FeatureList.FeatureRecord))
        axes=[{'tag':a.axisTag,'min':a.minValue,'default':a.defaultValue,'max':a.maxValue} for a in t['fvar'].axes] if 'fvar' in t else []
        fonts.append({'file':str(f.relative_to(ROOT)).replace('\\','/'),'family':n(16) or n(1),'style':n(17) or n(2),'weight':t['OS/2'].usWeightClass,'axes':axes,'features':feats,'glyphs':len(t.getGlyphOrder()),'sha256':hashlib.sha256(f.read_bytes()).hexdigest(),'licence_file':str((p/'OFL.txt').relative_to(ROOT)).replace('\\','/'),'optical_size_available':any(a['tag']=='opsz' for a in axes)})
    out['files']=fonts
    return out
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as ex:
    data=list(ex.map(one,entries))
(OUT/'FONT-REGISTER.json').write_text(json.dumps({'date':'2026-10-07','prior_family_records':len(initial),'new_family_records':len(new),'families':data,'raqm':features.check('raqm'),'note':'Metadata refreshed from Google Fonts primary repository; actual binaries inspected by fontTools. Licence bundled per family. Download is not system installation. Variable font default metadata is not full weight range.'},indent=2),encoding='utf-8')
print('families',len(data),'opened',sum(x['source_opened'] for x in data),'files',sum(len(x['files']) for x in data),'errors',[(x['name'],x['errors']) for x in data if x['errors']])
