"""Unpooled matched denominators; preserve the preregistration's original audit."""
import collections,hashlib,json
from pathlib import Path
P=Path(__file__).resolve().parent;B=P.parent/'full-corpus';S=B/'span-resolved-v1'
def jl(p):return [json.loads(l) for l in p.open()]
def dump(p,x):p.write_text(json.dumps(x,indent=2,sort_keys=True)+'\n')
meta={r['row_id']:r for r in jl(B/'inputs/rows.jsonl')}
eligible={k:r for k,r in meta.items() if r['accepted_gold'] and r['record_kind']=='function' and r['id']!='CF-C02'}
allrows=jl(S/'paired-rows.jsonl');rows=[r for r in allrows if r['row_id'] in eligible]
lookup={(r['row_id'],r['cohort_id'],r['profile'],r['arm']):r for r in rows}
def identity(a):return dict(lineage_records=len({r['row_id'] for r in a}),canonical_pairs=len({r['pair_id'] for r in a}),families=len({r['family_id'] for r in a}),row_background_units=None)
def funded(r):
 if not r['supported'] or not r['evaluated']:return None
 if r['retrieved'] is False:return False
 return r['funded']
def counts(a):return dict(scope_units=len(a),canonical_pairs=len({r['pair_id'] for r in a}),families=len({r['family_id'] for r in a}),lineage_records=len({r['row_id'] for r in a}))
records=[];cases=[]
arms=['baseline','half-name-only','csls-only','blocks-only','rrf60','protected-ensemble2','rrf60-half-csls','protected-half-csls2']
for panel in ['all','research-wave1-unpublished']:
 for profile in ['default','balanced']:
  for arm in arms:
   for label in ['positive','negative']:
    rr=[r for r in rows if r['profile']==profile and r['arm']==arm and (r['label'] in ['duplicate','drifted'])==(label=='positive') and (panel=='all' or r['dataset']==panel)]
    match=[]
    for r in rr:
     b=lookup[r['row_id'],r['cohort_id'],profile,'baseline']
     if funded(r) is not None and funded(b) is not None:match.append((r,b))
    win=[r for r,b in match if funded(r) and not funded(b)];loss=[r for r,b in match if funded(b) and not funded(r)]
    unique=[r for r,b in match if funded(r) and all(funded(lookup[r['row_id'],r['cohort_id'],profile,a]) is False for a in ['baseline','half-name-only','csls-only','blocks-only'] if a!=arm)]
    rec=dict(panel=panel,profile=profile,arm=arm,label=label,available=counts(rr),matched_funding=counts([r for r,b in match]),baseline_funded=counts([b for r,b in match if funded(b)]),arm_funded=counts([r for r,b in match if funded(r)]),wins=counts(win),losses=counts(loss),unique_funded_vs_individuals=counts(unique),unknown_or_unsupported_scope_units=len(rr)-len(match))
    records.append(rec)
    for change,rs in [('win',win),('loss',loss),('unique',unique)]:
     for r in rs:
      b=lookup[r['row_id'],r['cohort_id'],profile,'baseline'];cases.append({k:r[k] for k in ['row_id','id','pair_id','family_id','cohort_id','repository','revision','scope','profile','arm','label']}|dict(panel=panel,change=change,baseline_first_loss=b['first_loss'],arm_first_loss=r['first_loss'],estimated_pair_usd=r['estimated_pair_usd']))
inventory={}
for label in ['all','positive','negative']:
 a=[r for r in eligible.values() if label=='all' or (r['label'] in ['duplicate','drifted'])==(label=='positive')];inventory[label]=identity(a)
receipt=dict(schema=1,status='fixed comparisons complete 79/79; denominator clarification, no retuning',inventory=inventory,definitions=dict(canonical_pair='shared pair_id; repeated labels/backgrounds are not new independent pairs',family='shared family_id, overlapping endpoints retained; positive and negative family totals can overlap',scope_unit='one lineage record in one exact background/pin/scope, per profile; never pooled as independent positives',matched='both arms have known funding on the identical scope unit; unsupported and source-incomplete selected campaigns unknown; known non-retrieval implies unfunded without a prompt',aggregation='No any-background union success rate. Tables retain profile and exact scope; canonical pair/family counts are coverage counts only, not independent trials.'),original_complementarity_sha256=hashlib.sha256((P/'COMPLEMENTARITY.json').read_bytes()).hexdigest(),records=records,interpretation='249 positive row/background units in original audit are not249 independent pairs. Shared accepted function positive inventory has200 lineage records representing185 canonical pair IDs and103 family IDs. No new reportable family confirmed by these funding diagnostics.')
dump(P/'COMPLEMENTARITY-RECEIPT.json',receipt);(P/'complementarity-cases.jsonl').write_text(''.join(json.dumps(r,sort_keys=True)+'\n' for r in cases))
for r in records:
 if r['panel']=='all' and r['label']=='positive':print(json.dumps({k:r[k] for k in ['profile','arm','matched_funding','baseline_funded','arm_funded','wins','losses']}))
