"""Build a screen-review book and verified portable local delivery pack.
Requires Pillow and ReportLab. No network or external side effects.
"""
from pathlib import Path
import argparse, hashlib, json, re, zipfile, subprocess, sys
from datetime import datetime, timezone
from PIL import Image
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

ROOT=Path(__file__).resolve().parent
def read(p):return json.loads((ROOT/p).read_text(encoding='utf-8-sig'))
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
SUITES=[('B','The Russet Editorial','Warm russet; offset serif names and separate programme / welcome columns.'),
        ('A','The Ceremonial Script','Garnet; connected script names and a centred invitation axis.'),
        ('C','The Inscription','Ink-blue capitals; paired families and an ordered programme ledger.'),
        ('D','The Garden Margin','Pine; original flowering stem, upright serif names, three programme columns.')]
KINDS=['01-sleeve','02-invitation','03-programme']
FONTROOT=ROOT/'fonts'/'production'
pdfmetrics.registerFont(TTFont('Body',str(FONTROOT/'SourceSans3-Regular.ttf')))
pdfmetrics.registerFont(TTFont('Strong',str(FONTROOT/'SourceSans3-Semibold.ttf')))
pdfmetrics.registerFont(TTFont('Display',str(FONTROOT/'Baskervville-Regular.ttf')))

def build_pdf():
    out=ROOT/'REVIEW-BOOK.pdf'; c=canvas.Canvas(str(out),pagesize=(1440,1080),pageCompression=1)
    c.setTitle('Samir & Sana | Four English invitation suites | 7 October 2026')
    c.setAuthor('Private invitation design research')
    pages=0
    def start(title,sub='',size=(1440,1080)):
        nonlocal pages
        pages+=1;c.setPageSize(size);w,h=size
        c.setFillColorRGB(.965,.95,.922);c.rect(0,0,w,h,fill=1,stroke=0)
        c.setFillColorRGB(.17,.14,.12);c.setFont('Display',29);c.drawString(55,h-60,title)
        c.setFont('Body',15);c.drawString(55,h-91,sub)
        c.setStrokeColorRGB(.78,.70,.58);c.line(55,51,w-55,51)
        c.setFont('Body',12);c.drawString(55,29,'PRIVATE SCREEN REVIEW | Physical dimensions / print process unverified | Hindi option retained')
        c.drawRightString(w-55,29,str(pages));return w,h
    def lines(text,y,w=1200,size=20,x=55,leading=29,font='Body'):
        c.setFont(font,size);c.setFillColorRGB(.17,.14,.12)
        for para in text.split('\n'):
            row=''
            for word in para.split():
                test=(row+' '+word).strip()
                if pdfmetrics.stringWidth(test,font,size)>w and row:
                    c.drawString(x,y,row);y-=leading;row=word
                else:row=test
            if row:c.drawString(x,y,row);y-=leading
            y-=8
        return y
    def image_page(p,title,sub='',size=(1440,1080)):
        w,h=start(title,sub,size);im=Image.open(ROOT/p);iw,ih=im.size
        scale=min((w-110)/iw,(h-190)/ih);dw,dh=iw*scale,ih*scale
        c.drawImage(ImageReader(im), (w-dw)/2,68+(h-190-dh)/2,width=dw,height=dh,mask='auto')
        c.showPage()
    w,h=start('Four suites for Samir & Sana','English invitation design research | 7 October 2026')
    y=lines('One purchased card. Four distinct compositions. Twelve clean previews.\nStart with B, The Russet Editorial. Its dark warm ink, composed serif names and independent welcome column make it my recommended first physical sample.',h-170,w-110,28,leading=38,font='Display')
    y=lines('This book is a visual review of the proposed core copy plus all 36 welcome names. The exact approved #337 message is retained once across the inserts. Both Arif Khan entries remain separate. The four suites carry the same comparison content.',y-25,w-110)
    y=lines('Read the actual PNGs at full resolution for small detail. Sleeve previews: 1089 × 565 px. Each insert: 1493 × 1053 px. The boards use a common source-pixel scale; the physical relative sizes remain unmeasured.',y-18,w-110)
    y=lines('The pack includes real font files and licences, editable live-text layouts, transparent additional-ink layers, dark-ink fallbacks, copy/source records, eight rough development boards and the research evidence. Do not send the paper/gold composite to the printer as additional ink.',y-18,w-110)
    lines('Final wording/inclusion review and a test on spare measured stock remain separate. No print order, font purchase, family-database edit, deployment or publication was made.',y-18,w-110)
    c.showPage()
    image_page('boards/twelve-face-comparison.png','The same words, four compositions','One common source-pixel comparison scale; labels sit outside the cards.',(1100,1320))
    for sid,title,thesis in SUITES:
        image_page(f'boards/{sid}-suite-board.png',f'{sid} | {title}',thesis)
        for kind in KINDS:
            label={'01-sleeve':'Sleeve front','02-invitation':'Invitation','03-programme':'Programme & welcome'}[kind]
            dim='1089 × 565 px' if kind=='01-sleeve' else '1493 × 1053 px'
            image_page(f'faces/{sid}-{kind}.png',f'{sid} | {title} | {label}',f'Clean source-resolution composite | {dim} | No review notes printed on the card')
    image_page('research/type-culture-print/palettes/PALETTE-COMPARISON.webp','Eight ink investigations','RGB simulations on the locked stock. Actual ink, light, coating and gold reflection need a physical sample.')
    for sid,title,thesis in SUITES:
        image_page(f'proofs/{sid}-long-copy-density.png',f'{sid} | All 36 welcome names','Proposed core + full welcome-list density test; not automatic approval of the full saved English selection.')
        image_page(f'proofs/{sid}-full-sleeve-placement.png',f'{sid} | Unfolded sleeve placement','Estimated front crop x221 / y214 / 1089 × 565. Opening, medallion and fold exclusions are screen estimates.')
    if (ROOT/'proofs/expanded-adult-density-comparison.png').exists():
        image_page('proofs/expanded-adult-density-comparison.png','Expanded adult density diagnostic','50 sanitized entries / 285 words; see proof notes. Not the complete 62-entry card and not a fifth finalist.')
        for n in ['01','02']:
            image_page(f'proofs/expanded-adult-density-{n}.png',f'Expanded adult diagnostic | Insert {n}','Practical detail sizes retained; name emphasis / negative space reduced. Source flags and physical proof remain pending.')
    w,h=start('Evidence, selection and practical limits','Keep discovery, visual inspection, design judgement and physical proof separate.')
    y=lines('661 unique stationery candidates + 4 cultural records in the link register. 311 inherited records; 354 new candidates this run. 127 actual image visual screens, 48 individual opened/deep studies and 24 comparative layout/type/art studies. No claim that all catalogue links were visually inspected.',h-160,w-110)
    y=lines('58 genuine font families, actual specimens and supported-feature checks. 72 concepts across 12 composition families; 18 shortlisted; eight real three-face development boards; four final suites after critique and revision. Scores are editorial judgements, not scientific measurements.',y-15,w-110)
    y=lines('All 12 final images were visually reviewed. Text layers match the copy lock. Zero protected-zone ink pixels and zero background changes where added-ink alpha is zero. Conservative masks protect the opening/medallion and existing frame. Source PNG hashes are retained.',y-15,w-110)
    y=lines('The accepted backgrounds are AI photo-based reconstructions, not measured manufacturing scans. Tool/backend model identities not disclosed by the tools are not guessed. No new religious quotations, symbols, address, phone, QR destination or missing venue was invented.',y-15,w-110)
    lines('Detailed research and sources: research/stationery/. Exact copy and unresolved records: copy/. Typography, culture, palette and printer checklist: research/type-culture-print/. Selection: research/concepts/FINAL-CRITIQUE.md. All are bundled locally.',y-15,w-110)
    c.showPage()
    w,h=start('From review to a real sample','Recommended first trial: B | The Russet Editorial')
    y=lines('1. Confirm the complete English wording and inclusion choices. The current A–D comparison represents 16 of 62 saved composition entries. The full-inclusion report accounts for the rest; children, private contacts and held wording are explicitly excluded from the sanitized adult diagnostic.',h-160,w-110)
    y=lines('2. Measure both physical pieces and the actual opening / medallion. Agree a safe print zone with the printer. Do not infer millimetres, point sizes or 300 DPI from these pixels.',y-20,w-110)
    y=lines('3. Print ordinary dark ink on spare purchased stock. Check feeding, adhesion, fine serif/script/botanical strokes, actual colour and the smallest names, times and venues at normal distance.',y-20,w-110)
    y=lines('4. Fold and assemble. Check window clearance and registration. Extra foil / embossing / heat treatment requires a separate stock-compatible trial.',y-20,w-110)
    lines('5. Refine the chosen system at the measured size, re-proof every word, and approve the printer’s sample before placing an order. Existing Hindi choices stay available.',y-20,w-110)
    c.showPage();c.save()
    return {'file':out.name,'pages':pages,'screen_review_only':True,'bytes':out.stat().st_size}

def files():
    return sorted(p for p in ROOT.rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.name not in {'DELIVERY-MANIFEST.json','ZIP-RECEIPT.json'} and not p.name.endswith('.tmp'))

def validate():
    required=[]
    for sid in 'ABCD':
        required += [f'faces/{sid}-{kind}.png' for kind in KINDS]
        required += [f'boards/{sid}-suite-board.png',f'proofs/{sid}-full-sleeve-placement.png',f'proofs/{sid}-long-copy-density.png',f'systems/{sid}-design-system.md',f'systems/{sid}-design-system.json']
        required += [f'layouts/{sid}-{kind}-ink.svg' for kind in KINDS]
        required += [f'ink-only/{sid}-{kind}-ink.png' for kind in KINDS]
        required += [f'dark-ink/{sid}-{kind}-dark.png' for kind in KINDS]
    required += ['index.html','gallery.js','gallery.css','boards/twelve-face-comparison.png','copy/copy-lock.json','copy/COPY-MAP.md','copy/FULL-INCLUSION-STRESS.md','copy/full-inclusion-stress.json','research/stationery/source-register.json','research/stationery/counts.json','research/stationery/PATTERN-ATLAS.md','research/concepts/72-CONCEPT-MATRIX.csv','research/concepts/SHORTLIST-18.md','research/concepts/EIGHT-RENDERED-SELECTION.md','research/concepts/FINAL-CRITIQUE.md','research/type-culture-print/TYPE-REPORT.md','research/type-culture-print/PRINT-REVIEW.md','systems/FINAL-TYPE-AND-ART-CONTRACT.md','systems/FINAL-TYPE-AND-ART-CONTRACT.json','proofs/expanded-adult-density-01.png','proofs/expanded-adult-density-02.png','proofs/expanded-adult-density-comparison.png','qa/expanded-adult-density.json','qa/render-validation.json','qa/independent-copy-audit.json','qa/independent-visual-review.json','qa/portable-reproduction.json','qa/pdf-validation.json','REVIEW-BOOK.pdf']
    required += [f'semifinalists/revised/{sid}-revised-three-face.png' for sid in 'EFGH']
    required += ['qa/reserve-revision-independent-review.json','qa/reserve-revision-copy-audit.json','qa/COMPLETENESS-REVIEW.md']
    missing=[p for p in required if not (ROOT/p).is_file()]
    if missing:raise AssertionError('Missing: '+', '.join(missing))
    checks=read('qa/render-validation.json')
    assert checks['all_checks_pass'] and len(checks['faces'])==12
    for f in checks['faces']:
        assert tuple(Image.open(ROOT/'faces'/(f['name']+'.png')).size)==tuple(f['size'])
        assert f['protected_overlap_pixels']==0 and f['stock_changed_outside_ink']==0
    reviewed=read('qa/independent-visual-review.json')
    mismatch=[f['file'] for f in reviewed['files'] if sha(ROOT/f['file'])!=f['sha256']]
    if mismatch:raise AssertionError('Reviewer hash mismatch: '+str(mismatch))
    pngs=list((ROOT/'faces').glob('*.png'));assert len(pngs)==12
    for p in pngs:
        with Image.open(p) as im:im.verify()
    for name,digest in checks['stock_sha256'].items():assert sha(ROOT/'stock'/name)==digest
    refs=[]
    for p in (ROOT/'layouts').glob('[A-D]*-ink.svg'):
        text=p.read_text(encoding='utf-8')
        for path in re.findall(r'(?:url\([\"\']?|href=[\"\'])(\.\./[^\"\')]+)',text):
            if not (p.parent/path).exists():refs.append((p.name,path))
    assert not refs,refs
    assert read('qa/portable-reproduction.json')['all12_identical']
    assert read('qa/pdf-validation.json')['all_pages_rendered']
    expanded=read('qa/expanded-adult-density.json')
    assert expanded['selected_entries']==50 and expanded['actual_rendered_words']==285
    assert all(row['copy_pass'] for row in expanded['copy_audit'])
    for ref in re.findall(r'(?:src|href)=[\"\']([^\"\']+)',(ROOT/'index.html').read_text(encoding='utf-8-sig')):
        if not ref.startswith(('#','http:','https:','data:')):assert (ROOT/ref).exists(),ref
    return {'required_file_checks':len(required),'clean_face_count':12,'reviewed_hashes_match':True,'stock_hashes_match':True,'protected_ink_overlap_pixels':0,'background_changed_outside_ink_pixels':0,'portable12faces_identical':True,'pdf32pages_rendered':True,'expanded50entry_copy_pass':True,'physical_tested':False,'final_print_approved':False}

def package(pdf):
    validation=validate()
    manifest={'prepared_utc':datetime.now(timezone.utc).isoformat(),'pdf':pdf,'validation':validation,'research_counts':read('research/stationery/counts.json'),'files':[{'path':p.relative_to(ROOT).as_posix(),'bytes':p.stat().st_size,'sha256':sha(p)} for p in files()]}
    (ROOT/'DELIVERY-MANIFEST.json').write_text(json.dumps(manifest,indent=2,ensure_ascii=False),encoding='utf-8')
    out=ROOT.parent/(ROOT.name+'.zip')
    with zipfile.ZipFile(out,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as z:
        for p in files()+[ROOT/'DELIVERY-MANIFEST.json']:z.write(p,ROOT.name+'/'+p.relative_to(ROOT).as_posix())
    with zipfile.ZipFile(out) as z:
        assert z.testzip() is None
        count=len(z.infolist())
    receipt={'zip':str(out),'bytes':out.stat().st_size,'sha256':sha(out),'entries':count,'crc_test_pass':True,'manifest_entries':len(manifest['files']),'pdf_pages':pdf['pages'],'validation':validation}
    (ROOT/'ZIP-RECEIPT.json').write_text(json.dumps(receipt,indent=2),encoding='utf-8')
    print(json.dumps(receipt,indent=2))

if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--pdf-only',action='store_true');args=parser.parse_args()
    pdf=build_pdf()
    if args.pdf_only:print(json.dumps(pdf))
    else:
        subprocess.run([sys.executable,str(ROOT/'qa/verify-pdf.py')],check=True,stdout=subprocess.DEVNULL)
        package(pdf)
