"""Strict frozen source adapters; no acquisition or XLSX/XML parsing."""
import hashlib,json
from pathlib import Path
from common import ROOT,PREP,checked,module,rows,read,need,encoded
import gnd_adapter as G
from catalog_authority import merge_authority_row,next_source_rank
SCB_ID='se-scb-registered-names-2022'
def closed_sources(cfg,gate):
 g=cfg['gnd'];need(g['source']=='bibliographic:gnd2026-retained03' and g['scope']==G.SCOPE,'GND03 cutoff differs')
 frozen=read(PREP/'INPUT_MANIFEST.json')
 need({(p['path'],p['sha256']) for p in g['proofs']}=={(p['path'],p['sha256']) for p in frozen['source_pins']+frozen['packet_pins']},'Required GND full closure/privacy/terminal/notice chain differs')
 for p in g['proofs']:checked(p,gate)
 packet=checked(g['names'],gate);need(g['names']['sha256']=='6e0905a838431e8e61c473f4c021905c3313151d8226a98bfc568b0d948172ca','Different GND packet')
 result={'gnd':packet}
 if cfg.get('scb') is not None:
  scb=cfg['scb'];path=checked(scb['contract'],gate);contract=module(path,'v7_closed_scb_contract')
  closure=contract.closed_source(scb['closed_config']);packet=checked(scb['names'],gate)
  need(packet.resolve()==(Path(scb['closed_config']['source']['packet_root'])/'NAMES.jsonl.gz').resolve() and scb['receipt_sha256']==scb['closed_config']['source']['receipt']['sha256'],'SCB admitted packet/receipt differs from full CLOSED contract')
  result.update(scb=packet,scb_contract=contract,scb_closure=closure)
 return result
def scb_events(row,contract,closure,receipt_sha,policy):
 contract.validate_row(row,policy,closure['members'])
 digest=hashlib.sha256(encoded(row)).hexdigest();indices={v:n for n,v in enumerate(row['forms'])}
 for ordinal,obs in enumerate(row['attestations']):
  yield {'source_id':SCB_ID,'source_group':'scb','tier':'official','evidence_kind':'official_scb_registered_name_field',
   'role':row['role'],'form':obs['form'],'language':None,'cohort':'se-scb-registered-names-20221231',
   'packet_receipt_sha256':receipt_sha,'source_row_sha256':digest,'representative_form':row['form'],
   'source_form_ordinal':indices[obs['form']],'source_forms_count':len(row['forms']),
   'source_categories':row['source_categories'],'publisher_category_counts_are_overlapping_not_summed':True,
   'source_attestation_ordinal':ordinal,'source_attestations_count':len(row['attestations']),
   'reference_date':'2022-12-31','workbook_updated':'2024-11-21','license':'CC-BY-4.0','scb_observation':obs}
def add_sources(c,cfg,closed,policy,gate):
 rank=next_source_rank(c.db);counts={'gnd_rows':0,'gnd_events':0,'scb_rows':0,'scb_events':0}
 c.db.execute('CREATE TABLE v7_source_rows(source TEXT,role TEXT,key TEXT,digest TEXT,PRIMARY KEY(source,role,key)) WITHOUT ROWID')
 for source,path in [('gnd',closed['gnd'])]+([('scb',closed['scb'])] if 'scb' in closed else []):
  for row in rows(path):
   gate();need(c.db.execute('SELECT 1 FROM v7_source_rows WHERE source=? AND role=? AND key=?',(source,row['role'],row['key'])).fetchone() is None,'Duplicate source role/key')
   if source=='gnd':events=list(G.project(row,policy));merge_authority_row(c,row,policy,rank)
   else:
    events=list(scb_events(row,closed['scb_contract'],closed['scb_closure'],cfg['scb']['receipt_sha256'],policy))
    for e in events:c.event(row['key'],row['form'],e,rank+1)
    for literal in row['forms']:c.db.execute('INSERT OR IGNORE INTO forms VALUES(?,?)',(row['key'],literal))
   counts[source+'_rows']+=1;counts[source+'_events']+=len(events)
   c.db.execute('INSERT INTO v7_source_rows VALUES(?,?,?,?)',(source,row['role'],row['key'],hashlib.sha256(encoded(row)).hexdigest()))
   if counts[source+'_rows']%2000==0:c.db.commit()
 c.db.commit();need(counts['gnd_rows']==449019,'GND role-row closure differs')
 if 'scb' in closed:need(counts['scb_rows']==closed['scb_closure']['counts']['distinct_qualified_role_keys'],'SCB source-role closure differs')
 return counts
