from pathlib import Path
import json,csv,hashlib
from fontTools.ttLib import TTFont
ROOT=Path(__file__).resolve().parents[2];OUT=Path(__file__).parent;P=ROOT/'fonts/production'
reg=json.loads((OUT/'FONT-REGISTER.json').read_text())
sources=[
('C01','The arts of the Mughal Empire','V&A','https://www.vam.ac.uk/articles/the-arts-of-the-mughal-empire','4','source-opened','Regional Iranian and northern Indian workshop exchange; rows of flowering plants. Context, not family identity.'),
('C02','Marigold bloom','V&A','https://www.vam.ac.uk/shop/prints/floral-and-still-life/marigold-bloom-2006BL1624.html','4,8','image-visually-inspected','Orange-yellow flower and dark green foliage; isolated vertical botanical treatment. 1600–1700 Mughal watercolour.'),
('C03','Two Panels with Flower Designs','The Met','https://www.metmuseum.org/art/collection/search/825614','4,8','image-visually-inspected','ca.1650 Mughal India painted wood panels: separated stems, red/blue/white flowers and gold ground; no trace/copy used.'),
('C04','Tent Panel with Flowering Motif','The Met','https://www.metmuseum.org/art/collection/search/78207','4','source-opened; no image available','Specifically Rajasthan, late18th-century kalamkari tent furnishing; the page states no image available. Distinguish from Persian manuscript work.'),
('C05','Vegetal Patterns in Islamic Art','The Met','https://www.metmuseum.org/essays/vegetal-patterns-in-islamic-art','4','source-opened','Broad vegetal vocabulary crosses regions and media. Botanical pattern is not proof of particular wedding symbolism.'),
('C06','Geometric Patterns in Islamic Art','The Met','https://www.metmuseum.org/essays/geometric-patterns-in-islamic-art','4','source-opened','Symmetry, interlace and repeat are principles, not mandatory religious motifs.'),
('C07','The Shah Jahan Album / Nanha floral calligraphy folio','The Met','https://www.metmuseum.org/essays/the-shah-jahan-album','4,8','image-visually-inspected','Folio451287: rose-toned outer margin with spaced gold plants and framed centre. Borrow margin breathing room, never the script, animals or composition.'),
('T01','Cinzel','NDISCOVER / Natanael Gama','https://github.com/NDISCOVER/Cinzel','6','source-opened','Roman inscription origin. Ceremonial Latin display only; never call it Islamic calligraphy.'),
('T02','Source Sans 3','Adobe / Paul D. Hunt','https://github.com/adobe-fonts/source-sans','6','source-opened','Open-source text/UI family; practical readable programme companion.'),
('T03','EB Garamond','Octavio Pardo / Georg Duffner','https://github.com/octaviopardo/EBGaramond12','6','source-opened','Open Garamond text companion; actual downloaded font tested rather than commercial Garamond imitation.'),
('T04','Cormorant','Christian Thalmann / Catharsis Fonts','https://github.com/CatharsisFonts/Cormorant','6','source-opened','Developer calls the family display type. Upright cursive provides restrained name expression; keep dense body in a text face.'),
('T05','Bickham Script','Adobe Originals / Richard Lipton','https://fonts.adobe.com/fonts/bickham-script','6','source-opened; commercial benchmark only','Formal calligraphic benchmark. No binary downloaded, no local licensing verified, no claim of exact final typesetting.'),
('T06','Garamond Premier','Adobe Originals / Robert Slimbach','https://fonts.adobe.com/fonts/garamond-premier','6','source-opened; commercial benchmark only','Optical-size/weight benchmark; not installed or redistributed.'),
('T07','Mrs Eaves','Emigre / Zuzana Licko via Adobe Fonts','https://fonts.adobe.com/fonts/mrs-eaves','6','source-opened; commercial benchmark only','Formal short-form serif benchmark; no binary or licensing assumed.'),
('T08','Common Issues in Script Fonts','Monotype Foundry Support','https://foundrysupport.monotype.com/hc/en-us/articles/360061288131-Common-Issues-in-Script-Fonts','6','source-opened','Joining/script-spacing caution. Actual feature lists are verified from local binaries separately.'),
('P01','Printing methods','Bella Figura','https://www.bellafigura.com/customize/printing-methods/','7','source-opened','Flat digital ink, letterpress, foil, engraving and embossing differ. Their own paper compatibility is not compatibility with our stock.'),
('P02','Letterpress design tips','Boxcar Press','https://www.boxcarpress.com/letterpress-design-tips/','7','source-opened','Crisp artwork, line thickness, solids and reverse-type guidance. Their numerical limits remain process-specific examples.'),
('P03','Foil stamping design tips','Boxcar Press','https://www.boxcarpress.com/designing-for-foil-stamping/','7','source-opened','Foil can appear heavier, fine reverses fill, scoring clearances matter; optional only after stock test.'),
('P04','FAQs / paper supply','Boxcar Press','https://www.boxcarpress.com/faqs/','7','source-opened','Paper type/sheet size must be known; compatibility restrictions reinforce stock-testing need.'),
('K01','Contrast (Minimum)','W3C WAI','https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html','8','source-opened','Relative luminance for screen screening; thin text may look weak despite nominal ratio. Not a print standard.'),
('K02','Copper foil invitations with botanical accents','Bella Figura','https://www.bellafigura.com/pressd/copper-foil-invitations-with-botanical-accents/','8','source-opened','Professional warm-copper accent and darker body hierarchy; its foil process is not promised on our stock.')]
rows=[{'id':i,'title':t,'maker':m,'url':u,'lanes':l.split(','),'evidence':e,'lesson':n,'date_checked':'2026-10-07','primary_source':True} for i,t,m,u,l,e,n in sources]
for n,e in enumerate(reg['families'],1):rows.append({'id':f'F{n:02d}','title':e['name']+' metadata and TTF','maker':e['designer'],'url':e['metadataUrl'],'lanes':['6'],'evidence':'source-opened + actual binary inspected + actual-string contact-sheet visually screened','lesson':'See FONT-REGISTER.json for weights, axes, GSUB/GPOS, hashes and OFL provenance.','date_checked':'2026-10-07','primary_source':True})
(OUT/'sources.json').write_text(json.dumps({'primary_sources':rows,'counts':{'nonfont_primary_pages_opened':21,'font_metadata_records_opened':58,'prior_font_families':44,'additional_font_families':14,'actual_font_binaries_inspected':121,'museum_images_visually_inspected':3,'font_families_contact_sheet_visually_screened':58,'final_pairings_deeply_inspected':4,'palette_panels_visually_screened':8},'failed_source_pages':[{'url':'https://github.com/ANRT-Type/Baskervville','result':'web open internal error; Google Fonts metadata/binary fetched successfully instead'}],'boundary':'Font records and museum studies are not wedding-suite candidate counts. No private names were sent in public queries. Museum inspection files remain in temp folder outside deliverable; only links/notes redistributed.'},indent=2),encoding='utf-8')
notes={
'Alex Brush':'Open capitals and expressive connecting rhythm; useful alternative, broader than Imperial and more swash room required.',
'Italianno':'Compact and simple at names; weaker visual authority at equal size and thin small numerals.',
'Petit Formal Script':'Broad, open, almost unjoined rhythm; less ceremonial flourish and more name width.',
'Imperial Script':'Selected A: compact formal loops on both S capitals and elegant ampersand; excellent name rhythm, needs large scale and no tracking.',
'Parisienne':'Clear casual calligraphic names; less formal than the proposed engraved tone.',
'Tangerine':'Light compact cursive with tall S; small text loses authority and is unsuitable for timetable.',
'Ballet':'Spectacular capital coils dominate the stock and crowd the ampersand; reject for this aperture/frame.',
'Ephesis':'Flowing but relatively casual; distinctive e shape has less formal premium rhythm.',
'Luxurious Script':'Tight condensed loops; more difficult at small sizes and less open than Imperial.',
'Carattere':'Heavy directional strokes and pronounced capitals; viable alternate but more theatrical.',
'Beau Rivage':'Broad S and strong ampersand; fine name alternate with more horizontal demand.',
'Lavishly Yours':'Looped flourishes consume vertical clearance; reject dense practical text and conservative sleeve.',
'Fleur De Leah':'Leaf-like embellishment on capitals adds competing art; reject beside factory flourishes.',
'Monsieur La Doulaise':'Long upper loops and thin hairlines complicate stock clearance; reject for programme/body.',
'Lovers Quarrel':'Busy compressed calligraphic joins; diminishes ordinary-English scanning.',
'Qwigley':'Energetic brush rhythm; comparatively informal for the classical gold frame.',
'Corinthia':'Clean and modest script; credible alternate, less ceremonial definition than Imperial.',
'Pinyon Script':'Elegant wide sloping names; ampersand form unusual in this string, less immediate recognition.',
'Great Vibes':'Readable theatrical S and broad name rhythm; credible alternate but capital overshoots need extra room.',
'Allura':'Friendly clear script; safer, but less distinguished formal name treatment.',
'Baskervville':'Selected B: firm balanced classical names, restrained ampersand and legible lowercase; carries art-free hierarchy.',
'GFS Didot':'High-contrast names; fine hairline proof risk and no gain over Baskervville detail pairing.',
'Cinzel':'Selected C: open inscriptional capitals, strong structural change; leave small schedule in mixed-case sans.',
'Instrument Serif':'Narrow display texture saves width but is relatively editorial/fashion-like; alternate, not chosen.',
'Playfair Display':'Broad familiar high-contrast names with decorative ampersand; more dominant than desired here.',
'Forum':'Light inscriptional character, less assertive than Cinzel at the sleeve view.',
'Cinzel Decorative':'Decorative capitals add complexity; ordinary Cinzel is calmer alongside stock gold.',
'DM Serif Display':'Heavy and soft display mass; premium warmth but reduces the frame’s restraint.',
'Cormorant Infant':'Friendly rounded details and elegant proportions; D Upright offers clearer independent voice.',
'Cormorant Upright':'Selected D: curved upright cursive, lively a and graceful ampersand; Semibold600 only large display, not tiny body.',
'Cormorant Garamond':'Graceful thin serif, but display intent and smaller x-height make it weaker for dense practical text.',
'EB Garamond':'Selected A/D companion: compact readable names/body and genuine medium500 for density; robust figure features.',
'Libre Baskerville':'Large x-height and wide structure; readable alternative but takes more family-list width.',
'Bodoni Moda':'Sharp contrast and display drama; hairline risk on uncertain stock.',
'Prata':'Bold hairline contrast and wide names; decorative shape does not improve dense companion use.',
'Marcellus':'Soft inscriptional/flared voice; useful title alternate, limited style range.',
'Cardo':'Bookish and composed; good fallback, less differentiated display personality.',
'Sorts Mill Goudy':'Humanist warmth and open ampersand; promising alternative, not more distinct than four finalists.',
'Old Standard TT':'Traditional severe contrast; numerals and hairlines need more physical proof.',
'Oranienbaum':'Tall economical serif; attractive but weaker style flexibility.',
'Bellefair':'Elegant light tall form; quiet names, weak fine detail at source preview scale.',
'Goudy Bookletter 1911':'Broad literary warmth and decorative ampersand; not the desired clear modern programme.',
'Castoro Titling':'Strong uppercase alternative to C; heavier/more uniform than chosen Cinzel treatment.',
'Della Respira':'Rounded ornamental serif shapes; charming but more vintage/eclectic than stock fit.',
'Lora':'New readable serif fallback, larger x-height; stronger density but greater width than EB.',
'Source Sans 3':'New selected B/C companion: clean mixed-case detail, roomy counters and default equal-width digits.',
'Source Serif 4':'New very legible optical-size family; credible expanded-copy alternative, more text-heavy feel.',
'Crimson Pro':'New warm readable oldstyle serif; viable alternate but EB offers familiar narrower practical texture.',
'Castoro':'New robust book serif; heavy at equal scale, less delicate ceremonial name voice.',
'Alegreya':'New lively literary texture; good body alternate, stylistic energy may crowd factory ornaments.',
'Newsreader':'New contemporary readable serif with optical sizing; distinctive editorial alternate for B.',
'Fraunces':'New soft personality; bouncy shapes shift the mood too far from formal invitation.',
'Literata':'New strong book text and robust x-height; excellent legibility, heavier/more spacious family lists.',
'Spectral':'New calm text serif; body alternate with less memorable display rhythm.',
'Libre Franklin':'New functional sans; excellent details but more utilitarian name form than selected serif.',
'IBM Plex Serif':'New clear sturdy serif; mechanical squared details less complementary to the gold stock.',
'Cormorant SC':'New true small-cap texture; useful secondary heading alternate, no need for third family.',
'Gelasio':'New robust familiar text serif; reads well but less distinct for ceremony display.'}
with (OUT/'FONT-VISUAL-SCREEN.csv').open('w',newline='',encoding='utf-8-sig') as f:
    w=csv.writer(f);w.writerow(['family','origin','evidence','letterform_or_fit_finding'])
    for e in reg['families']:w.writerow([e['name'],'prior44' if e['prior'] else 'new14','Actual-string render viewed in six contact sheets; finalist pairings additionally viewed full sheet',notes[e['name']]])
reg['visual_inspection']={'date':'2026-10-07','58_families':'Actual name, event and date/time contact specimens visually screened; all 8 strings plus family/programme rendered individually. Rendering count is not full-size inspection count.','4_final_pairings':'Full specimen sheets visually inspected, including all 8 strings + 26px family line + 23px programme row.','script_tracking_em':0,'engine':'Pillow12.3 with RAQM True','notes_file':'FONT-VISUAL-SCREEN.csv'}
(OUT/'FONT-REGISTER.json').write_text(json.dumps(reg,indent=2),encoding='utf-8')
fontrows=[]
for f in sorted(P.glob('*.ttf')):
    t=TTFont(f);feats=[]
    for tb in ['GSUB','GPOS']:
        if tb in t and t[tb].table.FeatureList:feats+=list(set(x.FeatureTag for x in t[tb].table.FeatureList.FeatureRecord))
    style=next((n.toUnicode() for n in t['name'].names if n.nameID==2),'')
    fontrows.append(f'| `{f.name}` | {style} / {t["OS/2"].usWeightClass} | '+', '.join(sorted(set(feats)))+' |')
(OUT/'TYPE-REPORT.md').write_text('''# English type decisions and actual-file evidence

The four proposed pairings survive the real-string screen: **A Imperial Script + EB Garamond; B Baskervville + Source Sans 3; C Cinzel + Source Sans 3; D Cormorant Upright + EB Garamond.** These express connected formal calligraphy, classical text elegance, inscriptional architecture and warm upright cursive. The structural layouts still have to supply the suite differences; merely switching these fonts is insufficient.

## What was actually done

44 prior family records were refreshed and 14 new families discovered and downloaded from the primary Google Fonts repository. **58 metadata records, 121 source TTFs** were inspected with fontTools; all have bundled OFL licences. Ten reproducible production TTF files are in `fonts/production/`, with per-file licences and `provenance.json`. Eight variable instances were saved at genuine specified weights; two original static faces copied unchanged. Internal names identify the static instance style. Fonts were loaded from files, not installed into Windows. No commercial binaries were acquired or redistributed.

58 individual 1600×1260 actual-string specimens, six 1800×1700 contact sheets and four 1493×1230 final-pairing sheets were rendered. **58 families were visually screened on the contact sheets and four finalist pairings inspected in full.** This does not claim that all 58 large individual sheets were separately deeply reviewed. Contact sheets test names, event names and date/time; the individual sheets include all eight commissioned strings plus the exact long host-family line and a 23px small programme row. Pillow12.3 RAQM shaped the script; tracking remains zero. See `SPECIMEN-RECEIPTS.json` and `FONT-VISUAL-SCREEN.csv`.

## Selection and alternatives

| Suite | Expressive face | Detail face | Actual letterform reason | Rejected/backup |
|---|---|---|---|---|
| A | Imperial Script Regular400 | EB Garamond Regular400 / Medium500 | Both S capitals have controlled loops; the ampersand belongs to the rhythm; compact name width leaves room by the medallion. | Great Vibes/Alex Brush are broader; Ballet and Fleur De Leah compete with stock decoration. |
| B | Baskervville Regular400 | Source Sans 3 Regular400 / Semibold600 | Upright names and calm classical ampersand; mixed-case sans programme separates ceremony from navigation clearly. | Newsreader is a credible editorial alternate; Libre Baskerville consumes more width. |
| C | Cinzel Medium500 | Source Sans 3 Regular400 / Semibold600 | Inscriptional Latin capitals create an architectural voice; open counters carry names while practical English remains mixed case. | Castoro Titling is heavier; Cinzel Decorative adds unnecessary ornament. |
| D | Cormorant Upright Semibold600 | EB Garamond Regular400 / Medium500 | Warm curved upright cursive, memorable a and ampersand; retains ceremonial restraint in the final pine ink. | Lora Regular400 is a robust body fallback; its larger x-height increases list width. |

[Cinzel's designer](https://github.com/NDISCOVER/Cinzel) identifies its Roman inscription origin; it is not Islamic lettering. [Cormorant's maker](https://github.com/CatharsisFonts/Cormorant) describes a display family, which supports using Upright only for larger names. [Source Sans 3](https://github.com/adobe-fonts/source-sans) supplies dependable practical text. Commercial [Bickham Script](https://fonts.adobe.com/fonts/bickham-script), [Garamond Premier](https://fonts.adobe.com/fonts/garamond-premier) and [Mrs Eaves](https://fonts.adobe.com/fonts/mrs-eaves) were primary-source benchmarks only; no installed licence or exact rendering claimed.

## Features verified from these actual production files

| File | Genuine style / OS2 weight | Supported OpenType tags |
|---|---|---|
'''+ '\n'.join(fontrows)+'''

Do not assume all families offer swashes or optical size. **Imperial has `liga`, `kern`, `case` but no `swsh` or `calt` tag in this file.** Its capital loops are default glyph designs. **Cinzel has no `tnum`**; do not use it for aligned schedules. Source Sans 3 has no `tnum` tag, yet its actual default digits are tabular: each digit measures19.875px at40px in Regular,20.5156px in Semibold. EB Garamond Regular default digits measure19.2031px each at40px; its `tnum`, `lnum`, `onum`, `smcp` and ligature tags are available. Explicitly choose lining figures for practical rows if the renderer supports them; default EB specimens use its default figures. Baskervville and Cormorant Upright support `tnum`, confirmed with equal-width glyph measurement after enabling it. The production finalists have no `opsz` axis. Source Serif4, Newsreader and Literata were investigated as optical-size alternatives, not substituted silently.

## Recommended hierarchy starting rules

The final layout JSON is authoritative for exact chosen pixels/boxes. These proportions are starting rules, not physical point sizes. Sleeve refers to **565px front height**, inserts to**1053px**. Maximum line lengths are set by actual measured font advance; never distort characters to fit.

| Role | Insert px / height% | Sleeve px / height% where used | Style, case, tracking, line-height |
|---|---|---|---|
| Display names | 76–100px /7.22–9.50% (A script may need110px/10.45%) | 90–128px /15.93–22.65% | Genuine display weight; title case except Cinzel glyph design; script0em; serif0 to0.02em; line-height1.05–1.18 |
| Ampersand/connector | Match selected name rhythm, not an unrelated glyph | Match names | Same family; no forced script tracking; separate line only when composition earns it |
| Invitation prose | 27–31px /2.56–2.94% | — | Detail400, sentence case,0em, line-height1.25–1.35; paragraph gap0.5–0.8em |
| Parent/family line | 24–27px /2.28–2.56% | — | Detail400/500, exact name spellings,0em, line-height1.25; use two lines before shrinking |
| Section heading | 33–42px /3.13–3.99% | 27–34px /4.78–6.02% | Genuine medium/semibold; title case; occasional caps0.04em; line-height1.1 |
| Event title | 29–35px /2.75–3.32% | — | Detail500 or600, title case,0em; line-height1.15 |
| Date/time | 24–29px /2.28–2.75% | 24–30px /4.25–5.31% | Detail400/500; Western digits; true tabular default/feature for columns |
| Venue | 24–27px /2.28–2.56% | — | Detail400/500;0em; line-height1.2–1.3; allow logical venue/city wrap |
| 36-name welcome list | 23–25px /2.18–2.37% | — | Detail400/500;0em; column reading order explicit; line-height1.22–1.3 |
| Small practical notes | Minimum23px /2.18% | Minimum24px /4.25% | Detail400/500;0em; no script or hairline display face |

Text boxes start inside x11–89%,y10–90% of inserts and refine against the widest mid-side stock flourishes. Keep at least18px visible separation from gold in the proposed overlay, then increase wherever swashes/side art approach it. Use at least0.5em name-to-adjacent-text gap and approximately1em name-to-art gap; judge actual visible outlines, not just bounding boxes. Sleeve names stay entirely above or below the full medallion exclusion zone and folds. These are visual clearances pending physical measurement.

Long-name rules: prefer an intentional second line or reduce a display font within its stated range; never compress width or shrink details under23px to force a list. EB500 is the A/D density-proof companion, not synthetic bold. If real-stock sampling loses hairlines, replace the large face with its named backup and rerun spacing; do not thicken joining script with an arbitrary stroke. Fallbacks are licensed files in the pack; exact fallback layouts must be remeasured.

All licences preserve designer copyright and OFL terms. The files may accompany editable work with those licence notices; commercial reference fonts must not be included in the transfer.
''',encoding='utf-8')
print('Written sources, type report and font visual screen')
