"""Separate, sanitized expanded-adult density diagnostic. Does not alter A–D.
Only writes expanded-adult-density proof PNGs, audit JSON and proof note.
Source pixels are not physical measurements or printer-approved plates.
"""
from pathlib import Path
import json,hashlib,re
from collections import defaultdict,Counter
from PIL import Image,ImageDraw,ImageFont
import numpy as np

ROOT=Path(__file__).resolve().parent
SOURCE=ROOT/'copy/full-inclusion-stress.json'
data=json.loads(SOURCE.read_text(encoding='utf-8-sig'))
entries=[e for e in data['selected_entries'] if e['render_in_expanded_adult_density_candidate']]
assert len(entries)==50 and sum(e['word_count'] for e in entries)==285
assert not any(set(e['source_ids'])&{335,248,320,380} for e in entries)
lookup={sid:e for e in entries for sid in e['source_ids']}
FONTS=ROOT/'fonts/production'
STOCK=ROOT/'stock/02-insert-one.png'
assert STOCK.exists()
BG=Image.open(STOCK).convert('RGBA')
INK='#292522'
cache={}
def font(key,size):
    if (key,size) not in cache:cache[(key,size)]=ImageFont.truetype(str(FONTS/(key+'.ttf')),size,layout_engine=ImageFont.Layout.RAQM)
    return cache[(key,size)]
def normal(t):return ' '.join(t.split())
def wrap(t,key,size,w):
    lines=[];line='';ft=font(key,size)
    for word in t.split():
        nxt=(line+' '+word).strip()
        if line and ft.getlength(nxt)>w:lines.append(line);line=word
        else:line=nxt
    if line:lines.append(line)
    return lines
class DiagnosticFace:
    def __init__(self,kind):
        self.kind=kind;self.bg=BG.copy();self.layer=Image.new('RGBA',BG.size);self.draw=ImageDraw.Draw(self.layer);self.ops=[];self.errors=[]
    def text(self,t,x,y,size=26,key='SourceSans3-Regular',align='left',ids=(),maxw=None):
        ft=font(key,size);w=ft.getlength(t,features=['kern','liga']);x0=x-w/2 if align=='center' else x;b=ft.getbbox(t,anchor='lt');box=[round(x0+b[0],3),round(y+b[1],3),round(x0+w,3),round(y+b[3],3)]
        self.draw.text((x0,y),t,font=ft,fill=INK,anchor='lt',features=['kern','liga'])
        if maxw and w>maxw+1:self.errors.append('Width overflow: '+t)
        if box[0]<130 or box[2]>1363 or box[1]<82 or box[3]>962:self.errors.append('Protected envelope overlap: '+t)
        self.ops.append({'text':t,'source_ids':list(ids),'font':'fonts/production/'+key+'.ttf','size_px':size,'tracking_em':0,'features':['kern','liga'],'bbox_px':box,'max_width_px':maxw})
        return y+size
    def para(self,t,x,y,size=26,maxw=1050,step=34,key='SourceSans3-Regular',align='left',ids=()):
        for line in wrap(t,key,size,maxw):self.text(line,x,y,size,key,align,ids,maxw);y+=step
        return y
    def entry(self,sid,x,y,size=26,maxw=340,step=34,key='SourceSans3-Regular',align='left'):
        e=lookup[sid]
        for hardline in e['text'].splitlines():y=self.para(hardline,x,y,size,maxw,step,key,align,e['source_ids'])
        return y
    def rule(self,x1,y1,x2,y2):self.draw.line((x1,y1,x2,y2),fill='#8B7B61',width=1)
    def result(self):return Image.alpha_composite(self.bg,self.layer).convert('RGB')

f1=DiagnosticFace('invitation and expanded adults')
f1.entry(336,746,121,27,1080,34,align='center')
parts=lookup[337]['text'].replace('\r\n','\n').split('\n\n')
prose,datecity,welcome=parts
line1,line2=prose.split('\n')
y=167
for line in (line1,line2):y=f1.para(line,746,y,26,1050,34,align='center',ids=[337])+8
f1.text(datecity,746,295,25,align='center',ids=[337])
# Known groom/bride family blocks; no new relationship labels are printed.
for x,name,town,parents in [(435,'Samir Khan',177,[179,180]),(1058,'Sana Bano',178,[183,184])]:
    f1.text(name,x,354,56,'Baskervville-Regular','center',ids=[174,176],maxw=540)
    f1.entry(town,x,426,26,525,34,align='center')
    y=467
    for sid in parents:y=f1.entry(sid,x,y,26,525,34,align='center')
f1.text(lookup[187]['text']+' '+lookup[181]['text'],435,535,26,align='center',ids=[187,181],maxw=525)
f1.entry(182,435,569,26,525,34,align='center')
f1.entry(185,1058,535,26,525,34,align='center')
f1.entry(186,1058,569,26,525,34,align='center')
f1.rule(204,620,1289,620)
extra=[[250,251,252,253,254,255,256,257],[258,259,260,261,262,264,265,266],[267,271,272,274,345,339,338]]
for x,col in zip([204,567,930],extra):
    y=653
    for sid in col:y=f1.entry(sid,x,y,26,330,34)

f2=DiagnosticFace('literal programme and full adult welcome')
# Literal source event wording, without invented programme/journey headings.
# Source189 gets no venue; the Dawat venue belongs only to source197.
events=[(189,204,125,None),(193,567,125,None),(197,930,125,242),(203,204,351,None),(218,567,351,240),(231,930,351,None)]
event_titles={'Rasm-e-Baan','Rasm-e-Mehndi','Dawat-e-Aam','DJ Night','Nikah'}
for sid,x,y,venue in events:
    e=lookup[sid]
    for hardline in e['text'].splitlines():
        size=29 if hardline in event_titles else 23
        key='SourceSans3-Semibold' if hardline in event_titles else 'SourceSans3-Regular'
        y=f2.para(hardline,x,y,size,330,32,key=key,ids=e['source_ids'])
    if venue:y=f2.entry(venue,x,y+3,23,330,30)
f2.rule(204,486,1289,486)
f2.entry(245,204,511,26,480,34)
f2.entry(246,204,545,26,480,34)
f2.entry(247,204,579,26,480,34)
f2.entry(249,788,533,26,501,34)
heading,host=welcome.split('\n')
f2.text(heading,746,635,32,'Baskervville-Regular','center',ids=[337])
f2.para(host,746,684,24,1085,30,align='center',ids=[337])
names=lookup[379]['text'].split(', ')
assert len(names)==36 and names.count('Arif Khan')==2
for col,x in enumerate([204,483,762,1041]):
    for row,name in enumerate(names[col*9:col*9+9]):
        idx=col*9+row
        f2.text(name+(',' if idx<35 else ''),x,736+row*25,23,ids=[379],maxw=247)

faces=[f1,f2]
def labelled(face,number):
    out=Image.new('RGB',(1613,1313),'#EAE5DC');d=ImageDraw.Draw(out)
    d.text((60,26),'EXPANDED ADULT DENSITY / DIAGNOSTIC ONLY',font=font('SourceSans3-Semibold',27),fill=INK)
    d.text((60,69),f'Insert {number} • selected 50 entries / 285 words across both inserts • no inclusion or printing approval',font=font('SourceSans3-Regular',21),fill=INK)
    out.paste(face.result(),(60,125))
    note='Body 26px; programme 23px; welcome 23px. Expanded density trades name scale and blank space for more adults.' if number==1 else 'Read welcome down consecutive columns. Both Arif Khan entries preserved. Held wording, children and private data withheld.'
    d.text((60,1210),note,font=font('SourceSans3-Regular',21),fill=INK)
    d.text((60,1251),'Source pixels only. Real-stock reading size, process and final inclusion remain Information required.',font=font('SourceSans3-Regular',21),fill=INK)
    return out
for i,f in enumerate(faces,1):labelled(f,i).save(ROOT/'proofs'/f'expanded-adult-density-{i:02d}.png')
board=Image.new('RGB',(3146,1280),'#EAE5DC');d=ImageDraw.Draw(board)
d.text((60,27),'EXPANDED ADULT DENSITY / TWO-INSERT DIAGNOSTIC — NOT A FIFTH FINAL SUITE',font=font('SourceSans3-Semibold',32),fill=INK)
for i,f in enumerate(faces):board.paste(f.result(),(55+i*1538,116))
d.text((60,1200),'Readable source-resolution fit at unchanged detail sizes. Name scale and negative space reduced; physical/premium approval not established.',font=font('SourceSans3-Regular',26),fill=INK)
board.save(ROOT/'proofs/expanded-adult-density-comparison.png')

ops=[o for f in faces for o in f.ops]
byid=defaultdict(list)
for o in ops:
    for sid in o['source_ids']:byid[sid].append(o['text'])
audits=[]
for e in entries:
    sid=e['source_ids'][0]
    rendered=normal(' '.join(byid[sid]))
    expected=normal(e['text'])
    if sid in [174,176]:passed=rendered==expected
    elif sid==181:passed=rendered==normal(lookup[187]['text']+' '+e['text'])
    elif sid==187:passed=rendered==normal(e['text']+' '+lookup[181]['text'])
    else:passed=rendered==expected
    audits.append({'source_ids':e['source_ids'],'source_order':e['source_order'],'expected':e['text'],'rendered_after_permitted_reflow':rendered,'copy_pass':passed,'source_issues':e['source_issues'],'status':'Diagnostic only; source review flags retained'})
geom=[]
for f in faces:
    alpha=np.array(f.layer.getchannel('A'));raw=np.array(f.bg.convert('RGB'));out=np.array(f.result());protected=np.zeros(alpha.shape,bool);protected[:82,:]=True;protected[962:,:]=True;protected[:,:130]=True;protected[:,1363:]=True
    collisions=[]
    for i,a in enumerate(f.ops):
        for b in f.ops[i+1:]:
            aa=a['bbox_px'];bb=b['bbox_px']
            if min(aa[2],bb[2])>max(aa[0],bb[0])+1 and min(aa[3],bb[3])>max(aa[1],bb[1])+1:collisions.append([a['text'],b['text']])
    geom.append({'face':f.kind,'canvas_px':list(BG.size),'minimum_source_font_px':min(o['size_px'] for o in f.ops),'stock_changed_outside_added_ink':int(np.count_nonzero(np.any(raw!=out,axis=2)&(alpha==0))),'protected_overlap_pixels':int(np.count_nonzero((alpha>0)&protected)),'text_box_collisions':collisions,'layout_errors':f.errors,'operations':f.ops})
rendered_words=[w for w in ' '.join(o['text'] for o in ops).split() if any(c.isalpha() or c.isdigit() for c in w)]
assert len(rendered_words)==285
receipt={'scope':'Separate expanded adult density diagnostic, not final A–D or entire62entry inclusion proof','selected_entries':50,'selected_words':285,'actual_rendered_words':len(rendered_words),'source_file_sha256':hashlib.sha256(SOURCE.read_bytes()).hexdigest(),'omitted_source_ids':[335,248,320,380],'private_contact_or_address_data_printed':False,'children_printed':False,'337_once_after_reflow':next(x['copy_pass'] for x in audits if x['source_ids']==[337]),'welcome_names':names,'welcome_count':36,'Arif_Khan_count':names.count('Arif Khan'),'font_sizes':'Family/adult body26px; programme23px; full36welcome23px; no detail shrunk below matched B thresholds','readability_result':'Readable geometric fit at source resolution; smaller56px display names and more crowded adult area sacrifice premium name presence/negative space. This is not premium or physical print approval.','visual_review':{'proof_images_viewed':2,'method':'Both full labelled insert images visually inspected after render; exact word audit uses real-font text layers.','finding':'No clipped practical text, frame competition or apparent line collision. Programme grouping and consecutive welcome columns readable at the supplied source resolution. Additional adult columns reduce ceremonial emphasis.','physical_readability_verified':False},'physical_tested':False,'copy_audit':audits,'geometry':geom,'all_copy_and_geometry_checks_pass':all(x['copy_pass'] for x in audits) and all(not x['layout_errors'] and not x['text_box_collisions'] and x['protected_overlap_pixels']==0 and x['stock_changed_outside_added_ink']==0 for x in geom)}
(ROOT/'qa/expanded-adult-density.json').write_text(json.dumps(receipt,indent=2,ensure_ascii=False),encoding='utf-8')
(ROOT/'proofs/expanded-adult-density-NOTE.md').write_text('''# Expanded adult density diagnostic

These two labelled stock-insert proofs render the50 selected nonprivate adult density entries (285 source words) from `copy/full-inclusion-stress.json`. They are a separate diagnostic, not a fifth final suite, final wording approval or proof that every saved62-entry inclusion fits.

The full36-name welcome order and both distinct Arif Khan entries remain. All #337 blocks appear exactly once after reflow across the two inserts. Held335/248/320, children, private contacts and addresses are withheld. Review flags travel in the audit rather than being silently approved. Known groom/bride parent/elder groups are spatially paired without adding relationship sentences. The saved “The late” is placed with Kasam Khan Alman; no unsourced relationship heading is introduced.

The diagnostic uses genuine Baskervville/Source Sans3 at56px names,26px adult/body lines,23px programme detail and23px welcome list. It tests extra inclusion without shrinking practical type below matched B sizes. Geometric fit alone is not premium acceptance: smaller names, three additional-family columns and tighter welcome rhythm sacrifice negative space. Keep the four final suites as the primary design choice; select expanded inclusion only after reading a real-stock sample and resolving source flags.

See `qa/expanded-adult-density.json` for all50 exact-copy checks, text layers, boxes, preserved-stock pixel checks and source review flags. The annotated margins are proof notes outside the stock, never additional printed copy. Physical sizes/process and final inclusion remain Information required.
''',encoding='utf-8')
print(json.dumps({'copy_failures':[a['source_ids'] for a in audits if not a['copy_pass']],'geometry_summary':[{k:v for k,v in g.items() if k!='operations'} for g in geom],'all_pass':receipt['all_copy_and_geometry_checks_pass']},indent=2))
