"""Read-only measurement of final layout/type/art; writes this contract only.

No new rendering, typesetting choices, printable copy changes or physical units.
Pillow/RAQM reproduces the existing operations for occupied-alpha measurement.
"""
from pathlib import Path
from collections import defaultdict
import hashlib, json, math, re
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from fontTools.ttLib import TTFont

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'systems'
def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
def rect(box): return [round(box[0], 3), round(box[1], 3), round(box[2]-box[0], 3), round(box[3]-box[1], 3)]
def pct(r,w,h): return [round(r[0]/w*100,4),round(r[1]/h*100,4),round(r[2]/w*100,4),round(r[3]/h*100,4)]
def distance(a,b):
    dx=max(a[0]-b[2],b[0]-a[2],0);dy=max(a[1]-b[3],b[1]-a[3],0)
    return round(math.hypot(dx,dy),3)
def names(t,i):
    vals=[n.toUnicode() for n in t['name'].names if n.nameID==i]
    return vals[0] if vals else None
def tags(t):
    return sorted({f.FeatureTag for table in ('GSUB','GPOS') if table in t and t[table].table.FeatureList for f in t[table].table.FeatureList.FeatureRecord})
provenance={p['production_file']:p for p in json.loads((ROOT/'fonts/production/provenance.json').read_text(encoding='utf-8-sig'))}
register=json.loads((ROOT/'research/type-culture-print/FONT-REGISTER.json').read_text(encoding='utf-8-sig'))
family_sources={f['name']:f for f in register['families']}
fallbacks={
    'ImperialScript-Regular':('Alex Brush','fonts/Alex Brush/AlexBrush-Regular.ttf','fonts/Alex Brush/OFL.txt','Connected script backup; different capital rhythm, not an interchangeable metric.'),
    'Baskervville-Regular':('EB Garamond','fonts/production/EBGaramond-Medium.ttf','fonts/production/EBGaramond-Medium-OFL.txt','A genuine medium serif for a stronger ordinary-ink trial; a different display voice.'),
    'Cinzel-Medium':('Baskervville','fonts/production/Baskervville-Regular.ttf','fonts/production/Baskervville-Regular-OFL.txt','Licensed serif backup; inscriptional character changes, source case stays exact.'),
    'CormorantUpright-Semibold':('Baskervville','fonts/production/Baskervville-Regular.ttf','fonts/production/Baskervville-Regular-OFL.txt','Licensed upright serif backup; re-establish the botanical/name balance.'),
    'EBGaramond-Regular':('Lora','fonts/production/Lora-Regular.ttf','fonts/production/Lora-Regular-OFL.txt','Readable serif backup, genuine regular400; no synthetic weight.'),
    'EBGaramond-Medium':('Lora','fonts/production/Lora-Regular.ttf','fonts/production/Lora-Regular-OFL.txt','Readable serif backup, regular400 is a real available style, not simulated500.'),
    'SourceSans3-Regular':('Lora','fonts/production/Lora-Regular.ttf','fonts/production/Lora-Regular-OFL.txt','Readable serif backup; detail typography changes from sans to serif.'),
    'SourceSans3-Semibold':('Lora','fonts/production/Lora-Regular.ttf','fonts/production/Lora-Regular-OFL.txt','Readable serif backup, regular400 is a real available style, not simulated600.')
}
font_contract={}
def fontinfo(file):
    path=ROOT/file;t=TTFont(path);p=provenance.get(file,{})
    family=p.get('family') or names(t,16) or names(t,1)
    source=family_sources.get(family,{})
    return dict(family=family,style=names(t,17) or names(t,2),weight=t['OS/2'].usWeightClass,
        designer_or_foundry=source.get('designer') or names(t,9) or names(t,8),
        source_metadata_url=source.get('metadataUrl'),file=file,sha256=sha(path),
        original_file=p.get('original_file',file),original_instance_axes=p.get('instance_axes',{}),
        production_axes=[a.axisTag for a in t['fvar'].axes] if 'fvar' in t else [],
        optical_size='No opsz axis in this final file; no optical-size value set.',
        supported_features=tags(t),requested_features=['kern','liga'],
        supported_requested_features=[f for f in ('kern','liga') if f in tags(t)],
        availability='Bundled real font file; system installation not claimed.')
for key,(fam,file,lic,note) in fallbacks.items():
    original='fonts/production/'+key+'.ttf'
    info=fontinfo(original);info['licence']=provenance[original]['licence']
    f=fontinfo(file);f.update(licence=lic,note=note,status='RECOMMENDATION; not substituted in finals; every fallback requires new layout, copy and actual-stock proof.')
    assert (ROOT/lic).exists()
    info['fallback_id']='fallback:'+key;info['fallback']=f
    font_contract[key]=info

cache={}
def font(op):
    k=(op['file'],round(op['size_px']))
    if k not in cache:cache[k]=ImageFont.truetype(str(ROOT/k[0]),k[1],layout_engine=ImageFont.Layout.RAQM)
    return cache[k]
def textmask(op,size):
    im=Image.new('L',size);d=ImageDraw.Draw(im);f=font(op);s=op['size_px'];t=op['text'];tracking=op['tracking_em']
    advance=f.getlength(t)+(len(t)-1)*tracking*s
    left=op['x_px']-advance/2 if op['alignment']=='center' else op['x_px']-advance if op['alignment']=='right' else op['x_px']
    if tracking:
        cursor=left
        for ch in t:d.text((cursor,op['y_px']),ch,font=f,fill=255,anchor='lt',features=op['features']);cursor+=f.getlength(ch)+tracking*s
    else:d.text((left,op['y_px']),t,font=f,fill=255,anchor='lt',features=op['features'])
    return im,advance,left
def role(op):
    b=op.get('block') or 'unlabelled';t=op['text']
    if b.startswith('programme_') and b!='programme_heading':
        if t in {'Rasm-e-Baan','Rasm-e-Mehndi','Dawat-e-Aam','DJ Night','Baraat','Nikah'}:return 'event_title'
        if 'Marriage Garden' in t or (t=='Sardarshahar' and b=='programme_2'):return 'event_venue'
        if 'Meal starts' in t or 'Gathering:' in t or t in {'Sardarshahar to Sikar','Sardarshahar'}:return 'practical_note'
        return 'event_date_time'
    return b
def case(op):
    if op['block']=='connector':return 'Literal ampersand'
    if op['block']=='invitation_prose':return 'Sentence case; source unchanged'
    if op['block'] in {'groom_parents','bride_parents','welcome_host'}:return 'Sentence/name case; source unchanged'
    if op['font']=='Cinzel-Medium':return 'Source title case; Cinzel uses capital/small-cap-like glyph forms'
    return 'Exact source case; no case transform'
def para_for(op,boxes):
    for i,b in enumerate(boxes):
        if b['block']!=op['block'] or b['x_px']!=op['x_px']:continue
        for n,t in enumerate(b['lines']):
            if t==op['text'] and abs(b['y_px']+n*b['line_height_px']-op['y_px'])<.01:return i,b,n
    return None,None,None

contract={'date':'2026-10-07','scope':'Final A–D source-pixel type/art contract; no new layout or printable-copy change.',
    'units':'Source pixels and percentages of the named face. No point, millimetre, DPI or physical legibility certification.',
    'measurement':'Existing operations reconstructed with the same Pillow/RAQM real fonts. Occupied bounds use alpha>0; editing zones are separate conservative allocations.',
    'font_contract':font_contract,
    'editing_rules':{
        'direct_row':'A fixed one-line position has no automatic line-height or paragraph flow. Its conservative editing width starts from the actual current advance/visible overhang, not imagined blank capacity.',
        'flow_row':'Recorded para widths and advances retain current layout. Text-box x is an alignment anchor: subtract half width for center and full width for right to obtain allocated left.',
        'long_names':'Keep exact words and genuine styles. Prefer a deliberate two-line name within a newly reviewed box before reducing size. No horizontal scaling, joining-script tracking or fake bold. A fixed row does not automatically gain a second line.',
        'long_families':'Rewrap only at words inside the recorded maximum width and leading; recheck the next fixed block. No automatic downstream movement is implemented.',
        'date_time':'Preserve title/date/meal/journey relationships and western digits. A/B/D use their current independent fixed event boxes; C aligns detail starts at x580. Do not assume a tnum feature absent from Source Sans3 or Cinzel; final features remain as recorded.',
        'welcome':'Read down each column, then the next column. All 36 names including both Arif entries remain. Any longer spelling needs a new column-width and physical-reading proof.',
        'fallback':'Use the exact per-font fallback file/licence below as a fresh candidate. Re-measure every role, wrap, swash, clearance, ink density and exact word count; do not silently replace fonts in delivered layouts.',
        'gold_folds_art':'Keep added alpha out of tested exclusion envelopes. Measured source-envelope/art clearances below are not a segmentation of every gold flourish or a physical fold/die clearance. The visual 18px-to-gold starting guideline in TYPE-REPORT is an editing guideline, not a certified minimum on all finished rows.',
        'physical':'Finished piece dimensions, minimum printer clearance and readable physical point sizes remain INFORMATION_REQUIRED.'},
    'faces':{},'checks':{}}
md=['# Final type and original-art contract','',
    'This supplements the four design-system sheets with **actual final role metrics**. The 12 layout JSONs and PNGs stay unchanged. All units refer to the named source-pixel face: sleeve front 1089×565; each insert 1493×1053. Full-sleeve placement adds x221/y214. Physical type sizes, gold/fold clearances, ink matching and DPI remain **Information required**.','',
    'An occupied glyph box is the nonzero text-alpha union; it is **not** an allocated editing box. The JSON records both for every line, plus normalized x/y/width/height, font file, size, case, tracking, actual top advances, explicit paragraph gaps and maximum editing width. Flow-box x is an alignment anchor, not always its left edge. A fixed one-line row has no automatic line height or downstream reflow. Direct-row allocations deliberately reserve only current measured width/overhang.','',
    'No print text, font, layer position or stock pixel is changed by this contract. Fallbacks are licensed new candidates that require a new proof, never a silent substitution.','',
    '| Final real font | Genuine style/weight | Source / designer | Practical fallback file |',
    '|---|---|---|---|']
for k,v in font_contract.items():
    md.append(f"| {v['family']} / `{k}.ttf` | {v['style']} / {v['weight']} | {v['designer_or_foundry']} / Google Fonts primary metadata | `{v['fallback']['file']}` |")
md+=['','Exact source metadata links, bundled OFL notices, SHA256s and supported features are in JSON `font_contract`. Final operations request kern/liga; the JSON separates requests from tags supported by each actual file. Cinzel has no liga tag; its literal request does not prove such a feature exists. No final file has an opsz axis. All case is the approved source case; Cinzel’s glyph styling does not uppercase the stored text.','',
    '**Fixed-row rules.** No automatic paragraph gap applies. Keep the recorded anchor and alignment. Long names/families get a deliberately re-composed two-line box before detail type is reduced; a second line may require moving adjacent blocks and a fresh proof. Never track joining script, fake bold or distort letters. Keep the real event relationships, meal start and road-departure label together. C’s details start at x580; other schedules use fixed independent event boxes. Do not silently switch numeral features.','',
    '**Gold, folds and art.** Strictly keep added alpha out of the tested protected envelopes. JSON reports each row’s measured minimum distance to those envelope boundaries and to actual additional-art bounding boxes. These are source-screen measurements, not exact gold-contour or physical die clearances. TYPE-REPORT’s 18px visual-to-gold starting rule remains a conservative editing guideline; it is not retrospectively certified for every finished row. Physical measurements and actual-stock sampling are still required.','',
    'Role tables below include every programme subrole rather than inheriting the first event-title font for all event details. Widths are the permitted conservative maximum at the current anchor; exact per-line x/y/w/h and percentages are in JSON `faces.<face>.lines`.']
face_checks=[]
for suite in 'ABCD':
    for number,kind in enumerate(('sleeve','invitation','programme'),1):
        name=f'{suite}-{number:02d}-{kind}';lp=ROOT/'layouts'/f'{name}.json';data=json.loads(lp.read_text(encoding='utf-8-sig'));w,h=data['size'];ops=data['operations'];boxes=data['text_boxes']
        artmask=Image.new('L',(w,h));seedmask=Image.new('L',(w,h));rulemask=Image.new('L',(w,h));artops=[]
        for op in ops:
            if op['type']=='art':
                a=Image.open(ROOT/op['file']).convert('RGBA');a.thumbnail((op['w'],op['h']),Image.Resampling.LANCZOS)
                assert a.size==(op['w'],op['h']),f'{name}: stored art dimensions differ'
                if op.get('flip'):a=a.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
                am=Image.new('RGBA',(w,h));am.alpha_composite(a,(round(op['x']),round(op['y'])));alpha=am.getchannel('A')
                artmask=Image.fromarray(np.maximum(np.array(artmask),np.array(alpha)))
                artops.append(dict(**op,source_sha256=sha(ROOT/op['file']),alpha_bbox_px=rect(alpha.getbbox()),alpha_bbox_percent=pct(rect(alpha.getbbox()),w,h)))
            elif op['type']=='seed':
                d=ImageDraw.Draw(seedmask)
                for dx in (-14,0,14):d.ellipse((op['x']+dx-2,op['y']-2,op['x']+dx+2,op['y']+2),fill=255)
            elif op['type']=='line':ImageDraw.Draw(rulemask).line((op['x1'],op['y1'],op['x2'],op['y2']),fill=255,width=round(op['stroke']))
        extra=np.maximum(np.array(artmask),np.maximum(np.array(seedmask),np.array(rulemask)))
        textunion=np.zeros((h,w),dtype=np.uint8);lines=[]
        alltext=[o for o in ops if o['type']=='text']
        for index,op in enumerate(alltext):
            im,advance,left=textmask(op,(w,h));bb=im.getbbox();assert bb is not None;glyph=rect(bb)
            textunion=np.maximum(textunion,np.array(im));bi,b,n=para_for(op,boxes)
            maxwidth=op.get('maximum_width_px') or math.ceil(advance)
            zoneleft=op['x_px']-maxwidth/2 if op['alignment']=='center' else op['x_px']-maxwidth if op['alignment']=='right' else op['x_px']
            # Include visible side bearings; never confuse alpha extent with the allocated advance.
            zoneright=max(zoneleft+maxwidth,bb[2]);zoneleft=min(zoneleft,bb[0])
            lineheight=b['line_height_px'] if b else None
            if op['block']=='welcoming_list':
                ys=sorted(set(x['y_px'] for x in alltext if x['block']==op['block'] and x['x_px']==op['x_px']))
                lineheight=ys[1]-ys[0]
            zonetop=min(op['y_px'],bb[1])
            zonebottom=max(bb[3],op['y_px']+(lineheight or op['size_px']))
            zone=[round(zoneleft,3),zonetop,round(zoneright-zoneleft,3),round(zonebottom-zonetop,3)]
            samecol=sorted((x for x in alltext if x['block']==op['block'] and x['x_px']==op['x_px'] and x['y_px']>op['y_px']),key=lambda x:x['y_px'])
            nextadvance=round(samecol[0]['y_px']-op['y_px'],3) if samecol else None
            outer=[]
            if b:
                siblings=sorted((x for x in boxes if x['block']==b['block'] and x['x_px']==b['x_px']),key=lambda x:x['y_px'])
                for aa,zz in zip(siblings,siblings[1:]):outer.append(zz['y_px']-(aa['y_px']+aa['height_px']))
            boundary=min(bb[0]-20,w-20-bb[2],bb[1]-15,h-15-bb[3]) if kind=='sleeve' else min(bb[0]-130,1363-bb[2],bb[1]-82,962-bb[3])
            if kind=='sleeve':boundary=min(boundary,distance(bb,[350,165,745,398]))
            artdist=[distance(bb,[r['alpha_bbox_px'][0],r['alpha_bbox_px'][1],r['alpha_bbox_px'][0]+r['alpha_bbox_px'][2],r['alpha_bbox_px'][1]+r['alpha_bbox_px'][3]]) for r in artops]
            info=font_contract[op['font']]
            lines.append(dict(operation_index=index,role=role(op),block=op['block'],text=op['text'],file=op['file'],font=op['font'],style=info['style'],weight=info['weight'],size_px=op['size_px'],size_face_height_percent=op['size_height_percent'],case=case(op),tracking_em=op['tracking_em'],alignment=op['alignment'],anchor_px=[op['x_px'],op['y_px']],features_requested=op['features'],features_supported_requested=info['supported_requested_features'],fallback_id=info['fallback_id'],glyph_alpha_bbox_px=glyph,glyph_alpha_bbox_percent=pct(glyph,w,h),recorded_renderer_bbox_px=op['bbox_px'],editing_zone_px=zone,editing_zone_percent=pct(zone,w,h),maximum_line_width_px=maxwidth,maximum_line_width_percent=round(maxwidth/w*100,4),current_text_advance_px=round(advance,3),line_height_px=lineheight,line_height_em=round(lineheight/op['size_px'],4) if lineheight else None,flow='Measured para wrapping; fixed final lines' if b else 'Fixed column rows; no automatic wrap' if op['block']=='welcoming_list' else 'One fixed row; no automatic line-height/paragraph flow',paragraph_gap_inside_source_box_px=b['paragraph_gap_px'] if b else None,paragraph_outer_gap_px=sorted(set(outer)),advance_to_next_top_in_same_block_column_px=nextadvance,source_para_index=bi,minimum_tested_boundary_clearance_px=round(boundary,3),minimum_added_botanical_bbox_clearance_px=min(artdist) if artdist else None))
        combined=np.array(Image.open(ROOT/'ink-only'/f'{name}-ink.png').getchannel('A'))
        union=np.maximum(textunion,extra);different=int(np.count_nonzero((union>0)!=(combined>0)))
        def stats(a):
            pixels=int(np.count_nonzero(a));return dict(alpha_nonzero_pixels=pixels,canvas_area_pixels=w*h,alpha_coverage_percent=round(pixels/(w*h)*100,6))
        artstats=dict(botanical_only=stats(np.array(artmask)),original_seed_only=stats(np.array(seedmask)),information_rules_only=stats(np.array(rulemask)),all_nontext_union=stats(extra),text_only_union=stats(textunion),combined_existing_ink_layer=stats(combined),reconstructed_alpha_union_diff_pixels=different,
            meaning='Coverage counts every alpha>0 pixel once, including faint antialiasing; not optical ink density, toner mass, physical area or print coverage approval.')
        para_records=[]
        for b in boxes:
            matching=next(o for o in alltext if o['block']==b['block'] and o['x_px']==b['x_px'] and abs(o['y_px']-b['y_px'])<.01)
            x=b['x_px']-b['width_px']/2 if matching['alignment']=='center' else b['x_px']-b['width_px'] if matching['alignment']=='right' else b['x_px']
            allocation=[x,b['y_px'],b['width_px'],b['height_px']]
            para_records.append(dict(source=b['source'],block=b['block'],lines=b['lines'],alignment=matching['alignment'],allocation_px=allocation,allocation_percent=pct(allocation,w,h),line_height_px=b['line_height_px'],paragraph_gap_inside_source_box_px=b['paragraph_gap_px']))
        contract['faces'][name]=dict(suite=suite,kind=kind,canvas_px=[w,h],layout_file=str(lp.relative_to(ROOT)).replace('\\','/'),layout_sha256=sha(lp),face_sha256=sha(ROOT/'faces'/f'{name}.png'),ink_layer_sha256=sha(ROOT/'ink-only'/f'{name}-ink.png'),tested_envelope_px=[20,15,w-40,h-30] if kind=='sleeve' else [130,82,1233,880],sleeve_medallion_exclusion_px=[350,165,395,233] if kind=='sleeve' else None,lines=lines,source_para_allocations=para_records,art_operations=artops,art_coverage=artstats)
        face_checks.append(dict(face=name,reconstructed_occupied_ink_pixels_match=different==0,diff_pixels=different,minimum_tested_boundary_clearance_px=min(l['minimum_tested_boundary_clearance_px'] for l in lines)))
        md+=['',f'## {name}','', '| Role | Font / genuine weight | px / face-height% | Case; alignment; tracking | Actual leading / gap | Max line widths px |', '|---|---|---|---|---|---|']
        groups=defaultdict(list)
        for l in lines:groups[l['role']].append(l)
        for role_id,group in groups.items():
            fonts=', '.join(sorted({l['font']+'/'+str(l['weight']) for l in group}));sizes=', '.join(sorted({f"{l['size_px']}/{l['size_face_height_percent']:.3f}%" for l in group}));lh=sorted({l['line_height_px'] for l in group if l['line_height_px'] is not None});gap=sorted({v for l in group for v in l['paragraph_outer_gap_px']});widths=sorted({round(l['maximum_line_width_px'],2) for l in group});align='/'.join(sorted({l['alignment'] for l in group}));track='/'.join(str(v) for v in sorted({l['tracking_em'] for l in group}));cas='sentence/name' if any(l['case'].startswith('Sentence') for l in group) else 'literal &' if role_id=='connector' else 'source'
            rhythm=(' / '.join(str(x) for x in lh)+'px top advance' if lh else 'one fixed row; no auto flow')+('; outer paragraph gap '+','.join(str(x) for x in gap)+'px' if gap else '; no automatic paragraph gap')
            md.append(f"| {role_id} | {fonts} | {sizes} | {cas}; {align}; {track}em | {rhythm} | {', '.join(str(x) for x in widths)} |")
        md.append('')
        md.append(f"Minimum measured text distance to tested exclusion boundaries: **{face_checks[-1]['minimum_tested_boundary_clearance_px']}px**. This is not an exact gold-contour or physical clearance. All allocated/occupied row rectangles and percentages are in the face’s JSON lines.")

all_lines=[l for f in contract['faces'].values() for l in f['lines']]
zones_contain=all(l['editing_zone_px'][0]<=l['glyph_alpha_bbox_px'][0] and l['editing_zone_px'][1]<=l['glyph_alpha_bbox_px'][1] and l['editing_zone_px'][0]+l['editing_zone_px'][2]>=l['glyph_alpha_bbox_px'][0]+l['glyph_alpha_bbox_px'][2]-.001 and l['editing_zone_px'][1]+l['editing_zone_px'][3]>=l['glyph_alpha_bbox_px'][1]+l['glyph_alpha_bbox_px'][3]-.001 for l in all_lines)
contract['checks']={'measurement_preserves_final_files':True,'editing_zones_contain_every_current_occupied_glyph_box':zones_contain,'reconstructed_nonzero_ink_union_matches_all_existing_ink_layers':all(x['reconstructed_occupied_ink_pixels_match'] for x in face_checks),'per_face':face_checks,'exact_copy_checks':'Existing independent copy/render audits referenced; not rerun by this contract.','physical_readability_or_print_fit':False}
md+=['','## Original additional-art coverage','',
    'Only D has raster botanical art. B’s three-seed punctuation and all suites’ information rules are separately measured original geometry. A and C use no additional illustration. The botanical is a fictional garden stem, with no species, venue, sacred meaning or traced cultural composition asserted; see `art/README.md` for provenance and generation description.','',
    '| Face | Botanical alpha>0 pixels / face% | Seed pixels / face% | Rule pixels / face% | Combined text + all additions / face% |', '|---|---|---|---|---|']
for face,d in contract['faces'].items():
    a=d['art_coverage'];cols=[]
    for k in ('botanical_only','original_seed_only','information_rules_only','combined_existing_ink_layer'):
        v=a[k];cols.append(f"{v['alpha_nonzero_pixels']} / {v['alpha_coverage_percent']:.4f}%")
    md.append('| '+face+' | '+' | '.join(cols)+' |')
md+=['','These are unions of **nonzero alpha at delivered source resolution**, with antialiasing included, not a percentage of opaque paint or physical ink consumption. Botanical alpha alone is distinct from text/rules/combined alpha. JSON also contains pure text and nontext union counts, exact resized art boxes and hashes. The reconstruction’s occupied union matches all 12 existing ink-only layers; no final image was rewritten.','',
    'B seed geometry and rules are neutral original punctuation/information separators. Their raster stroke widths are `round(stroke)` in the existing renderer (1px for 1.4); SVG strokes remain the recorded vector values. SVG/font rendering must be visually re-proofed in the printer’s editor. No metallic gradient, new foil or embossing is represented as the baseline. Ordinary ink intent and dark #292522 trials remain in the four systems and `dark-ink/`; the purchased ivory/gold is excluded from additional-ink art.','',
    'References: `fonts/production/provenance.json`; `research/type-culture-print/TYPE-REPORT.md`; `research/type-culture-print/FONT-REGISTER.json`; `art/README.md`; per-face `layouts/*.json`; `qa/render-validation.json`; `qa/independent-copy-audit.json`; `qa/independent-visual-review.json`.']
assert contract['checks']['reconstructed_nonzero_ink_union_matches_all_existing_ink_layers'],face_checks
assert zones_contain,'Editing zone excludes occupied glyph pixels'
(OUT/'FINAL-TYPE-AND-ART-CONTRACT.json').write_text(json.dumps(contract,indent=2,ensure_ascii=False),encoding='utf-8')
(OUT/'FINAL-TYPE-AND-ART-CONTRACT.md').write_text('\n'.join(md)+'\n',encoding='utf-8')
print(json.dumps({'faces':len(contract['faces']),'line_records':sum(len(f['lines']) for f in contract['faces'].values()),'nonzero_union_match':True,'D_art_coverage':{k:v['art_coverage']['botanical_only'] for k,v in contract['faces'].items() if k.startswith('D-')},'output':['systems/FINAL-TYPE-AND-ART-CONTRACT.md','systems/FINAL-TYPE-AND-ART-CONTRACT.json']},indent=2))
