from pathlib import Path
import json,hashlib,copy
from fontTools.ttLib import TTFont
from fontTools.fontBuilder import FontBuilder
from fontTools.pens.t2CharStringPen import T2CharStringPen
from fontTools.pens.transformPen import TransformPen
from PIL import Image,ImageDraw,ImageFont
OUT=Path(__file__).resolve().parent
src=OUT/'source/SourceHanSerifCN-Heavy.otf'
font=TTFont(src);gs=font.getGlyphSet();order=font.getGlyphOrder();cmap=font.getBestCmap()
scale=.78;spacing=.82
charstrings={};metrics={}
for i,name in enumerate(order):
    aw,lsb=font['hmtx'][name];delta=aw*(spacing-scale)/2
    width=round(aw*spacing)
    pen=T2CharStringPen(width,None)
    gs[name].draw(TransformPen(pen,(scale,0,0,1,delta,0)))
    charstrings[name]=pen.getCharString();metrics[name]=(width,round(lsb*scale+delta))
    if i%5000==0:print(f'Converted {i}/{len(order)} glyphs',flush=True)
fb=FontBuilder(font['head'].unitsPerEm,isTTF=False)
fb.setupGlyphOrder(order);fb.setupCharacterMap(cmap)
fb.setupCFF('JiaYingSong-Heavy',{'FullName':'Jia Ying Song Heavy','FamilyName':'Jia Ying Song','Weight':'Heavy'},charstrings,{})
fb.setupHorizontalMetrics(metrics)
fb.setupHorizontalHeader(ascent=font['hhea'].ascent,descent=font['hhea'].descent,lineGap=font['hhea'].lineGap)
license_text=(OUT/'OFL.txt').read_text()
fb.setupNameTable({'familyName':'Jia Ying Song','styleName':'Heavy','fullName':'Jia Ying Song Heavy','psName':'JiaYingSong-Heavy','uniqueFontIdentifier':'JiaYingSong-Heavy-0.300','version':'Version 0.300','copyright':'Copyright 2017-2022 Adobe (http://www.adobe.com/), with Reserved Font Name Source. Modified version: Jia Ying Song, 2026.','description':'Modified from Source Han Serif CN Heavy under SIL OFL 1.1. Narrow horizontal display adaptation, outline width 78%, advance 82%.','licenseDescription':license_text,'licenseInfoURL':'https://openfontlicense.org'})
for nameid,txt in [(1,'贾影宋'),(2,'特粗'),(4,'贾影宋 特粗')]:fb.font['name'].setName(txt,nameid,3,1,0x804)
os=font['OS/2']
fb.setupOS2(sTypoAscender=os.sTypoAscender,sTypoDescender=os.sTypoDescender,sTypoLineGap=os.sTypoLineGap,usWinAscent=os.usWinAscent,usWinDescent=os.usWinDescent,usWeightClass=900,usWidthClass=3,fsType=0)
fb.setupPost();fb.setupMaxp()
# Keep glyph substitutions and classifications; title layout uses horizontal advances.
for tag in ['GSUB','GDEF']:
    if tag in font:fb.font[tag]=copy.deepcopy(font[tag])
path=OUT/'JiaYingSong-Heavy.otf';fb.save(path)
check=TTFont(path)
assert check.getBestCmap()==cmap
sample='穿山贾说了啥刑侦八虎旧事重现真相大白岁月人间玉金露云律闰秋寒辰日宇天0123456789，。！？'
assert not [c for c in sample if ord(c) not in cmap]
report={'base':'Source Han Serif CN Heavy','source_url':'https://github.com/adobe-fonts/source-han-serif/tree/release/SubsetOTF/CN','base_sha256':hashlib.sha256(src.read_bytes()).hexdigest(),'output_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'glyphs':len(order),'unicode_mappings':len(cmap),'CJK_mappings':sum(0x3400<=c<=0x9fff or 0x20000<=c<=0x323af for c in cmap),'outline_width':scale,'advance_width':spacing,'license':'SIL OFL 1.1','checks':['cmap preserved','sample characters covered','serialized font reopened']}
(OUT/'build-report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
img=Image.new('RGB',(1800,1260),'#302e2b');d=ImageDraw.Draw(img)
ui=ImageFont.truetype('/System/Library/Fonts/Supplemental/Arial.ttf',23)
d.text((95,55),'JIA YING SONG  /  HEAVY  /  OPEN FONT EDITION 03',font=ui,fill='#b9aa8c')
for text,y,size,color in [('旧事重现',120,280,'#f7f0df'),('真相大白',425,280,'#f7f0df'),('穿山贾说了啥',755,178,'#d6bd85'),('刑侦八虎 · 岁月人间',982,104,'#f7f0df')]:
    d.text((90,y),text,font=ImageFont.truetype(str(path),size),fill=color)
d.text((95,1200),'SIL OFL 1.1  /  Condensed display adaptation of Source Han Serif',font=ui,fill='#b9aa8c')
img.save(OUT/'specimen-v03.png')
print(json.dumps(report,ensure_ascii=False),flush=True)
