from pathlib import Path
import json,re,csv,concurrent.futures,requests
from bs4 import BeautifulSoup

OUT=Path(__file__).parent
doc=json.loads((OUT/'source-register.json').read_text(encoding='utf-8'))
records=doc['records']
def base(n):return re.sub(r'[^a-z0-9]+',' ',re.sub(r'\s+V\.?\s*\d+$','',n,flags=re.I).lower()).strip()
def match(maker,name):
    for r in records:
        if maker not in r['maker']:continue
        if base(r['name'])==base(name):return r
        if any(base(a['name'])==base(name) for a in r.get('aliases',[])):return r
    raise ValueError((maker,name))

# This wax-seal listing visibly shows the same Vellum Roses base design.
rose=next(r for r in records if '/mf2558.asp' in r['url'])
wax=next((r for r in records if '/is2558-wxbi.asp' in r['url']),None)
if wax:
    rose.setdefault('aliases',[]).append({'name':wax['name'],'url':wax['url'],'origin':wax['origin'],'dedup_reason':'Same photographed Vellum Roses design; wax seal is a finish/accessory variant, not a new layout.'})
    records.remove(wax)
if not any('copper-foil-invitations-with-botanical' in r['url'] for r in records):
    records.append(dict(id='ST0666',name='Copper botanical Samantha and Timothy custom suite',maker='Bella Figura',url='https://www.bellafigura.com/pressd/copper-foil-invitations-with-botanical-accents/',image_url=None,origin='new',collection_source=None,lanes=[1,8],discovered=True,source_opened=True,image_visually_inspected=True,deeply_analysed=True,shortlisted=True,inspection_provenance='Parent agent browser inspected invitation and rehearsal detail this run; counted once.',notes='Copper expressive names/art paired with darker Marsala body; dense foliage on liner. Additional foil and light small text do not transfer to this purchased stock.'))

BF=['Melrose V.2','Pura Vida V.2','Imari V.2','Scout V.2','Mai V.2','Vayda','Isolde','Delevingne','Charmain','Augustine','Canfield','Heaton','Valerie','Corbin','Ashby','Pennington','Hettie','Harvie','Leland','Monroe','Hughes','Italo','Vivien','Yasmin','Hiriata','Talavera','Palmer','Duval V.2','Derian V.2','Nash','Rhea','Thea','Vitale','Astrid']
SM=['Blush Terrace','Traditional','Golden Rule','Jewel','Breeze','Fresh Air','Pastel','Twist','Lemon Drop','Meadow','Eucalyptus branch','Whisper','Classic Script','Winter Berry','Fresco','Sketched Affection','Anchor','Midnight Stars','Wave','Promise','Villa','Sycamore Creek','Cherry Blossom','Elegant Bloom','Modern Lines','Deco','Typewriter','Harmony','Manor','Revival','Folia','Little Leaf','Classic Greens','Citrus Grove','Modern Drift','Trellis','Modern Wash','Modern Bouquet','Charming Garland','Float','Deep End','Valentine','Classic and Chic','True Affection','Classically Tailored','Dreamy Love','White Magnolia','Romantic Crest','Olive Branch','Lovely Eucalyptus','Eloquence','Love Abloom','Watercolor Crest','Watercolor Swash','Snowfall Wreath','Traditional Elegance','Classic Belle','Heirloom Romance','Homewood','Enchanted Drift','Fairfield','Elegant Floral','Arbor Love','Sweet Bouquet','Harvest Garden','Blissful Wreath','Gatehouse Floral','Floral Script','Simple Romance','Dreamy Willow','Sweet Peony','Plantation Floral']
PA=['Islamic Wedding Invitation | Vellum Romance - BI','Vellum Roses','Indigo Symphony','Islamic Wedding Invitation | Golden Orchid - BI','Muslim Wedding Card | Pastel Palettes - BI','Islamic Wedding Invitation | Foil Fantasy - BI','Wedding Frame - NA','Islamic Wedding Invitation | Color Bonanza - BI','Muslim Wedding Card | Burnished Gold - BI','Floral Splash - NA','Banarasi Texture - NA','Regal Meadow - BI','Blossom of Vows - BI','Regal Curve - NA','Timeless Ivory - BI','Muslim Wedding Card | Purple Flora - BI','Verve Vows - BI (Ivory)','Muslim Wedding Card | Floral Brown - BI','Passport Invite-1','Acrylic Fusion - BI']
for maker,names,source in [('Bella Figura',BF,'https://www.bellafigura.com/wedding-invitations/all/'),('Smitten on Paper',SM,'https://smittenonpaper.com/pages/signature-wedding'),('Parekh Cards',PA,'https://www.parekhcards.com/Muslim-Wedding-Cards.asp')]:
    for name in names:
        r=match(maker,name)
        r['image_visually_inspected']=True
        r['inspection_provenance']='This-run Chrome catalogue viewport screenshots, named item matched against visible DOM; compositional thumbnail screen only.'
        r['visual_evidence_url']=source
        r['inspection_scale']='Catalogue product thumbnail at approximately 190-310 screen pixels across; no paper/ink or fine-print certification.'

# Structured close-fit studies are editorial observations, not traced or copied layouts.
# columns: maker, name, format, density, names, body, grid, art, ink, useful principle, stock-specific failure.
DATA=[
['Bella Figura','Canfield','Portrait main card; exact ratio not measured','Moderate invitation; several distinct short blocks','Two spacious lines of formal script','Quiet Roman detail','Centered invitation with wide unfilled side margins','Rich florals in companion packaging; quiet main field','Dark brown detail plus warm finish in named source','Keep the invitation field calm while the bought stock carries richness','Do not add its dark mount/frame or reproduce its extra embossing; script details cannot carry the programme.'],
['Bella Figura','Valerie','Portrait with one organic side edge; ratio not measured','Moderate','Small Roman name with flowing script surname','Small conventional detail','Left aligned invitation field, botanical mass on right','One large right-side leaf silhouette','Very pale/blind relief appearance; image cannot prove finish','Asymmetry works when one clear text edge is sustained','The diecut/big leaf consumes printable area; use only a tiny original edge sprig and dark details.'],
['Bella Figura','Corbin','Portrait; ratio not measured','Low-moderate','Large stacked Roman capitals','Quiet small Roman with script connector','Strong central axis, names dominate upper half','Almost no new picture art','Dark essential type on white','Expressive serif names can be as ceremonial as script','Its short copy does not prove our long names fit; preserve separate body-size threshold.'],
['Bella Figura','Augustine','Portrait; ratio not measured','Low','Large stacked highly flourished names','Compact small Roman facts','Display block fills upper two thirds; compressed detail below','Flourishes belong to letters','Dark names on dusty warm paper','One expressive display block can supply all personality','Do not let loops collide or force practical information into the tiny remaining base; coloured paper cannot replace stock.'],
['Bella Figura','Harvie','Portrait; ratio not measured','Low','Oversized inscriptional Roman names plus joining script fragments','Small compact detail at bottom','Names set as several large lines','No picture art','Dark paper with subtle darker display and light facts','A mostly typographic suite can earn richness through scale','Low-contrast large names and reversed dark panel are unsuitable additional ink on ivory.'],
['Bella Figura','Italo','Portrait; ratio not measured','Moderate','Calm classical Roman names','Roman details with selective script','Centered hierarchy broken into several visibly distinct blocks','Two controlled perimeter rules','Dark core text with restrained frame colour','Separate names, date and place with spacing rather than ornament','Do not duplicate its rules over the purchased double gold frame.'],
['Bella Figura','Leland','Portrait; ratio not measured','Low-moderate','Very large stacked narrow Roman names','Small Roman facts','Long upper name block and lower detail island','No picture art','Dark type on blue textured sheet','Allow multi-line long names deliberately, with a consistent axis','Portrait stacking would be too tall on the sleeve; pale coloured ground is outside scope.'],
['Bella Figura','Talavera','Landscape; exact ratio not measured','Moderate','Bold informal lower-case names','Selective script opening/closing and compact Roman facts','Broad centered name lines; comparatively wide lower detail area','Quiet pale overall texture','Strong blue names','Landscape can preserve substantial name scale without a second art border','The informal display voice may weaken ceremony; inherited texture cannot be printed as a new background.'],
['Bella Figura','Palmer','Portrait; ratio not measured','Low-moderate','Condensed uppercase display names','Small italic/serif details','Names occupy full upper width, lower detail is offset right','A compact lower-left palm drawing balances lower-right details','Single coral/warm ink look','Place a small original art cluster opposite a quiet detail column','Palms/location cannot be borrowed as family facts; bright coral essential text needs darker fallback.'],
['Bella Figura','Duval V.2','Portrait; ratio not measured','Moderate','Two separated script name lines','Compact upright serif','Centered invitation, upper names and lower detail islands','Fine striped perimeter','Very light warm type on ivory','Rhythm comes from fixed gaps between copy roles','Pale thin script and extra frame cannot survive as practical print strategy here.'],
['Bella Figura','Nash','Portrait; ratio not measured','Moderate','Roman capitals with one large isolated decorative connector','Small Roman facts','Centered, generous separate names and details','Tiny repeating perimeter ornament','Dark neutral text','A single connector supplies enough specialness','Its repeating border would become a third competing frame.'],
['Bella Figura','Rhea','Portrait; ratio not measured','Moderate','Highly flourished script names','Roman body','Centered name block crossed by physical thread','Thread/medallion is a separate assembly feature','Dark core text with existing warm edge','Treat material/assembly as distinct from typesetting','Physical thread overlaps names; cannot imply we can tie or print over the aperture.'],
['Bella Figura','Thea','Portrait; ratio not measured','Low-moderate','Formal script','Small upright details','Widely spaced central axis','Single physical oval seal in middle','Warm pale foil appearance on coloured textured stock','A physical object needs protected space in the grid','Do not typeset on our aperture; light warm essential copy and changed stock are rejected.'],
['Bella Figura','Vitale','Portrait clipped-corner card; ratio not measured','Low','Thin large Roman mixed-case names on two lines','Lower Roman facts with small script close','Two major text islands separated by a wide middle pause','Very quiet blind botanical field','Dark names/detail on pale stock','A large pause can make a restrained invitation feel intentional','Middle blank cannot simply waste scarce programme room; physical embossing is not available evidence for this stock.'],
['Bella Figura','Astrid','Multi-piece portrait pocket system; component ratio not measured','Several cards share information','Flowing script title names','Upright facts on separate cards','Main invitation right, stacked auxiliary cards left','Scalloped card edges supply shared identity','Blue ink and blue paper companions','A suite belongs together through one repeated hierarchy even when grids differ','No new pockets/diecut shapes; both actual inserts remain equal landscape backgrounds.'],
['Bella Figura','Hiriata','Portrait; ratio not measured','Moderate','Widely spaced Roman capitals','Upright small capitals/serif','Centered name and fact islands','Patterned double frame','Dark cool type and blue frame','Inscriptional type can carry dignity without script','Additional frame is disallowed; tracking must not undermine smaller family lines.'],
['Smitten on Paper','Breeze','Portrait main card and envelope; ratio not measured','Moderate, several short detail blocks','Large initial identity mark; small names in text field','Upright detail','Left aligned prose and stacked independent blocks','Art-free main field; coloured liner','Dark neutral on ivory','A fixed left edge makes information groups easy to compare','Initials require approval; the smaller underlying detail cannot be copied at an unverified size.'],
['Smitten on Paper','Golden Rule','Portrait; ratio not measured','Moderate','Strong Roman stacked full names','Upright detail','Centered upper names with separate lower prose block','Large flowers confined to liner','Dark main type','Keep figurative richness away from the reading surface','The liner illustration is proprietary; our sleeve already supplies rich material identity.'],
['Smitten on Paper','Fresh Air','Portrait; ratio not measured','Moderate','Restrained Roman names','Upright details and small script close','Continuous calm central text field','Single-colour botanical detail mainly liner','Green dark-ish details on pale ground','Original art can stay subordinate and still establish a suite','Do not copy the plant illustration or treat green as compulsory.'],
['Smitten on Paper','Twist','Square-looking main card; exact ratio not measured','Low-moderate','Small classical Roman names','Upright body','Centered names/date/place with generous paragraph gaps','Art-free front; solid dark liner','Dark type on white','Spacing and paragraph grouping replace added decoration','The short payload is not density proof; retain the same grouping when using a landscape programme.'],
['Smitten on Paper','Eucalyptus branch','Portrait; ratio not measured','Moderate','Script names positioned high and to left','Upright body','Light asymmetry from high-left identity and calm detail below','Fine branch outline descends beneath names','Quiet grey detail','One branch can mark a transition without becoming a frame','Existing side flourishes limit the same branch placement; pale outlines are accent only.'],
['Smitten on Paper','Classic Script','Portrait; ratio not measured','Moderate','Oversized joined script','Much of practical copy also script','One long central script stack','No extra front art; striped liner','Dark script','Names may be expressive while outer material stays simple','This is a useful rejection: timings and long programme labels must not use script.'],
['Smitten on Paper','Villa','Portrait; ratio not measured','Moderate','Large high-left script spanning much of card width','Upright centered detail','High display-name block then quieter narrower prose','Botanical liner only','Dark type on white','Let names depart slightly from the body alignment while preserving a stable reading field','Do not let the name swashes touch bought stock gold; long names need width proof.'],
['Smitten on Paper','Wave','Portrait; ratio not measured','Low-moderate','Loose script','Roman facts with a large numeric date marker','Names high; date number creates second hierarchy stop','Watercolour liner only','Dark text, cool liner','A date can become a clear second anchor after names','Loose lettering is less formal; large number alone cannot lose month/year or mean programme order.'],
['Smitten on Paper','Typewriter','Portrait; ratio not measured','Moderate','Quiet narrow Roman names','Upright compact details','Strong horizontal separators and date/time compartments','Art-free front','Dark text inside darker mount','Practical information benefits from distinct labelled rows/compartments','Do not add its heavy mount and rules; translate compartments into whitespace.'],
['Smitten on Paper','Modern Lines','Portrait; ratio not measured','Moderate','Restrained Roman full names','Compact upright body','Center axis with visible gaps','Geometric pattern only on liner','Dark neutral text','Shared graphic language can remain off the primary field','Copying the liner pattern or adding multiple rules would compete with factory gold.'],
['Smitten on Paper','Folia','Portrait; ratio not measured','Low-moderate','Stacked spaced Roman names','Upright detail','Separated name blocks with a tiny botanical midpoint','One small leaf mark between names; larger liner foliage','Dark readable type','A tiny original mark can separate two people without filling margins','Vertical full-name stacking is costly on landscape; small body letters need physical proof.'],
['Smitten on Paper','Little Leaf','Portrait; ratio not measured','Moderate','Small Roman names','Upright detail plus small script close','Clear central blocks','Tiny horizontal leaf dividers','Dark type on ivory','An original divider can recur across three different grids','Do not use more dividers than meaningful sections or confuse an art mark with an event indicator.'],
['Smitten on Paper','Classic Greens','Portrait; ratio not measured','Moderate','Roman names with clear spacing','Upright details','Centered continuous text with calm margins','Small top sprig, leafy liner','Dark core with green art','One small top art mark is sufficient when names carry scale','Plant identity is not prescribed; mark must shrink around stock top clearance.'],
['Smitten on Paper','Trellis','Portrait; ratio not measured','Moderate','Quiet script names','Upright body','Centered structure within spare field','Two delicate opposing corner marks','Dark type on ivory, rich liner','Diagonal art balance leaves the middle wide for copy','Our side flourishes prohibit copying full corner growth; use original compact buds.'],
['Smitten on Paper','Modern Wash','Portrait; ratio not measured','Moderate','Calm Roman names','Upright details','Clear names and facts; generous unfilled field','Almost art-free main card; soft art liner','Dark neutral core','The stock can supply all ornament and still feel complete','Coloured watercolour ground/liner cannot be recreated as ink over purchased paper.'],
['Smitten on Paper','Classic and Chic','Landscape; exact ratio not measured','Moderate','Two strong Roman full-name rows','Compact upright prose/date/place','Wide centered field; paragraph islands','Single quiet rounded inner frame','Dark text with pale gold frame','A landscape invitation can be ceremonial and compact without script','Our existing double frame already fulfils the border role; no third rectangle.'],
['Smitten on Paper','True Affection','Portrait; ratio not measured','Moderate','Bold serif first names with a script connector','Upright detail','Strong name block above several quiet practical blocks','Green illustration on liner only','Dark core on white','Display serif weight plus one softer connector improves warmth and clarity','Do not fake bold or allow connector swashes to intrude into family lines.'],
['Smitten on Paper','Olive Branch','Portrait; ratio not measured','Moderate','Classical Roman full names','Upright details','Two balanced horizontal botanical accents around name area','Two small sprig-like marks; bigger liner branch','Dark text/green art','Small repeated marks can establish suite identity without a full frame','Not permission for an olive motif specifically; redraw original sparse plant geometry.'],
['Smitten on Paper','Traditional Elegance','Portrait; ratio not measured','Moderate','Expressive formal joined script','Quiet Roman facts','Centered invitation with disciplined role gaps','Art-free front','Dark names/body on ivory','Script display and Roman utility can coexist with restrained material richness','Avoid script programme headings becoming dense; long labels should use companion Roman face.'],
['Smitten on Paper','Simple Romance','Portrait; ratio not measured','Moderate','Strong spaced Roman names','Upright body with script ending','Clear blocks separated by very small botanical accents','Two short horizontal sprigs','Dark core, warm burgundy liner','Restrained original warm art can supply hospitality without overt symbols','Keep sprigs out of decorative-stock flourishes and avoid very pale accent text.'],
['Parekh Cards','Islamic Wedding Invitation | Vellum Romance - BI','Landscape multi-insert stock; ratio not measured','Moderate; separate Nikah and other cards visible','Smaller script names','Compact upright text below a clear event title','One dominant event label over centered short invitation blocks','Preprinted botanical stock','Warm dark green/brown detail on pale card','Give Nikah a clear information title while names retain their separate role','Do not borrow its spelling/sample names or infer religious text is approved; vellum/assembly is different.'],
['Parekh Cards','Vellum Roses','Landscape multi-insert stock; ratio not measured','Moderate; distinct ceremony and reception cards','Roman names with a script connector','Upright facts','Independent event headings and separated inserts','Existing floral corners/patterned sleeve','Dark body with restrained warm accents','Reception and marriage information may live on distinct surfaces','Same photographed design with a wax seal is one candidate; vendor dates and event order do not govern ours.'],
['Parekh Cards','Indigo Symphony','Landscape sleeve with separate pale inserts; ratio not measured','Moderate','Small classical/script identity','Compact detail','Existing cover ornament; calm insert text field','Dark blue patterned cover and gold motif','Blue/gold cover; darker text on pale insert','Let the already-rich cover carry decoration; readable inserts can be quiet','No copied emblem or change to our gold/ivory; pale decorative body can fail.'],
['Parekh Cards','Islamic Wedding Invitation | Golden Orchid - BI','Landscape predecorated ivory stock; ratio not measured','Moderate','Compact name role','Upright centered facts','Wide unfilled insert field','Factory-like golden opposing floral masses','Gold/light warm details on ivory','Reserve broad white/ivory fields amid existing decoration','Its gold-looking text is not a reliable dark-ink baseline; sample Arabic is not approved religious content.'],
['Parekh Cards','Muslim Wedding Card | Pastel Palettes - BI','Landscape predecorated ivory stock; ratio not measured','Moderate','Blue script names','Upright short details','Separate insert hierarchy over pale substrate','Gold patterned cover and small corner art','Blue detail with existing gold','Cool dark ink can sit well beside existing warm ornament','Do not copy calligraphy or infer every product photo accurately represents a faith-specific sample.'],
['Parekh Cards','Wedding Frame - NA','Landscape sleeve with framed centre; ratio not measured','Moderate, two adjacent insert text blocks visible','Separate name role and event title','Upright facts','Paired event columns divide content','Decorated frame/sleeve','Dark brown text on cream','Landscape supports independent ceremony/reception columns','Its centre is a name label, while ours is a real opening; printing text into our hole is invalid.'],
['Parekh Cards','Muslim Wedding Card | Burnished Gold - BI','Landscape ivory/gold multi-piece; ratio not measured','Moderate','Warm dark script name role','Dark upright body','Centered details within pale insert','Gold pattern concentrated on cover edge','Red/brown on ivory beside existing gold','A restrained warm dark ink is commercially plausible beside golden stock','No proof of adhesion or process for our actual card; avoid copied sacred mark.'],
['Parekh Cards','Banarasi Texture - NA','Landscape patterned sleeve and insert; ratio not measured','Moderate','Warm dark name role','Compact upright facts','Cover name line at base; insert distinct text area','Dense red cover pattern; spare insert margins','Red/brown and ivory/gold','Warm family palette need not be orange across every printed word','Do not add its full background or assume pattern is religious authority.'],
['Parekh Cards','Timeless Ivory - BI','Portrait-looking predecorated sleeve and insert; ratio not measured','Moderate','Warm coloured name role','Upright event programme facts visible on separate card','Separate invitation and programme headings','Ivory relief-like leaves; golden central mark','Warm red-brown additional text on ivory','Programme clarity can coexist with predecorated stock','No copying its emblem or claiming relief/foil method from a photo; enlarge details for real density.'],
['Parekh Cards','Muslim Wedding Card | Floral Brown - BI','Multi-insert set, mostly portrait visible; ratio not measured','Moderate','Small name role','Upright invitation body','Text stays high in clear insert centre','Rich floral cover; restrained inserts','Dark brown on pale inserts','A dark warm ink can serve the entire ordinary-print suite','Metallic-looking cover is existing stock; it is not evidence additional foil is feasible.'],
['Parekh Cards','Regal Curve - NA','Multi-insert predecorated stock; ratio not measured','Several event cards shown','Script/serif name roles','Upright event details','Each card receives an explicit event title','Curved sleeve flap; floral side detail','Warm gold-looking headings with darker body','Separate event headings improve instant finding across a suite','Vendor sample includes other-faith symbols; none of those facts/symbols or new curved construction transfer.'],
['Bella Figura','Copper botanical Samantha and Timothy custom suite','Multi-piece invitation and rehearsal detail; ratio not measured','Moderate with subordinate rehearsal-detail block','Copper expressive display names','Darker Marsala detail (named by source)','Centered main invitation; detail card has separate event hierarchy','Large botanical richness mainly liner and companion art','Copper accent plus darker wine body','Warm accent works best when essential details keep darker ink','Do not promise its foil process on bought stock; lighter small text and proprietary art are rejected.']
]

studies=[]
for n,row in enumerate(DATA,1):
    maker,name,fmt,density,names,body,grid,art,ink,principle,failure=row
    r=match(maker,name)
    r['deeply_analysed']=True
    r['shortlisted']=True
    r['notes']=principle+' | '+failure
    r['format']=fmt
    studies.append(dict(study_id=f'DS{n:02}',register_id=r['id'],maker=maker,title=name,url=r['url'],format_and_ratio=fmt,text_density=density,name_style_visual=names,body_style_visual=body,grid_and_hierarchy=grid,art_placement=art,ink_logic=ink,what_works=principle,what_fails_on_actual_stock=failure,transferable_principle=principle,source_font_identity='Unknown until source metadata explicitly names it; visual style is not font identification.',evidence_scope='This-run catalogue visual inspection plus individual design page/collection opening; editorial composition analysis at screen scale.'))

def open_source(r):
    try:
        resp=requests.get(r['url'],timeout=35)
        if resp.status_code!=200:return {'id':r['id'],'status':resp.status_code}
        soup=BeautifulSoup(resp.text,'html.parser')
        title=soup.title.get_text(' ',strip=True) if soup.title else ''
        specs=[]
        for e in soup.select('p,.design__description,.description'):
            t=e.get_text(' ',strip=True)
            if 'fonts:' in t.lower():
                f=re.search(r'fonts:\s*([^|]+)',t,re.I)
                if f:specs.append(f.group(1).strip())
        return {'id':r['id'],'status':200,'page_title':title,'identified_font_pairings':list(dict.fromkeys(specs)),'page_role':'individual design page' if r['maker']=='Bella Figura' else 'specific named suite collection' if r['maker']=='Smitten on Paper' else 'individual product page'}
    except Exception as e:return {'id':r['id'],'error':str(e)[:120]}
lookup={r['id']:r for r in records}
targets=[lookup[s['register_id']] for s in studies]
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:receipts=list(ex.map(open_source,targets))
for a in receipts:
    r=lookup[a['id']]
    if a.get('status')==200:
        r['source_opened']=True
        r['source_open_receipt']=a
        if a['identified_font_pairings']:r['typography_identification']={'basis':'explicit named metadata on primary product page','pairings':a['identified_font_pairings']}
    for study in studies:
        if study['register_id']==a['id']:
            study['source_opened_status']=a.get('status',a.get('error'))
            if a.get('identified_font_pairings'):study['source_font_identity']='Explicit source metadata: '+'; '.join(a['identified_font_pairings'])+'. Availability/licensing on this machine is not established by the reference.'

for r in records:
    r['candidate_kind']='cultural-art-reference' if any(t in r['maker'] for t in ['Metropolitan Museum','Victoria and Albert','Amir Mohtashemi']) else 'stationery-design-or-suite-reference'
doc['records']=records
doc['evidence_boundary']='Conservatively deduplicated named stationery/design and cultural references. This-run image inspections are catalogue-scale compositional screens, separate from inherited evidence; deep studies do not certify exact font sizes, physical ink or full print legibility. Colour/finish versions, same canonical product URLs, Parekh base-SKU variations and Vellum Roses wax-seal variants counted once.'
(OUT/'source-register.json').write_text(json.dumps(doc,ensure_ascii=False,indent=2),encoding='utf-8')
(OUT/'deep-studies.json').write_text(json.dumps(studies,ensure_ascii=False,indent=2),encoding='utf-8')
(OUT/'individual-source-open-receipts.json').write_text(json.dumps(receipts,ensure_ascii=False,indent=2),encoding='utf-8')
cols=['id','name','maker','url','image_url','origin','candidate_kind','collection_source','designer','lanes','discovered','source_opened','image_visually_inspected','deeply_analysed','shortlisted','inherited_evidence_level','format','inspection_scale','notes']
with (OUT/'source-register.csv').open('w',newline='',encoding='utf-8-sig') as f:
    w=csv.DictWriter(f,fieldnames=cols,extrasaction='ignore');w.writeheader();w.writerows(records)
counts={'raw_enumerated_records':719,'deduplicated_reference_candidates':len(records),'stationery_design_or_suite_candidates':sum(r['candidate_kind']=='stationery-design-or-suite-reference' for r in records),'cultural_art_references':sum(r['candidate_kind']=='cultural-art-reference' for r in records),'inherited_records':sum(r['origin']=='inherited' for r in records),'new_reference_candidates':sum(r['origin']=='new' for r in records),'refreshed_inherited_discovery':sum(bool(r.get('refreshed_discovery')) for r in records),'source_opened_individual_this_run':sum(bool(r['source_opened']) for r in records),'image_visually_inspected_this_run':sum(bool(r['image_visually_inspected']) for r in records),'deeply_analysed_this_run':len(studies),'compact_paired_layout_studies':24,'visual_screen_by_maker':{m:sum(r['image_visually_inspected'] and m in r['maker'] for r in records) for m in ['Bella Figura','Smitten on Paper','Parekh Cards']},'important_limit':'Catalogue images show composition and suite relationships; fine practical typography, real stock adhesion, metallic reflections and physical dimensions are not validated. No proprietary image archive redistributed.'}
(OUT/'counts.json').write_text(json.dumps(counts,indent=2),encoding='utf-8')
lines=['# 48 close-fit stationery studies','', 'These are genuine this-run screen-scale composition observations. Exact font identities appear only where the primary source explicitly lists them. Format is visually classified; aspect ratios/physical dimensions are unmeasured. The same design is counted once across views, colours and accessory variants. The source images remain with their makers; the pack stores links and original analysis only.','']
for s in studies:
    lines.extend([f"## {s['study_id']} · {s['title']} · {s['maker']}",'',f"[Primary source]({s['url']}) · register {s['register_id']}",'',f"**Format/density:** {s['format_and_ratio']}; {s['text_density']}.",'',f"**Type/grid:** {s['name_style_visual']}; {s['body_style_visual']}. {s['grid_and_hierarchy']}.",'',f"**Art/ink:** {s['art_placement']}; {s['ink_logic']}.",'',f"**Transfer:** {s['transferable_principle']}.",'',f"**Failure to avoid:** {s['what_fails_on_actual_stock']}",'',f"**Font evidence:** {s['source_font_identity']}",''])
(OUT/'48-close-fit-studies.md').write_text('\n'.join(lines),encoding='utf-8')
print(json.dumps(counts,indent=2))
