"""Reproducible public catalogue discovery; no private wedding data sent.
Stores links and short factual catalogue records only, not third-party art archives.
"""
from pathlib import Path
import requests, re, json, csv, concurrent.futures, datetime
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlsplit, urlunsplit

OUT=Path(__file__).parent
BRIEF=OUT.parents[2]/'English-Invitation-Ultra-Design-Brief-2026-10-07'
S=requests.Session()
LOG=[]
def fetch(u):
    try:
        r=S.get(u,timeout=35)
        LOG.append({'url':u,'status':r.status_code,'bytes':len(r.content),'access':'public read only'})
        r.raise_for_status()
        return r
    except Exception as e:
        LOG.append({'url':u,'error':str(e)[:150]})
        return None
def absurl(u):return 'https:'+u if u.startswith('//') else u
def family_name(name):
    name=re.sub(r'\s+Wedding Invitation Design$','',name,flags=re.I)
    name=re.sub(r'\s+V[\.]?\s*[0-9]+$','',name,flags=re.I)
    name=re.sub(r'\s*\([^)]*\)\s*$','',name)
    name=re.sub(r'^(Muslim Wedding Card\s*\|\s*)','',name,flags=re.I)
    return re.sub(r'[^a-z0-9]+',' ',name.lower()).strip()
records=[]
def add(name,maker,url,image=None,origin='new',source=None,designer=None,lanes=None,evidence=None):
    records.append(dict(name=name,maker=maker,url=absurl(url),image_url=absurl(image) if image else None,
      designer=designer,origin=origin,collection_source=source,lanes=lanes or [],discovered=True,
      source_opened=False,image_visually_inspected=False,deeply_analysed=False,shortlisted=False,
      inherited_evidence_level=evidence,discovery_method='public named catalogue item',
      name_basis='catalogue title',format='not yet visually inspected',typography_identification='unknown',notes=''))

# Inherited inventory is explicitly distinct from current visual evidence.
prior=json.loads((BRIEF/'research/starting-reference-library.json').read_text(encoding='utf-8-sig'))
for v in prior['records']:
    add(v['title'],v['source'],v['url'],origin='inherited',source=v.get('source_page'),evidence=v.get('inherited_evidence_level'))
    records[-1].update(inherited_id=v['id'],discovery_method='supplied inherited inventory',notes='Inherited note, not a new inspection: '+v.get('our_transfer_note',''))

for gallery in ['wedding-invitation-etiquette','retired-designs']:
    url='https://www.bellafigura.com/rest/variations?gallery='+gallery
    response=fetch(url)
    if response is None:continue
    data=response.json()['data']
    for v in data:
        if not v.get('weddingGallery') or re.search(r'save.the.date|holiday|mitzvah|thank.you|birth|baby',v['name'],re.I):continue
        if v['name'].lower()=='custom design':continue
        add(v['name'],'Bella Figura',v['designUrl'],v.get('thumbnailUrl2x') or v.get('thumbnailUrl'),source=url,designer=v.get('designerName'),lanes=[1,5])
        records[-1]['availability']='current gallery' if gallery!='retired-designs' else 'retired reference; not an availability claim'
        records[-1]['catalogue_id']=v['id']

url='https://smittenonpaper.com/pages/signature-wedding'
r=fetch(url)
if r is not None:
    soup=BeautifulSoup(r.text,'html.parser')
    for a in soup.select('.products a[href]'):
        i=a.find('img')
        if i and i.get('alt'):
            add(i['alt'],'Smitten on Paper',urljoin(url,a['href']),i.get('src'),source=url,lanes=[1,2,5])

# Each product is actually enumerated by name, not inferred from the 114-item label.
base='https://www.parekhcards.com/Muslim-Wedding-Cards.asp'
pages=[base]+[base+'?p='+str(p) for p in range(2,14)]
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:
    results=list(ex.map(fetch,pages))
for u,r in zip(pages,results):
    if r is None:continue
    soup=BeautifulSoup(r.text,'html.parser')
    for a in soup.select('a.product-item-link'):
        card=a.find_parent(class_='product-item')
        i=card.find('img',class_='product-image-photo') if card else None
        add(a.get_text(' ',strip=True),'Parekh Cards',a['href'],i.get('src') if i else None,source=u,lanes=[2,3,7])

# Conservative family-level dedup: version, colour and suite-piece aliases do not inflate candidates.
dedup={}
seen_urls={}
for r in records:
    maker=r['maker'].lower().strip()
    if 'bella figura' in maker:maker='bella figura'
    if 'smitten' in maker:maker='smitten on paper'
    if 'parekh' in maker:maker='parekh cards'
    key=maker+'|'+family_name(r['name'])
    if maker=='parekh cards':
        code=re.search(r'/(?:is|mf)(\d+)(?:[a-z])?(?:-bi|-na)?\.asp',r['url'],re.I)
        if code:key=maker+'|sku-family-'+re.search(r'/(is|mf)',r['url'],re.I).group(1).lower()+code.group(1)
    parts=urlsplit(r['url'])
    canonical=urlunsplit(('https',parts.netloc.lower().removeprefix('www.'),parts.path.rstrip('/'),'', ''))
    if canonical in seen_urls:key=seen_urls[canonical]
    if key in dedup:
        old=dedup[key]
        old.setdefault('aliases',[]).append({'name':r['name'],'url':r['url'],'origin':r['origin'],'collection_source':r['collection_source']})
        if old.get('origin')=='inherited' and r['origin']=='new':old['refreshed_discovery']=True
        if not old.get('image_url') and r.get('image_url'):old['image_url']=r['image_url']
        old['lanes']=sorted(set(old['lanes']+r['lanes']))
    else:dedup[key]=r
    seen_urls[canonical]=key
final=list(dedup.values())
for n,r in enumerate(final,1):r['id']='ST'+str(n).zfill(4)
OUT.mkdir(parents=True,exist_ok=True)
(OUT/'source-register.json').write_text(json.dumps({'evidence_boundary':'Named candidates from public individual catalogue records and inherited inventory; discovery is not image inspection; versions and colour variants merged conservatively by maker and base name.','date':'2026-10-07','records':final},ensure_ascii=False,indent=2),encoding='utf-8')
cols=['id','name','maker','url','image_url','origin','collection_source','designer','lanes','discovered','source_opened','image_visually_inspected','deeply_analysed','shortlisted','inherited_evidence_level','availability','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(final)
counts={'raw_enumerated_records':len(records),'unique_design_families':len(final),'inherited_records':sum(r['origin']=='inherited' for r in final),'new_records':sum(r['origin']=='new' for r in final),'refreshed_inherited_discovery':sum(bool(r.get('refreshed_discovery')) for r in final),'by_maker':{},'image_visually_inspected_this_run':0,'source_opened_individual_this_run':0,'deeply_analysed_this_run':0,'caution':'No image inspection claimed from catalogue download or inherited evidence. Retired Bella Figura designs remain historical references.'}
for r in final:counts['by_maker'][r['maker']]=counts['by_maker'].get(r['maker'],0)+1
(OUT/'counts.json').write_text(json.dumps(counts,indent=2),encoding='utf-8')
(OUT/'fetch-log.json').write_text(json.dumps(LOG,indent=2),encoding='utf-8')
print(json.dumps(counts,indent=2))
