#!/usr/bin/env python3
"""Extract the EmuTOS GPL-2.0-or-later ST 8x8 source bitmap into renderer JSON.
No ROM image is used. C UWORDs are expanded high byte first, as on the 68000.
"""
from pathlib import Path
import re,json,hashlib
root=Path(__file__).resolve().parent
text=(root/'fnt_st_8x8.c').read_text()
offsets=(root/'fnt_off_8x8.c').read_text()
body=re.search(r'static const UWORD dat_table\[\]\s*=\s*\{(.*?)\};',text,re.S).group(1)
words=[int(v,16) for v in re.findall(r'0x([0-9a-fA-F]+)',body)]
assert len(words)==1024, len(words)
bitmap=b''.join(word.to_bytes(2,'big') for word in words)
offbody=re.search(r'const UWORD off_8x8_table\[\]\s*=\s*\{(.*?)\};',offsets,re.S).group(1)
offs=[int(v,16) for v in re.findall(r'0x([0-9a-fA-F]+)',offbody)]
assert offs==list(range(0,256*8+1,8)),len(offs)
glyphs={str(code):[bitmap[row*256+code] for row in range(8)] for code in range(256)}
assert glyphs['32']==[0]*8
assert glyphs['65']==[0x18,0x3c,0x66,0x66,0x7e,0x66,0x66,0]
assert glyphs['48'][0:2]==[0x3c,0x66]
font={'width':8,'height':8,'glyphs':glyphs,'name':'EmuTOS Atari ST 8x8 system font','encoding':'Atari ST','license':'GPL-2.0-or-later','copyright':'Copyright (C) 2001-2021 The EmuTOS development team','source':'https://github.com/emutos/emutos/blob/02c2db75fc875265c1449efea014450466cf20b7/bios/fnt_st_8x8.c','sourceRevision':'02c2db75fc875265c1449efea014450466cf20b7','extraction':'C UWORD high byte first; 256-byte scanline; eight rows; offsets verified8bits/glyph'}
(root/'atarist-8x8.json').write_text(json.dumps(font,separators=(',',':'))+'\n')
(root/'console-default.json').write_text(json.dumps({'machine':'Atari ST','mode':'ST low','rasterWidth':320,'rasterHeight':200,'columns':40,'rows':25,'cellWidth':8,'cellHeight':8,'foreground':'#000000','background':'#ffffff','foregroundIndex':15,'backgroundIndex':0,'sourceRevision':'02c2db75fc875265c1449efea014450466cf20b7','sourceEvidence':['bios/vt52.c: low-resolution init v_col_fg=15; v_col_bg=0','bios/screen.c: dflt_palette[0]=RGB_WHITE; dflt_palette[15]=RGB_BLACK'],'scope':'Documented EmuTOS native ST-compatible console defaults; no original-ROM pixel identity claim'},indent=2)+'\n')
files=[]
for name in ['fnt_st_8x8.c','fnt_off_8x8.c','license.txt','atarist-8x8.json','console-default.json','extract_font.py','ATTRIBUTION.md']:
 b=(root/name).read_bytes();files.append({'path':name,'bytes':len(b),'sha256':hashlib.sha256(b).hexdigest()})
(root/'provenance.json').write_text(json.dumps({'status':'SOURCE_BITMAP_EXTRACTED_AND_CHECKED','sourceRepository':'https://github.com/emutos/emutos','sourceRevision':'02c2db75fc875265c1449efea014450466cf20b7','license':'GPL-2.0-or-later','fontGeometry':[8,8],'glyphCount':256,'romUsed':False,'pixelScaling':False,'validation':['1024source UWORDs =2048bytes','257offsets exactly8bits apart','256glyphs ×8rows','space blank; A exact expected scanlines; zero leading scanlines cross-check','STlow320/8=40columns;200/8=25rows'],'files':files},indent=2)+'\n')
print(json.dumps({'font':'atarist-8x8.json','glyphs':256,'width':8,'height':8,'bytes':(root/'atarist-8x8.json').stat().st_size,'checks':'PASS'}))
