"""Exact-stock invitation previews. Python 3 + Pillow(RAQM) + numpy.
Run this script from any directory. All dimensions are screen pixels, not mm.
"""
from pathlib import Path
import json, math, hashlib, shutil, html, base64
from collections import defaultdict
from PIL import Image, ImageDraw, ImageFont, ImageChops
import numpy as np

ROOT = Path(__file__).resolve().parent
BRIEF = ROOT.parent / 'English-Invitation-Ultra-Design-Brief-2026-10-07'
FONTS = ROOT / 'fonts' / 'production'
for name in ['faces','boards','proofs','layouts','ink-only','dark-ink','systems','art','qa','stock','semifinalists']:
    (ROOT/name).mkdir(exist_ok=True)
STOCK = BRIEF/'images'/'confirmed'
if not STOCK.exists():STOCK=ROOT/'stock'
for name in ['01-printing-sleeve.png','02-insert-one.png','03-insert-two.png']:
    p=STOCK/name
    if p.resolve()!=(ROOT/'stock'/name).resolve():shutil.copy2(p,ROOT/'stock'/name)
FULL = Image.open(STOCK/'01-printing-sleeve.png').convert('RGBA')
SLEEVE = FULL.crop((221,214,1310,779))
INSERT = Image.open(STOCK/'02-insert-one.png').convert('RGBA')
SLEEVE.save(ROOT/'stock'/'sleeve-front-crop.png')
LOCK = json.loads((ROOT/'copy'/'copy-lock.json').read_text(encoding='utf-8-sig'))
BLOCKS = {b['id']:b for b in LOCK['blocks']}
NAMES = LOCK['exact_379_source'].split(', ')
assert len(NAMES)==36 and NAMES.count('Arif Khan')==2
PROSE = ['You are warmly invited to celebrate the Nikah of Samir and Sana.',
         'Please join us in our happiness and bless the bride and groom with your good wishes and duas.']
HOST = 'Hanif Khan Alman, Najma Bano and the entire family'
DATECITY = 'Wednesday, 4 November 2026 • Sikar'
CEREMONY = 'Wednesday, 4 November 2026 • 8:00 PM'
VENUE = 'Harshita Marriage Garden, Sikar'
EVENTS = [
 ('Rasm-e-Baan','1 November 2026 • 6:15 PM',[]),
 ('Rasm-e-Mehndi','2 November 2026 • 8:00 PM',[]),
 ('Dawat-e-Aam','3 November 2026 • 6:15 PM',['Meal starts at 7:00 PM','Kayamkhani Marriage Garden, Sardarshahar']),
 ('DJ Night','3 November 2026 • 9:30 PM',[]),
 ('Baraat','4 November 2026 • Road departure at 4:45 PM',['Sardarshahar to Sikar','Gathering: Family residence, Sardarshahar']),
 ('Nikah','4 November 2026 • 8:00 PM',[VENUE])]
CFG = {
 'A':dict(name='The Ceremonial Script',thesis='A poised central axis; generous connected names; a calm two-column programme.',display='ImperialScript-Regular',body='EBGaramond-Regular',emphasis='EBGaramond-Medium',ink='#4D1E2D',accent='#7E483B',art='none; the purchased ornament is sufficient'),
 'B':dict(name='The Russet Editorial',thesis='Offset serif names and an invitation margin; programme and welcome occupy independent reading columns.',display='Baskervville-Regular',body='SourceSans3-Regular',emphasis='SourceSans3-Semibold',ink='#63351E',accent='#B16A24',art='original measured amber seed separator; no enclosing border'),
 'C':dict(name='The Inscription',thesis='Quiet architectural names and paired families; an orderly event ledger makes the dense face useful.',display='Cinzel-Medium',body='SourceSans3-Regular',emphasis='SourceSans3-Semibold',ink='#1D2F4A',accent='#1D2F4A',art='none; sparse rules are information dividers'),
 'D':dict(name='The Garden Margin',thesis='An original flowering stem balances upright serif names; three programme columns create a garden-like rhythm.',display='CormorantUpright-Semibold',body='EBGaramond-Regular',emphasis='EBGaramond-Medium',ink='#173D35',accent='#173D35',art='one original generated botanical, converted to a single pine ink with alpha preserved')
}
FONT_CACHE={}
def font(key,size):
    cache=(key,round(size))
    if cache not in FONT_CACHE:
        FONT_CACHE[cache]=ImageFont.truetype(str(FONTS/(key+'.ttf')),round(size),layout_engine=ImageFont.Layout.RAQM)
    return FONT_CACHE[cache]
def rgb(h):return tuple(int(h[i:i+2],16) for i in (1,3,5))
def width(text,key,size,tracking=0):
    f=font(key,size)
    return f.getlength(text)+(len(text)-1)*tracking*size
def wrap(text,key,size,maxw):
    words=text.split(); lines=[]; line=''
    for word in words:
        trial=(line+' '+word).strip()
        if width(trial,key,size)>maxw and line:lines.append(line);line=word
        else:line=trial
    if line:lines.append(line)
    return lines

class Face:
    def __init__(self,suite,kind):
        self.suite=suite;self.kind=kind;self.cfg=CFG[suite]
        self.bg=SLEEVE.copy() if kind=='sleeve' else INSERT.copy()
        self.w,self.h=self.bg.size
        self.layer=Image.new('RGBA',self.bg.size)
        self.draw=ImageDraw.Draw(self.layer)
        self.ops=[];self.boxes=[];self.errors=[]
    def text(self,text,x,y,size,role='body',align='left',tracking=0,color=None,block=None,maxw=None):
        key=self.cfg.get(role,role);f=font(key,size);color=color or self.cfg['ink']
        tw=width(text,key,size,tracking)
        left=x-tw/2 if align=='center' else (x-tw if align=='right' else x)
        b=f.getbbox(text,anchor='lt')
        if tracking:
            cur=left
            for ch in text:
                self.draw.text((cur,y),ch,font=f,fill=color,anchor='lt',features=['kern','liga'])
                cur+=f.getlength(ch)+tracking*size
        else:self.draw.text((left,y),text,font=f,fill=color,anchor='lt',features=['kern','liga'])
        box=[round(left+b[0],2),round(y+b[1],2),round(left+tw,2),round(y+b[3],2)]
        if maxw and tw>maxw+1:self.errors.append('Line exceeds box: '+text)
        if box[0]<0 or box[1]<0 or box[2]>self.w or box[3]>self.h:self.errors.append('Text clipped: '+text)
        self.ops.append(dict(type='text',text=text,font=key,file='fonts/production/'+key+'.ttf',size_px=size,size_height_percent=round(size/self.h*100,4),x_px=x,y_px=y,alignment=align,tracking_em=tracking,color=color,block=block,bbox_px=box,bbox_percent=[round(box[0]/self.w*100,3),round(box[1]/self.h*100,3),round((box[2]-box[0])/self.w*100,3),round((box[3]-box[1])/self.h*100,3)],features=['kern','liga'],maximum_width_px=maxw))
        return y+b[3]
    def para(self,text,x,y,size,maxw,step=None,role='body',align='left',block=None,color=None):
        key=self.cfg.get(role,role);lines=wrap(text,key,size,maxw);step=step or round(size*1.28)
        for line in lines:
            self.text(line,x,y,size,role,align,color=color,block=block,maxw=maxw);y+=step
        self.boxes.append(dict(block=block,source=text,lines=lines,x_px=x,y_px=y-len(lines)*step,width_px=maxw,height_px=len(lines)*step,line_height_px=step,paragraph_gap_px=0))
        return y
    def line(self,x1,y1,x2,y2,color=None,stroke=1.4):
        color=color or self.cfg['accent'];self.draw.line((x1,y1,x2,y2),fill=color,width=round(stroke))
        self.ops.append(dict(type='line',x1=x1,y1=y1,x2=x2,y2=y2,color=color,stroke=stroke))
    def seed(self,x,y):
        # Small original geometric mark, not a sacred symbol.
        for dx in (-14,0,14):self.draw.ellipse((x+dx-2,y-2,x+dx+2,y+2),fill=self.cfg['accent'])
        self.ops.append(dict(type='seed',x=x,y=y,color=self.cfg['accent']))
    def art(self,x,y,w,h,flip=False):
        p=ROOT/'art'/'garden-pine.png'
        if not p.exists():self.errors.append('Botanical missing');return
        a=Image.open(p).convert('RGBA');a.thumbnail((w,h),Image.Resampling.LANCZOS)
        if flip:a=a.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
        self.layer.alpha_composite(a,(round(x),round(y)))
        self.ops.append(dict(type='art',file='art/garden-pine.png',x=x,y=y,w=a.width,h=a.height,flip=flip))
    def save(self,name,folder='faces'):
        result=Image.alpha_composite(self.bg,self.layer)
        result.convert('RGB').save(ROOT/folder/(name+'.png'))
        self.layer.save(ROOT/'ink-only'/(name+'-ink.png'))
        dark=Image.new('RGBA',self.layer.size,rgb('#292522')+(0,));dark.putalpha(self.layer.getchannel('A'))
        Image.alpha_composite(self.bg,dark).convert('RGB').save(ROOT/'dark-ink'/(name+'-dark.png'))
        self.write_svg(name)
        spec=dict(suite=self.suite,face=self.kind,size=[self.w,self.h],units='source image pixels; physical dimensions unknown',operations=self.ops,text_boxes=self.boxes,errors=self.errors)
        (ROOT/'layouts'/(name+'.json')).write_text(json.dumps(spec,indent=2,ensure_ascii=False),encoding='utf-8')
        # Pixel equality is checked where the final ink layer has zero alpha.
        raw=np.array(self.bg.convert('RGB'));out=np.array(result.convert('RGB'));alpha=np.array(self.layer.getchannel('A'))
        unchanged=int(np.count_nonzero(np.any(raw!=out,axis=2)&(alpha==0)))
        protected=np.zeros((self.h,self.w),bool)
        if self.kind=='sleeve':
            protected[165:398,350:745]=True
            protected[:15,:]=True;protected[-15:,:]=True;protected[:,:20]=True;protected[:,-20:]=True
        else:
            protected[:82,:]=True;protected[962:,:]=True;protected[:,:130]=True;protected[:,1363:]=True
        overlaps=int(np.count_nonzero((alpha>0)&protected))
        return dict(name=name,size=[self.w,self.h],stock_changed_outside_ink=unchanged,protected_overlap_pixels=overlaps,ink_coverage_percent=round(np.count_nonzero(alpha)/alpha.size*100,3),errors=self.errors)
    def write_svg(self,name):
        families=sorted({o['font'] for o in self.ops if o['type']=='text'})
        styles=''.join("@font-face{font-family:'%s';src:url('../fonts/production/%s.ttf')}"%(k,k) for k in families)
        parts=[f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{self.w}" height="{self.h}" viewBox="0 0 {self.w} {self.h}"><title>Additional ink only — {name}; prepress starting file, unmeasured physical stock</title><style>{styles}</style>']
        # Baseline uses the exact chosen font ascent; SVG keeps live editable text.
        for o in self.ops:
            if o['type']=='text':
                f=font(o['font'],o['size_px']);bbox=f.getbbox(o['text'],anchor='ls');baseline=o['y_px']-bbox[1]
                anchor={'left':'start','right':'end','center':'middle'}[o['alignment']]
                parts.append(f'<text x="{o["x_px"]}" y="{baseline}" font-family="{o["font"]}" font-size="{o["size_px"]}" text-anchor="{anchor}" fill="{o["color"]}" letter-spacing="{o["tracking_em"]}em">{html.escape(o["text"])}</text>')
            elif o['type']=='line':parts.append(f'<line x1="{o["x1"]}" y1="{o["y1"]}" x2="{o["x2"]}" y2="{o["y2"]}" stroke="{o["color"]}" stroke-width="{o["stroke"]}"/>')
            elif o['type']=='seed':
                for dx in (-14,0,14):parts.append(f'<circle cx="{o["x"]+dx}" cy="{o["y"]}" r="2" fill="{o["color"]}"/>')
            elif o['type']=='art':
                transform=f'translate({2*o["x"]+o["w"]} 0) scale(-1 1)' if o['flip'] else ''
                parts.append(f'<image x="{o["x"]}" y="{o["y"]}" width="{o["w"]}" height="{o["h"]}" xlink:href="../{o["file"]}" transform="{transform}"/>')
        parts.append('</svg>');(ROOT/'layouts'/(name+'-ink.svg')).write_text(''.join(parts),encoding='utf-8')

def prep_art():
    src=Path('C:/Users/samir/.codex/generated_images/01a11327-0dc1-7471-9cfb-c82d0f69fd84/exec-2bf0186a-3fa5-4d21-bb62-07b3a6bfabf5.png')
    if src.exists():
        shutil.copy2(src,ROOT/'art'/'garden-original-generated.png')
        a=Image.open(src).convert('RGBA');b=Image.new('RGBA',a.size,rgb('#173D35')+(0,));b.putalpha(a.getchannel('A'));b.save(ROOT/'art'/'garden-pine.png')

def sleeve(s):
    f=Face(s,'sleeve')
    if s=='A':
        f.text('Samir & Sana',544,42,122,'display','center',block='sleeve_names')
        f.text('Nikah',544,420,40,'emphasis','center',block='sleeve_event')
        f.text('4 November 2026',544,478,30,'body','center',block='sleeve_date')
    elif s=='B':
        f.text('Samir & Sana',128,48,85,'display',block='sleeve_names')
        f.text('Nikah',128,438,36,'display',block='sleeve_event')
        f.text('4 November 2026',957,442,30,'body','right',block='sleeve_date')
        f.seed(957,112)
    elif s=='C':
        f.text('Nikah',544,68,32,'body','center',tracking=.12,block='sleeve_event')
        f.text('Samir & Sana',544,416,66,'display','center',block='sleeve_names')
        f.text('4 November 2026',544,500,27,'body','center',block='sleeve_date')
    else:
        f.art(118,30,85,134)
        f.text('Samir & Sana',625,63,92,'display','center',block='sleeve_names')
        f.text('Nikah',544,428,36,'emphasis','center',block='sleeve_event')
        f.text('4 November 2026',544,481,29,'body','center',block='sleeve_date')
    return f

def invitation(s):
    f=Face(s,'invitation');cx=746
    if s=='A':
        f.text('Alhamdulillah',cx,118,31,'body','center',block='opening')
        y=185
        for p in PROSE:y=f.para(p,cx,y,28,880,35,align='center',block='invitation_prose')+9
        f.text('Samir Khan',cx,332,109,'display','center',block='groom_name')
        f.text('Son of Hanif Khan Alman and Najma Bano',cx,455,28,'body','center',block='groom_parents')
        f.text('&',cx,504,38,'body','center',block='connector')
        f.text('Sana Bano',cx,553,109,'display','center',block='bride_name')
        f.text('Daughter of Abbas Khan and Jubeda Bano',cx,676,28,'body','center',block='bride_parents')
        f.text(DATECITY,cx,747,29,'body','center',block='invitation_date_city')
        f.text('Nikah',cx,806,44,'emphasis','center',block='ceremony_title')
        f.text(CEREMONY,cx,872,28,'body','center',block='ceremony_datetime')
        f.text(VENUE,cx,916,29,'body','center',block='ceremony_venue')
    elif s=='B':
        f.text('Alhamdulillah',211,124,26,'body',block='opening')
        f.seed(1247,137)
        f.text('Samir Khan',211,231,84,'display',block='groom_name')
        f.para('Son of Hanif Khan Alman and Najma Bano',211,340,26,610,33,block='groom_parents')
        f.text('&',211,421,41,'display',block='connector')
        f.text('Sana Bano',211,481,84,'display',block='bride_name')
        f.para('Daughter of Abbas Khan and Jubeda Bano',211,598,26,610,33,block='bride_parents')
        y=235
        for p in PROSE:y=f.para(p,926,y,26,365,36,block='invitation_prose')+28
        f.line(878,224,878,668,stroke=1.4)
        f.line(211,720,1285,720,stroke=1.4)
        f.text('Nikah',211,759,46,'display',block='ceremony_title')
        f.text(DATECITY,211,830,26,'body',block='invitation_date_city')
        f.text(CEREMONY,211,872,26,'body',block='ceremony_datetime')
        f.text(VENUE,211,914,28,'body',block='ceremony_venue')
    elif s=='C':
        f.text('Alhamdulillah',cx,125,28,'body','center',block='opening')
        y=202
        for p in PROSE:y=f.para(p,cx,y,26,900,34,align='center',block='invitation_prose')+8
        f.text('Samir Khan',447,369,67,'display','center',block='groom_name')
        f.text('Sana Bano',1046,369,67,'display','center',block='bride_name')
        f.text('&',cx,386,39,'display','center',block='connector')
        f.para('Son of Hanif Khan Alman and Najma Bano',447,477,26,480,35,align='center',block='groom_parents')
        f.para('Daughter of Abbas Khan and Jubeda Bano',1046,477,26,480,35,align='center',block='bride_parents')
        f.line(289,600,1204,600,stroke=1.4)
        f.text('Nikah',cx,650,51,'display','center',block='ceremony_title')
        f.text(DATECITY,cx,740,27,'body','center',block='invitation_date_city')
        f.text(CEREMONY,cx,801,27,'body','center',block='ceremony_datetime')
        f.text(VENUE,cx,862,29,'emphasis','center',block='ceremony_venue')
    else:
        f.text('Alhamdulillah',880,123,31,'body','center',block='opening')
        f.art(210,234,245,405)
        f.text('Samir Khan',875,242,88,'display','center',block='groom_name')
        f.para('Son of Hanif Khan Alman and Najma Bano',875,353,28,748,35,align='center',block='groom_parents')
        f.text('&',875,425,35,'body','center',block='connector')
        f.text('Sana Bano',875,477,88,'display','center',block='bride_name')
        f.para('Daughter of Abbas Khan and Jubeda Bano',875,589,28,748,35,align='center',block='bride_parents')
        y=649
        for p in PROSE:y=f.para(p,cx,y,28,900,34,align='center',block='invitation_prose')+7
        f.text(DATECITY,cx,803,29,'body','center',block='invitation_date_city')
        f.text('Nikah',330,868,45,'display',block='ceremony_title')
        f.text(CEREMONY,907,865,26,'body','center',block='ceremony_datetime')
        f.text(VENUE,907,912,28,'emphasis','center',block='ceremony_venue')
    return f

def welcome(f,xs,y,size=24,step=26,count=9,align='left'):
    # A replacement name may not enter the next column's gutter.
    editing_width=min(250,min(abs(xs[i+1]-xs[i]) for i in range(len(xs)-1))-24) if len(xs)>1 else 250
    for col,x in enumerate(xs):
        for row,name in enumerate(NAMES[col*count:(col+1)*count]):
            f.text(name,x,y+row*step,size,'body',align,block='welcoming_list',maxw=editing_width)

def event(f,index,x,y,w,title=31,body=24,step=29,align='left'):
    t,dt,extra=EVENTS[index]
    f.text(t,x,y,title,'display' if f.suite in ['B','D'] else 'emphasis',align,block='programme_'+str(index))
    y+=title+12
    y=f.para(dt,x,y,body,w,step,align=align,block='programme_'+str(index))
    for line in extra:y=f.para(line,x,y,body-1,w,step,align=align,block='programme_'+str(index))
    return y

def programme(s):
    f=Face(s,'programme');cx=746
    if s=='A':
        f.text('Wedding Programme',cx,112,43,'emphasis','center',block='programme_heading')
        for i in range(6):event(f,i,[211,803][i%2],[195,304,459][i//2],483,32,24,29)
        f.line(211,598,1284,598)
        f.text('Welcoming you',cx,624,34,'emphasis','center',block='welcome_heading')
        f.text(HOST,cx,672,25,'body','center',block='welcome_host')
        welcome(f,[211,487,763,1039],720,24,25.5)
    elif s=='B':
        f.text('Wedding Programme',211,115,42,'display',block='programme_heading')
        f.line(211,184,1284,184)
        f.line(806,219,806,927,stroke=1.4)
        yy=[220,311,402,548,639,808]
        for i in range(6):event(f,i,211,yy[i],555,29,23,27)
        f.text('Welcoming you',865,220,32,'display',block='welcome_heading')
        f.para(HOST,865,273,24,423,30,block='welcome_host')
        welcome(f,[865,1083],388,23,30,18)
    elif s=='C':
        f.text('Wedding Programme',cx,116,35,'display','center',block='programme_heading')
        f.line(207,183,1287,183)
        yy=[195,249,303,390,444,531]
        for i,(title,dt,extra) in enumerate(EVENTS):
            f.text(title,211,yy[i],25,'emphasis',block='programme_'+str(i))
            f.para(dt,580,yy[i],23,709,27,block='programme_'+str(i))
            y=yy[i]+29
            for line in extra:y=f.para(line,580,y,22,709,27,block='programme_'+str(i))
        f.line(207,608,1287,608)
        f.text('Welcoming you',cx,631,30,'emphasis','center',block='welcome_heading')
        f.text(HOST,cx,674,24,'body','center',block='welcome_host')
        welcome(f,[211,487,763,1039],716,23,27)
    else:
        f.text('Wedding Programme',cx,114,45,'display','center',block='programme_heading')
        # Reading down each column: 1/2 Nov, 3 Nov, 4 Nov; no invented headings.
        xs=[202,597,992]
        for col,pair in enumerate([(0,1),(2,3),(4,5)]):
            event(f,pair[0],xs[col],211,304,29,24,28)
            event(f,pair[1],xs[col],452 if col==2 else 424,304,29,24,28)
        f.line(202,593,1292,593)
        f.text('Welcoming you',cx,615,34,'display','center',block='welcome_heading')
        f.text(HOST,cx,664,25,'body','center',block='welcome_host')
        welcome(f,[213,491,769,1047],714,24,27)
    return f

def board_text(draw,text,x,y,size=25,color='#292522',key='SourceSans3-Regular'):
    draw.text((x,y),text,font=font(key,size),fill=color,anchor='lt')

def suite_board(s,faces,name=None):
    # Same screen scale for all pieces, no invented assembled size relationship.
    scale=.70;pad=64;slot=round(1493*scale);h=round(1053*scale)
    b=Image.new('RGB',(3*slot+4*pad,h+245),'#EAE5DC');d=ImageDraw.Draw(b)
    board_text(d,s+'  /  '+CFG[s]['name'],pad,42,38)
    board_text(d,CFG[s]['thesis'],pad,104,25)
    for j,img in enumerate(faces):
        im=img.convert('RGB');im=im.resize((round(im.width*scale),round(im.height*scale)),Image.Resampling.LANCZOS)
        x=pad+j*(slot+pad)+(slot-im.width)//2;y=180+(h-im.height)//2
        b.paste(im,(x,y));board_text(d,['SLEEVE FRONT','INVITATION','PROGRAMME'][j],pad+j*(slot+pad),h+197,23)
    b.save(ROOT/'boards'/(name or s+'-suite-board.png'))

def placement(s,f):
    bg=FULL.copy();bg.alpha_composite(f.layer,(221,214))
    paper=Image.new('RGB',(1776,1244),'#EAE5DC');paper.paste(bg.convert('RGB'),(120,120));d=ImageDraw.Draw(paper)
    board_text(d,s+' / FULL SLEEVE PLACEMENT — PROPOSED SCREEN PROOF',120,39,28)
    # Proof-only marks; never exported in additional-ink files.
    x0,y0=341,334
    d.rectangle((x0,y0,x0+1089,y0+565),outline='#577981',width=2)
    d.rectangle((x0+350,y0+165,x0+745,y0+398),outline='#AA5555',width=2)
    board_text(d,'Blue: estimated front crop. Red: protected medallion + opening. All folds and flaps remain clear.',120,1169,24)
    paper.save(ROOT/'proofs'/(s+'-full-sleeve-placement.png'))
    f.layer.save(ROOT/'ink-only'/(s+'-01-front-ink.png'))
    whole=Image.new('RGBA',FULL.size);whole.alpha_composite(f.layer,(221,214));whole.save(ROOT/'ink-only'/(s+'-full-sleeve-ink.png'))

def density(s,f):
    b=Image.new('RGB',(1613,1253),'#EAE5DC');d=ImageDraw.Draw(b)
    board_text(d,s+' / PROPOSED DENSITY TEST — ALL 36 WELCOMING NAMES',60,30,28)
    b.paste(Image.alpha_composite(f.bg,f.layer).convert('RGB'),(60,105))
    board_text(d,'Read down consecutive columns. Both Arif Khan entries retained. Spellings/inclusion remain under review.',60,1182,22)
    b.save(ROOT/'proofs'/(s+'-long-copy-density.png'))

def system_sheet(s,fs):
    c=CFG[s];allops=[o for f in fs for o in f.ops if o['type']=='text']
    roles=defaultdict(list)
    for o in allops:roles[o['block']].append(o)
    spec={'suite':s,**c,'faces':{f.kind:{'canvas_px':[f.w,f.h],'operations':f.ops,'text_boxes':f.boxes} for f in fs},'dark_ink_fallback':'#292522; same alpha, geometry, stock and text','print_status':'Prepress starting artwork, source pixels only. Physical measurements, minimum stroke, adhesion and registration are Information required. No foil assumed.'}
    (ROOT/'systems'/(s+'-design-system.json')).write_text(json.dumps(spec,ensure_ascii=False,indent=2),encoding='utf-8')
    md=f'# {s} — {c["name"]}\n\n{c["thesis"]}\n\nProposed comparison, not final inclusion or print approval. See JSON for every glyph line box and pixel/normalized geometry.\n\n|Role / block|Real file|Size px (% face height)|Tracking em|Alignment|\n|---|---|---|---|---|\n'
    for role,ops in roles.items():
        o=ops[0];md+=f'|{role}|{o["file"]}|{o["size_px"]} ({o["size_height_percent"]:.2f}%)|{o["tracking_em"]}|{o["alignment"]}|\n'
    md+=f'\nEssential ink: {c["ink"]}. Accent: {c["accent"]}. All are RGB screen simulations, no Pantone/CMYK promise. Baseline ordinary flat ink; fallback #292522. Art: {c["art"]}.\n\nRules: no script tracking; genuine packaged font files only; kern/liga enabled; no invented swashes. A long name should wrap by words and be retested optically; do not condense/distort. Every prose box wraps using measured real-font advances. Details use ordinary Western digits. The SVG preserves editable live text; packaged fonts must be installed/resolved, and PNG is the visual authority if an editor differs.\n\nMinimum source clearance: insert ink stays within x130–1363/y82–962, with actual text starting about x200; sleeve medallion protected by x350–745/y165–398 in crop coordinates. This is a conservative screen estimate, not a physical die. Full sleeve transforms add x221/y214. Paragraph rhythm and actual lines are recorded in JSON; names are never auto-shrunk.\n\nAll36 welcoming names are included by design, with consecutive top-to-bottom columns. This tests the common core plus the full welcome list. It is not the entire saved62-entry English print selection: elders/businesses/other families/children and contact variants remain separate owner choices.\n\nRelative mm and type points: Information required. Fine strokes of {c["display"]} require an actual-stock sample. No extra foil/embossing/heat is represented as approved.\n'
    (ROOT/'systems'/(s+'-design-system.md')).write_text(md,encoding='utf-8')

def make_comparison():
    scale=.42;slotw=round(1493*scale);sloth=round(1053*scale);pad=48;rowh=sloth+110
    b=Image.new('RGB',(3*slotw+4*pad,4*rowh+150),'#EAE5DC');d=ImageDraw.Draw(b)
    board_text(d,'SAMIR & SANA / FOUR ENGLISH PRINTING PROPOSALS',pad,35,31)
    board_text(d,'Identical core +36-name copy. Same source-pixel scale; physical piece sizes are unmeasured.',pad,85,22)
    for row,s in enumerate(CFG):
        y0=150+row*rowh;board_text(d,s+' / '+CFG[s]['name'],pad,y0,25)
        for col,kind in enumerate(['sleeve','invitation','programme']):
            im=Image.open(ROOT/'faces'/f'{s}-0{col+1}-{kind}.png');im=im.resize((round(im.width*scale),round(im.height*scale)),Image.Resampling.LANCZOS)
            x=pad+col*(slotw+pad)+(slotw-im.width)//2;y=y0+52+(sloth-im.height)//2;b.paste(im,(x,y))
    b.save(ROOT/'boards'/'twelve-face-comparison.png')

def audit_copy(fs):
    errors=[];required=['opening','invitation_prose','invitation_date_city','groom_name','groom_parents','bride_name','bride_parents','connector','ceremony_title','ceremony_datetime','ceremony_venue','programme_heading','welcome_heading','welcome_host','welcoming_list']
    ops=[o for f in fs for o in f.ops if o['type']=='text'];by=defaultdict(list)
    for o in ops:by[o['block']].append(o['text'])
    expected={'opening':'Alhamdulillah','invitation_prose':' '.join(PROSE),'invitation_date_city':DATECITY,'groom_name':'Samir Khan','groom_parents':'Son of Hanif Khan Alman and Najma Bano','bride_name':'Sana Bano','bride_parents':'Daughter of Abbas Khan and Jubeda Bano','connector':'&','ceremony_title':'Nikah','ceremony_datetime':CEREMONY,'ceremony_venue':VENUE,'programme_heading':'Wedding Programme','welcome_heading':'Welcoming you','welcome_host':HOST}
    for k,v in expected.items():
        if ' '.join(by[k])!=v:errors.append('Copy mismatch '+k)
    if by['welcoming_list']!=NAMES:errors.append('Ordered36-name list mismatch')
    for i,(t,dt,e) in enumerate(EVENTS):
        if ' '.join(by['programme_'+str(i)])!=' '.join([t,dt]+e):errors.append('Programme mismatch '+str(i))
    if any('3:15' in o['text'] for o in ops):errors.append('Excluded home departure printed')
    exact='\n'.join([expected['invitation_prose'],DATECITY,'Welcoming you',HOST])
    return {'suite':fs[0].suite,'text_layer_copy_errors':errors,'welcoming_count':len(by['welcoming_list']),'Arif_Khan_count':by['welcoming_list'].count('Arif Khan'),'337_blocks_each_once':not any('invitation_' in e or 'welcome_' in e for e in errors),'programme_groups':6,'children_in_default':False,'method':'Exact real-font text-layer string equality after permitted line reflow; visual reading is recorded separately.'}

def main():
    prep_art();qas=[];copies=[]
    for s in CFG:
        fs=[sleeve(s),invitation(s),programme(s)]
        for i,f in enumerate(fs):qas.append(f.save(f'{s}-0{i+1}-{f.kind}'))
        suite_board(s,[Image.alpha_composite(f.bg,f.layer) for f in fs]);placement(s,fs[0]);density(s,fs[2]);system_sheet(s,fs);copies.append(audit_copy(fs))
    make_comparison()
    source_names=['01-printing-sleeve.png','02-insert-one.png','03-insert-two.png']
    receipt={'tool':'Python Pillow12.3 with RAQM; real font files; locked PNG stock +alpha ink layers','faces':qas,'copy_audits':copies,'stock_sha256':{name:hashlib.sha256((STOCK/name).read_bytes()).hexdigest() for name in source_names},'physical_tested':False,'final_print_approved':False,'all_checks_pass':all(x['stock_changed_outside_ink']==0 and x['protected_overlap_pixels']==0 and not x['errors'] for x in qas) and all(not x['text_layer_copy_errors'] for x in copies)}
    (ROOT/'qa'/'render-validation.json').write_text(json.dumps(receipt,indent=2,ensure_ascii=False),encoding='utf-8');print(json.dumps(receipt,indent=2,ensure_ascii=False))
if __name__=='__main__':main()
