"""Reproduce converted bitmap assets; run from this directory.
BBC input is the bundled jsbeeb teletext_data.js (GPL-3.0-or-later).
CPC input cpc464.ttf is CC0 by Damian Vila (included in source bundle).
MSX input MSX-SOURCE.ttf is CC-BY3.0 by Patrick H. Lauke.
"""
from pathlib import Path
import json,re
from PIL import Image,ImageFont,ImageDraw
HERE=Path(__file__).resolve().parent

def bitmap(ttf,width,height):
    font=ImageFont.truetype(str(ttf),height)
    glyphs={}
    for code in range(32,127):
        canvas=Image.new('1',(8,height))
        ImageDraw.Draw(canvas).text((0,0),chr(code),font=font,fill=1)
        glyphs[str(code)]=[sum(canvas.getpixel((x,y))<<(width-1-x) for x in range(width)) for y in range(height)]
    return glyphs

def save(name,width,height,glyphs,source,license,**extra):
    (HERE/name).write_text(json.dumps(dict(width=width,height=height,glyphs=glyphs,source=source,license=license,**extra),separators=(',',':')))

source=re.sub(r'//[^\n]*','',(HERE/'teletext_data.js').read_text())
a=source.split('new Uint8Array([')[1].split(']')[0]
data=list(map(int,re.findall(r'\d+',a)))
assert len(data)==96*6*10
save('bbc-mode7.json',6,10,{str(i+32):[sum(data[i*60+y*6+x]<<(5-x) for x in range(6)) for y in range(10)] for i in range(96)},'https://github.com/mattgodbolt/jsbeeb/blob/main/src/teletext_data.js','GPL-3.0-or-later')
save('cpc464.json',8,8,bitmap(HERE/'CPC-SOURCE.ttf',8,8),'https://github.com/damianvila/font-cpc464','CC0-1.0')
save('msx.json',6,8,bitmap(HERE/'MSX-SOURCE.ttf',6,8),'https://fontstruct.com/fontstructions/show/2310019/msx-international','CC-BY-3.0',author='Patrick H. Lauke',modifications='Rasterized original reconstruction at8px; retained leftmost6pixels perTMS9918SCREEN0 textmode.')
