from pathlib import Path
import copy,json,hashlib,sys,time
import pathops
from fontTools.ttLib import TTFont
from fontTools.fontBuilder import FontBuilder
from fontTools.pens.ttGlyphPen import TTGlyphPen
from fontTools.pens.cu2quPen import Cu2QuPen
from PIL import Image,ImageDraw,ImageFont
OUT=Path(__file__).resolve().parent
SOURCE=OUT.parent/'v03-open/JiaYingSong-Heavy.otf'
SAMPLE='北京大兴摔童案'
DETAIL='穿山贾说了啥刑侦八虎警察悬疑真相重现露霜藏警赢鬱0123456789ABC，。！？'
font=TTFont(SOURCE);gs=font.getGlyphSet();cmap=font.getBestCmap()

def shape(name,rx,ry):
    p=pathops.Path();gs[name].draw(p.getPen())
    if not len(p.verbs):return p,1
    # Anisotropic expansion: thicken stems more than horizontal hairlines.
    original=pathops.simplify(p,clockwise=True)
    base_contours=list(original.contours)
    holes=[c for c in base_contours if not c.clockwise]
    x0,y0,x1,y1=original.bounds
    density=original.area/max(1,(x1-x0)*(y1-y0))
    max_gain=.24 if density>.43 else .38
    for factor in [1,.85,.7,.55,.4,.25,.15,.08,0]:
        if not factor:return original,0
        try:
            stretched=original.transform(scaleY=rx/ry)
            stroked=pathops.Path(stretched)
            stroked.stroke(2*rx*factor,pathops.LineCap.BUTT_CAP,pathops.LineJoin.MITER_JOIN,2)
            grown=pathops.op(stretched,stroked,pathops.PathOp.UNION,clockwise=True)
            result=grown.transform(scaleY=ry/rx)
        except pathops.PathOpsError:
            continue
        if result.area>original.area*(1+max_gain):continue
        remaining=[c for c in result.contours if not c.clockwise]
        preserved=True
        for hole in holes:
            a,b,c,d=hole.bounds;cx=(a+c)/2;cy=(b+d)/2
            matches=[]
            for candidate in remaining:
                aa,bb,cc,dd=candidate.bounds
                if abs((aa+cc)/2-cx)<max(10,(c-a)*.3) and abs((bb+dd)/2-cy)<max(10,(d-b)*.3):matches.append(candidate.area)
            if not matches or max(matches)<hole.area*.50:
                preserved=False;break
        if preserved:return result,factor
    return original,0

def build(path,rx,ry,full=False):
    if full:order=font.getGlyphOrder();mapping=cmap
    else:
        mapping={ord(c):cmap[ord(c)] for c in SAMPLE+DETAIL+' ' if ord(c) in cmap}
        order=['.notdef']+list(dict.fromkeys(mapping.values()))
    glyphs={};metrics={};reduced=[];fallback=[];errors=[]
    for i,name in enumerate(order):
        aw,lsb=font['hmtx'][name]
        try:
            p,factor=shape(name,rx,ry)
        except (pathops.PathOpsError, pathops.OpenPathError) as e:
            p=pathops.Path();gs[name].draw(p.getPen());factor=0
            errors.append({'glyph':name,'error':str(e)})
        if factor<1:reduced.append([name,factor])
        if factor==0:fallback.append(name)
        p.convertConicsToQuads(.1)
        pen=TTGlyphPen(None);p.draw(Cu2QuPen(pen,max_err=.5,reverse_direction=False))
        g=pen.glyph();g.recalcBounds(None);glyphs[name]=g
        metrics[name]=(aw,getattr(g,'xMin',0))
        if full and i%2500==0:print(f'Built {i}/{len(order)} glyphs; reduced {len(reduced)}',flush=True)
    fb=FontBuilder(1000,isTTF=True)
    fb.setupGlyphOrder(order);fb.setupCharacterMap(mapping);fb.setupGlyf(glyphs)
    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 Black','styleName':'Regular','fullName':'Jia Ying Song Black','psName':'JiaYingSong-Black','uniqueFontIdentifier':'JiaYingSong-Black-0.400','version':'Version 0.400','copyright':'Copyright 2017-2022 Adobe (http://www.adobe.com/), with Reserved Font Name Source. Modified version Jia Ying Song, 2026.','description':f'Heavy title adaptation of Source Han Serif. Outline expansion x={rx}, y={ry} units, with counter preservation.','licenseDescription':license_text,'licenseInfoURL':'https://openfontlicense.org'})
    for nid,text in [(1,'贾影宋 超粗'),(2,'常规'),(4,'贾影宋 超粗')]:fb.font['name'].setName(text,nid,3,1,0x804)
    os=font['OS/2']
    ymin=min(getattr(g,'yMin',0) for g in glyphs.values());ymax=max(getattr(g,'yMax',0) for g in glyphs.values())
    fb.setupOS2(sTypoAscender=os.sTypoAscender,sTypoDescender=os.sTypoDescender,sTypoLineGap=os.sTypoLineGap,usWinAscent=max(os.usWinAscent,ymax),usWinDescent=max(os.usWinDescent,-ymin),usWeightClass=950,usWidthClass=3,fsType=0)
    fb.setupPost();fb.setupMaxp()
    if full:
        for tag in ['GSUB','GDEF']:
            if tag in font:fb.font[tag]=copy.deepcopy(font[tag])
    fb.save(path)
    return {'glyphs':len(order),'unicode_mappings':len(mapping),'adaptive_reductions':reduced,'unchanged_for_counter_preservation':fallback,'expansion_x':rx,'expansion_y':ry,'preserved_after_geometry_error':errors}

def preview():
    rows=[('V03 / CURRENT',SOURCE)]
    for rx,ry in [(16,4),(22,5),(28,6)]:
        path=OUT/f'preview-{rx}.ttf';build(path,rx,ry);rows.append((f'V04 / X+{rx*2} Y+{ry*2}',path))
    im=Image.new('RGB',(1720,1510),'#303030');d=ImageDraw.Draw(im)
    ui=ImageFont.truetype('/System/Library/Fonts/Supplemental/Arial.ttf',24)
    for i,(label,path) in enumerate(rows):
        y=20+i*370;d.text((50,y),label,font=ui,fill='#c9b386')
        d.text((45,y+30),SAMPLE,font=ImageFont.truetype(str(path),270),fill='white')
    im.save(OUT/'weight-candidates.png')

if __name__=='__main__':
    import shutil
    shutil.copy2(OUT.parent/'v03-open/OFL.txt',OUT/'OFL.txt')
    if '--preview' in sys.argv:preview()
    else:
        rx=float(sys.argv[1]) if len(sys.argv)>1 else 22
        ry=float(sys.argv[2]) if len(sys.argv)>2 else 5
        path=OUT/'JiaYingSong-Black.ttf'
        report=build(path,rx,ry,True)
        out=TTFont(path);assert out.getBestCmap()==cmap
        assert all(ord(c) in cmap for c in SAMPLE+DETAIL)
        print('TTF saved. Encoding WOFF2...',flush=True)
        out.flavor='woff2';out.save(OUT/'JiaYingSong-Black.woff2')
        web=TTFont(OUT/'JiaYingSong-Black.woff2')
        assert web.getBestCmap()==cmap
        assert web['glyf'].compile(web)==TTFont(path)['glyf'].compile(TTFont(path))
        report['source_sha256']=hashlib.sha256(SOURCE.read_bytes()).hexdigest()
        report['files']={p.name:{'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in [path,OUT/'JiaYingSong-Black.woff2']}
        report['validation']=['all Unicode mappings preserved','TTF reload passed','WOFF2 reload passed','WOFF2 decoded outlines identical to TTF']
        (OUT/'build-report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
        print(json.dumps({k:v for k,v in report.items() if k not in ['adaptive_reductions','unchanged_for_counter_preservation']},ensure_ascii=False),flush=True)
