"""Receiver incidence control. Import is read-only; --execute requires reviewed pins."""
from pathlib import Path
from fractions import Fraction
from bisect import bisect_right
from collections import defaultdict, Counter
import argparse, hashlib, json, math, os, random, sys, time
import numpy as np
D=Path(__file__).resolve().parent; BASE=D.parent
R=BASE/'gap_boundary_controls/results'; P=R/'comma_unresolved__no_Pb'
CENSUS=BASE/'receiver_incidence_feasibility'; DESIGN=BASE/'receiver_incidence_design/DESIGN.md'
LOCI=Path('488070c49a3d86a096d958fa.jsonl')
UNIVERSES=('all_cross_folio','cross_section','same_section','unknown'); ELIG=('unrestricted','candidate')
SEEDS=tuple(range(51000,51200)); DIAGNOSTIC_SEEDS=(52001,52002,52003,52004)
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def save(p,x):
    p=Path(p); temp=p.with_name(p.name+'.tmp');temp.write_text(json.dumps(x,indent=2,allow_nan=False)+'\n');os.replace(temp,p)
def fraction_json(x):return None if x is None else {'numerator':str(x.numerator),'denominator':str(x.denominator)}
def read_fraction(x):return None if x is None else Fraction(int(x['numerator']),int(x['denominator']))
def known(x):return x is not None and x not in ('@','MISSING','') and not x.startswith('MIXED:')
def bits(words):return sum(1<<int(w) for w in words)
def bit_indices(x):
    while x:
        low=x&-x;yield low.bit_length()-1;x-=low

class Context:
    def __init__(self):
        self.index=json.loads((R/'INDEX.json').read_text()); ri=json.loads((P/'page_receiver_index.json').read_text())
        self.units=ri['units'];self.names=[u['folio'] for u in self.units];self.forms=self.index['forms']
        self.B=np.load(P/'page_receiver_form_index.npz')['presence'].astype(np.int8)
        assert self.B.shape==(627,204) and set(np.unique(self.B))<={0,1}
        self.N=204;self.F=627;self.E=int(self.B.sum());assert self.E==3559
        self.df=self.B.sum(axis=1);assert np.array_equal(self.df,ri['form_df'])
        self.factors=[int(x)+1 for x in self.df]; self.q=205
        self.groups=self.index['source_form_indices'];self.source_names=self.index['source_pages'];self.source_sections=self.index['source_sections']
        self.source_bits=[bits(g) for g in self.groups]; assert len(self.groups)==53
        self.original_bits=[bits(np.flatnonzero(self.B[:,j])) for j in range(self.N)]
        ledger={r['line_id']:r for r in map(json.loads,LOCI.read_text().splitlines())};self.metadata={}; strata=defaultdict(list)
        for j,u in enumerate(self.units):
            md={}
            for axis in ('L','H','I'):
                values=defaultdict(list)
                for locus in u['loci']:
                    row=ledger[locus];assert row['folio']==u['folio'];v=row['metadata'].get(axis,'MISSING')
                    if v in (None,'@'):v='MISSING'
                    values[v].append(locus)
                assert values
                key=next(iter(values)) if len(values)==1 else 'MIXED:'+'|'.join(sorted(values))
                md[axis]={'group':key,'values':sorted(values),'loci_by_value':dict(sorted(values.items()))}
            key=tuple(md[a]['group'] for a in ('L','H','I'));strata[key].append(j)
            self.metadata[u['folio']]={'page_index':j,'joint_stratum':list(key),'axes':md,'distinct_included_forms':int(self.B[:,j].sum())}
        assert self.metadata==json.loads((CENSUS/'PAGE_METADATA.json').read_text())
        self.keys=sorted(strata);self.strata=[strata[k] for k in self.keys];assert len(self.keys)==16
        self.edge_pools=[[(p,w) for p in pages for w in bit_indices(self.original_bits[p])] for pages in self.strata]
        self.weights=[len(e)*(len(e)-1)//2 for e in self.edge_pools];self.cumulative=[];total=0
        for w in self.weights:total+=w;self.cumulative.append(total)
        self.total_weight=total;assert total>0
        ss=self.source_sections; rs=[self.metadata[n]['axes']['I']['group'] for n in self.names]
        same=np.array([[s==n for n in self.names] for s in self.source_names],bool)
        isknown=np.array([[known(s) and known(r) for r in rs] for s in ss],bool)
        eq=np.array([[s==r for r in rs] for s in ss],bool)
        self.masks={'all_cross_folio':~same,'cross_section':~same&isknown&~eq,'same_section':~same&isknown&eq,'unknown':~same&~isknown}
        self.same=same
        self.selected=[(self.source_names.index(s),self.names.index(p)) for s,p in [('fRos','f105r'),('fRos','f76r'),('f82v','f43v')]]
        self.input_paths=[DESIGN,BASE/'receiver_incidence_design/REVIEW.json',R/'INDEX.json',P/'page_receiver_index.json',P/'page_receiver_form_index.npz',LOCI,CENSUS/'PAGE_METADATA.json',CENSUS/'WITNESSES.json',D/'runner.py',D/'preflight.py']
        self.pins={str(p):sha(p) for p in self.input_paths}
    def matrix(self,page_bits):
        B=np.zeros((self.F,self.N),np.int8)
        for j,b in enumerate(page_bits):
            for w in bit_indices(b):B[w,j]=1
        return B
    def validate(self,page_bits):
        B=self.matrix(page_bits)
        assert np.array_equal(B.sum(axis=0),self.B.sum(axis=0))
        for pp in self.strata:assert np.array_equal(B[:,pp].sum(axis=1),self.B[:,pp].sum(axis=1))
        assert np.array_equal(B.sum(axis=1),self.df)
        return B
    def score(self,page_bits):
        counts=np.zeros((53,204),np.int16);ratios=[];cache={0:Fraction(1)}
        for g,sb in enumerate(self.source_bits):
            row=[]
            for p,pb in enumerate(page_bits):
                overlap=sb&pb;k=overlap.bit_count();counts[g,p]=k
                if overlap not in cache:cache[overlap]=Fraction(self.q**k,math.prod(self.factors[w] for w in bit_indices(overlap)))
                row.append(cache[overlap])
            ratios.append(row)
        summary={}
        for u,mask in self.masks.items():
            for e in ELIG:
                active=mask if e=='unrestricted' else mask&(counts>=2)
                rows=[]
                for g in range(53):
                    jj=list(map(int,np.flatnonzero(active[g])))
                    cm=max((int(counts[g,j]) for j in jj),default=None);wm=max((ratios[g][j] for j in jj),default=None)
                    rows.append({'source':self.source_names[g],'eligible_cells':len(jj),'count_maximum':cm,'count_tied_receiver_indices':[j for j in jj if int(counts[g,j])==cm],'weight_maximum':fraction_json(wm),'weight_tied_receiver_indices':[j for j in jj if ratios[g][j]==wm]})
                nonempty=[g for g,row in enumerate(rows) if row['eligible_cells']]
                cm=max((rows[g]['count_maximum'] for g in nonempty),default=None)
                wm=max((read_fraction(rows[g]['weight_maximum']) for g in nonempty),default=None)
                summary[u+'__'+e]={'universe_cells':int(mask.sum()),'eligible_cells':int(active.sum()),'empty':not nonempty,'count_maximum':cm,'weight_maximum':fraction_json(wm),'count_tied_pairs':[[g,j] for g in nonempty if rows[g]['count_maximum']==cm for j in rows[g]['count_tied_receiver_indices']],'weight_tied_pairs':[[g,j] for g in nonempty if read_fraction(rows[g]['weight_maximum'])==wm for j in rows[g]['weight_tied_receiver_indices']],'source_rows':rows}
        selected=[{'source':self.source_names[g],'receiver':self.names[p],'unit':'page','count':int(counts[g,p]),'weight':fraction_json(ratios[g][p])} for g,p in self.selected]
        return counts,ratios,summary,selected

class Chain:
    def __init__(self,ctx,seed):
        self.ctx=ctx;self.rng=random.Random(seed);self.page_bits=ctx.original_bits.copy()
        self.pools=[list(pool) for pool in ctx.edge_pools];self.attempted=[0]*len(self.pools);self.accepted=[0]*len(self.pools);self.outcomes=[Counter() for _ in self.pools]
    def attempt(self):
        c=self.ctx;s=bisect_right(c.cumulative,self.rng.randrange(c.total_weight));pool=self.pools[s];n=len(pool)
        i=self.rng.randrange(n);j=self.rng.randrange(n-1);j+=j>=i
        self.attempted[s]+=1;p,a=pool[i];q,b=pool[j]
        if p==q:reason='same_page'
        elif a==b:reason='same_form'
        elif (self.page_bits[p]>>b)&1 or (self.page_bits[q]>>a)&1:reason='crossed_cell_present'
        else:
            change=(1<<a)|(1<<b);self.page_bits[p]^=change;self.page_bits[q]^=change
            pool[i]=(p,b);pool[j]=(q,a);self.accepted[s]+=1;reason='accepted'
        self.outcomes[s][reason]+=1
    def advance(self,n):
        for _ in range(n):self.attempt()
    def diagnostic(self):
        per=[]
        for s,pp in enumerate(self.ctx.strata):
            ee=len(self.pools[s]);overlap=sum((self.page_bits[p]&self.ctx.original_bits[p]).bit_count() for p in pp)
            per.append({'stratum':list(self.ctx.keys[s]),'pages':[self.ctx.names[p] for p in pp],'edges':ee,'proposal_weight':self.ctx.weights[s],'attempted':self.attempted[s],'accepted':self.accepted[s],'rejected':self.attempted[s]-self.accepted[s],'acceptance_ratio':self.accepted[s]/self.attempted[s] if self.attempted[s] else None,'edge_overlap_to_start':overlap,'edge_turnover':ee-overlap,'outcomes':dict(self.outcomes[s])})
        a=sum(self.attempted);ok=sum(self.accepted);overlap=sum(x['edge_overlap_to_start'] for x in per)
        return {'attempted':a,'accepted':ok,'rejected':a-ok,'acceptance_ratio':ok/a if a else None,'edge_overlap_to_start':overlap,'edge_turnover':self.ctx.E-overlap,'strata':per}
    def validate(self):
        B=self.ctx.validate(self.page_bits)
        for s,pool in enumerate(self.pools):
            assert len(pool)==len(set(pool))==len(self.ctx.edge_pools[s])
            assert set(pool)=={(p,w) for p in self.ctx.strata[s] for w in bit_indices(self.page_bits[p])}
        return B

def retain(ctx,chain,out,kind,seed,checkpoint):
    B=chain.validate();packed=np.packbits(B,axis=0,bitorder='little');stem=f'{kind}_{seed}_{checkpoint:04d}E'
    np.savez_compressed(out/(stem+'.npz'),packed=packed,shape=np.array(B.shape),seed=np.array(seed),checkpoint_E=np.array(checkpoint))
    # Explicit round trip; array hash is independent of ZIP-container metadata.
    assert np.array_equal(np.unpackbits(packed,axis=0,count=ctx.F,bitorder='little'),B)
    counts,_,summary,selected=ctx.score(chain.page_bits)
    entry={'kind':kind,'seed':seed,'checkpoint_E':checkpoint,'graph':stem+'.npz','graph_sha256':sha(out/(stem+'.npz')),'graph_array_sha256':hashlib.sha256(B.tobytes()).hexdigest(),'diagnostics':chain.diagnostic(),'selected':selected,'summaries':summary}
    save(out/(stem+'.json'),entry)
    return {'kind':kind,'seed':seed,'checkpoint_E':checkpoint,'record':stem+'.json','record_sha256':sha(out/(stem+'.json')),'graph':entry['graph'],'graph_sha256':entry['graph_sha256'],'graph_array_sha256':entry['graph_array_sha256']}

def aggregate(ctx,out,records,observed):
    entries=[json.loads((out/r['record']).read_text()) for r in records if r['kind']=='reference'];assert len(entries)==200
    result={'draws':200,'descriptive_not_calibrated_p':True,'observed_start_bias_and_unproved_mixing':True,'unique_reference_graphs':len({x['graph_array_sha256'] for x in entries}),'duplicate_reference_graphs':200-len({x['graph_array_sha256'] for x in entries}),'universes':{}}
    for key,obs in observed.items():
        z={'eligible_cells':[e['summaries'][key]['eligible_cells'] for e in entries],'count':{},'weighted':{},'source_rows':{}}
        for metric,field in [('count','count_maximum'),('weighted','weight_maximum')]:
            cast=(lambda x:x) if metric=='count' else read_fraction
            val=cast(obs[field]);values=[cast(e['summaries'][key][field]) for e in entries];available=[v for v in values if v is not None]
            encode=(lambda x:x) if metric=='count' else fraction_json
            z[metric]={'observed':encode(val),'saved_draw_values':[encode(x) for x in values],'available_draws':len(available),'empty_draws':200-len(available),'meeting_or_exceeding_observed':sum(x>=val for x in available) if val is not None else None,'denominator':200,'minimum':encode(min(available)) if available else None,'maximum':encode(max(available)) if available else None}
        for g,name in enumerate(ctx.source_names):
            row={}
            for metric,field in [('count','count_maximum'),('weighted','weight_maximum')]:
                cast=(lambda x:x) if metric=='count' else read_fraction;encode=(lambda x:x) if metric=='count' else fraction_json
                val=cast(obs['source_rows'][g][field]);values=[cast(e['summaries'][key]['source_rows'][g][field]) for e in entries];avail=[v for v in values if v is not None]
                row[metric]={'observed':encode(val),'saved_draw_values':[encode(x) for x in values],'available_draws':len(avail),'empty_draws':200-len(avail),'meeting_or_exceeding_observed':sum(x>=val for x in avail) if val is not None else None,'denominator':200}
            z['source_rows'][name]=row
        result['universes'][key]=z
    save(out/'AGGREGATE.json',result)
    return result

def execute(review_path):
    ctx=Context();pre=json.loads((D/'PREFLIGHT.json').read_text());assert pre['VERDICT']=='PASS'
    review=json.loads(Path(review_path).read_text());assert review.get('VERDICT') in ('PASS','PASS_WITH_QUALIFICATIONS')
    assert review['runner_sha256']==sha(D/'runner.py') and review['preflight_sha256']==sha(D/'preflight.py')
    assert review['design_sha256']==sha(DESIGN)
    assert pre['input_pins']==ctx.pins,'Preflight inputs changed'
    design_review=json.loads((BASE/'receiver_incidence_design/REVIEW.json').read_text());assert design_review['design_sha256']==sha(DESIGN) and design_review['VERDICT']=='PASS_WITH_QUALIFICATIONS'
    receipt=D/'RUN_RECEIPT.json';state={'status':'RUNNING','pid':os.getpid(),'started_unix':time.time(),'input_pins':ctx.pins,'independent_review':{'path':str(Path(review_path).resolve()),'sha256':sha(review_path)},'seeds':list(SEEDS),'diagnostic_seeds':list(DIAGNOSTIC_SEEDS),'E':ctx.E,'reference_attempts':100*ctx.E,'diagnostic_attempts':1000*ctx.E,'progress':{},'python':sys.version,'numpy':np.__version__}
    with receipt.open('x') as f:json.dump(state,f,indent=2);f.write('\n')
    out=D/'results';records=[]
    try:
        out.mkdir(exist_ok=False)
        _,_,observed,selected=ctx.score(ctx.original_bits);save(out/'OBSERVED.json',{'summaries':observed,'selected':selected});save(out/'INPUT_PINS.json',ctx.pins)
        save(out/'INDEX.json',{'forms':ctx.forms,'source_names':ctx.source_names,'source_form_indices':ctx.groups,'receiver_names':ctx.names,'metadata':ctx.metadata,'strata':[{'key':list(k),'pages':pp,'edges':len(ctx.edge_pools[s]),'weight':ctx.weights[s]} for s,(k,pp) in enumerate(zip(ctx.keys,ctx.strata))]})
        for seed in SEEDS:
            chain=Chain(ctx,seed);chain.advance(100*ctx.E);records.append(retain(ctx,chain,out,'reference',seed,100))
            state['progress']={'phase':'reference','completed':len(records),'last_seed':seed};save(receipt,state);save(out/'SAVED_STATES.json',records)
            print(json.dumps(state['progress']),flush=True)
        for seed in DIAGNOSTIC_SEEDS:
            chain=Chain(ctx,seed)
            for checkpoint in range(100,1001,100):
                chain.advance(100*ctx.E);records.append(retain(ctx,chain,out,'diagnostic',seed,checkpoint));save(out/'SAVED_STATES.json',records)
                state['progress']={'phase':'diagnostic','seed':seed,'checkpoint_E':checkpoint};save(receipt,state);print(json.dumps(state['progress']),flush=True)
        aggregate(ctx,out,records,observed)
        assert all(sha(p)==h for p,h in ctx.pins.items())
        state.update(status='COMPLETED',finished_unix=time.time(),saved_states=len(records),unique_all_saved_graphs=len({r['graph_array_sha256'] for r in records}),duplicate_all_saved_graphs=len(records)-len({r['graph_array_sha256'] for r in records}),elapsed_seconds=time.time()-state['started_unix']);save(receipt,state)
        save(out/'FINAL_HASHES.json',{str(p.relative_to(out)):sha(p) for p in sorted(out.iterdir()) if p.is_file() and p.name!='FINAL_HASHES.json'})
    except BaseException as e:
        state.update(status='FAILED_PRESERVE_DO_NOT_REPLAY',error=repr(e),stopped_unix=time.time(),retained_states=len(records));save(receipt,state);raise

if __name__=='__main__':
    ap=argparse.ArgumentParser();ap.add_argument('--execute',action='store_true');ap.add_argument('--preflight-review');a=ap.parse_args()
    if not a.execute:ap.error('No operation selected. Run preflight.py first; execution is coordinator-only after independent review.')
    if not a.preflight_review:ap.error('--preflight-review is required')
    execute(a.preflight_review)
