"""Retain paired AnimCJK / Make Me a Hanzi stroke contours + medians for display only.
Never feed these alternative regional paths into recognition/grading.
Usage: python3 scripts/build-stroke-outlines.py RESEARCH_DIRECTORY
"""
import json,pathlib,sys,hashlib,unicodedata
root=pathlib.Path(__file__).resolve().parents[1];src=pathlib.Path(sys.argv[1]);out=root/'dist';index=json.loads((out/'writing-guides.json').read_text());chars=set(index['characters']);data=json.loads((out/'data.json').read_text());chars.update(d['char'] for d in data)
sources=[];sets={};guides={}
for p in (out/'writing-guides').glob('*.json'):guides.update(json.loads(p.read_text()))
own=json.loads((out/'original-korean.json').read_text())['characters']
for region,name in [('ko','graphicsKo.txt'),('hant','graphicsZhHant.txt'),('ja','graphicsJa.txt'),('reference','../graphics.txt')]:
 p=src/name;sets[region]={x['character']:x for x in map(json.loads,p.open())};sources.append({'region':region,'file':name,'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'url':'https://github.com/skishore/makemeahanzi' if region=='reference' else 'https://github.com/parsimonhi/animCJK/blob/master/'+name})
shards=[{} for _ in range(128)];lookup={};counts={}
for c in sorted(chars):
 key=unicodedata.normalize('NFKC',c);entry=own.get(c) or own.get(key) or guides.get(c) or guides.get(key);region=entry.get('source') if entry else None
 if region not in sets:continue
 raw=sets[region].get(c) or sets[region].get(key)
 if not raw:continue
 if not raw.get('strokes') or len(raw['strokes'])!=len(raw.get('medians',[])) or any(len(m)<2 for m in raw['medians']):continue
 n=ord(c)%128;lookup[c]=n;counts[region]=counts.get(region,0)+1
 shards[n][c]={'source':region,'outlines':raw['strokes'],'medians':raw['medians'],'url':next(s['url'] for s in sources if s['region']==region),'license':'Arphic Public License'}
(out/'stroke-outlines').mkdir(exist_ok=True)
for n,s in enumerate(shards):(out/f'stroke-outlines/{n:03d}.json').write_text(json.dumps(s,ensure_ascii=False,separators=(',',':')))
(out/'stroke-outlines.json').write_text(json.dumps({'version':1,'characters':lookup,'sources':sources,'bySource':counts,'canonical':sum(d['char'] in lookup for d in data),'modification':{'date':'2026-09-30','by':'한획','changes':'AnimCJK 및 Make Me a Hanzi graphics 자료의 획 윤곽과 대응 중심선을 함께 보존하여 128개 파일로 나눴습니다. 획별 영역 밖으로 진행선이 노출되지 않는 시범에 사용합니다. 원자료 경로 자체는 수정하지 않았습니다.','licenseFile':'licenses/ARPHICPL.txt'}},ensure_ascii=False,separators=(',',':')))
print(json.dumps({'total':len(lookup),'canonical':sum(d['char'] in lookup for d in data),'bySource':counts,'bytes':sum(f.stat().st_size for f in (out/'stroke-outlines').glob('*.json'))},ensure_ascii=False))
