"""Build an offline Chinese font for the independent mask editor only."""
import json
from pathlib import Path
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from fontTools import subset
from fontTools.ttLib import TTFont
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical


def main():
    assets=PROJECT/'pallet/assets/mask_gallery';target=assets/'editor-font.otf'
    out=PROJECT/'outputs/pallet_mask_editor_validation_v1';out.mkdir(parents=True,exist_ok=True)
    if target.exists() or (out/'font_coverage.json').exists():raise ValueError('Editor font already built; preserve it and use a new validation version')
    sources=[assets/n for n in ('editor.html','editor.css','editor.js')]+[PROJECT/'pallet/mask_gallery_review.py',PROJECT/'pallet/mask_gallery.py']
    text=''.join(p.read_text() for p in sources);required={ord(c) for c in text if '\u3400'<=c<='\u9fff'}
    source=Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf');font=TTFont(source)
    assert required<=set(font.getBestCmap());sub=subset.Subsetter();sub.populate(text=text);sub.subset(font);font.save(target)
    assert required<=set(TTFont(target).getBestCmap())
    (assets/'FONT_LICENSE.txt').write_bytes((PROJECT/'pallet/assets/pose_review/FONT_LICENSE.txt').read_bytes())
    (out/'font_coverage.json').write_bytes(canonical(dict(state='passed',Chinese_characters=len(required),
        all_editor_Chinese_present=True,editor_font_sha256=digest(target),source_font_sha256=digest(source),
        pose_UI_font_modified=False,sources={str(p.relative_to(PROJECT)):digest(p) for p in sources}))+b'\n')
    print(json.dumps(dict(state='passed',Chinese_characters=len(required))))


if __name__=='__main__':main()
