"""Exact deterministic derivatives of saved results. No RNG imports or draws."""
from pathlib import Path
from fractions import Fraction
from collections import Counter,defaultdict
import hashlib,json,math,os,sys,time
import numpy as np
D=Path(__file__).resolve().parent;ROOT=D.parent;R=ROOT/'results'
POLICIES=('comma_boundary__all_P','comma_boundary__no_Pb','comma_unresolved__all_P','comma_unresolved__no_Pb')
UNIVERSES=('all_cross_folio','cross_section','same_section','unknown');ELIG=('unrestricted','candidate')
PRIMARY='comma_unresolved__no_Pb'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def save(p,x):p.write_text(json.dumps(x,indent=2,allow_nan=False)+'\n')
def arrhash(a):return hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()
def ratio(q,denominators):return Fraction(q**len(denominators),math.prod(denominators))

class ExactContext:
    def __init__(self,B,df):
        self.B=B;self.N=B.shape[1];self.q=self.N+1;self.factors=[int(x)+1 for x in df]
        self.receiver_bits=[sum(1<<int(w) for w in np.flatnonzero(B[:,j])) for j in range(self.N)]
        self.ratios=[Fraction(1)];self.ids={Fraction(1):0};self.cache={0:0};self.maxcache={}
        self.BW=B*np.log((self.N+1)/(np.array(df)+1))[:,None]
    def sid(self,wordmask):
        old=self.cache.get(wordmask)
        if old is not None:return old
        left=wordmask;den=[]
        while left:
            lowest=left&-left;den.append(self.factors[lowest.bit_length()-1]);left-=lowest
        value=ratio(self.q,den);i=self.ids.get(value)
        if i is None:i=len(self.ratios);self.ratios.append(value);self.ids[value]=i
        self.cache[wordmask]=i;return i
    def matrices(self,groups):
        C=np.zeros((len(groups),self.N),np.int16);S=np.zeros(C.shape,np.int32);W=np.zeros(C.shape,float)
        for g,words in enumerate(groups):
            bitset=sum(1<<int(w) for w in words)
            for j,rb in enumerate(self.receiver_bits):
                intersection=bitset&rb;C[g,j]=intersection.bit_count();S[g,j]=self.sid(intersection)
            if words:W[g]=self.BW[sorted(words)].sum(axis=0)
        return C,S,W
    def maximum(self,values):
        key=tuple(np.unique(values).tolist())
        if not key:return -1
        if key not in self.maxcache:self.maxcache[key]=max(key,key=self.ratios.__getitem__)
        return self.maxcache[key]
    def export(self,path):
        save(path,{'N':self.N,'q':self.q,'score_definition':'R=q^k/product(df+1), canonical exact Fraction; ordering is log-monotone','zero_score_id':0,'scores':[{'id':i,'numerator':str(f.numerator),'denominator':str(f.denominator),'approximate_log':math.log(f.numerator)-math.log(f.denominator)} for i,f in enumerate(self.ratios)],'shared_form_masks_cached':len(self.cache),'unique_scores':len(self.ratios)})

def summarize(ctx,C,S,W,masks,ranks=False):
    arrays={};details={}
    for u,umask in masks.items():
        for e in ELIG:
            key=u+'__'+e;m=umask if e=='unrestricted' else umask&(C>=2)
            rowids=np.full(len(C),-1,np.int32);ties=np.zeros(C.shape,bool);rowfloat=np.full(len(C),np.nan);row_tiediff=0;row_wrong=0
            for g in range(len(C)):
                if not m[g].any():continue
                sid=ctx.maximum(S[g,m[g]]);rowids[g]=sid;ties[g]=m[g]&(S[g]==sid)
                rowfloat[g]=W[g,m[g]].max();oldties=m[g]&(W[g]==rowfloat[g])
                row_tiediff+=int(not np.array_equal(ties[g],oldties));row_wrong+=int(any(S[g,oldties]!=sid))
            available=rowids[rowids>=0];globalid=ctx.maximum(available) if len(available) else -1
            globalties=ties&(rowids[:,None]==globalid) if globalid>=0 else np.zeros_like(ties)
            floatmax=float(W[m].max()) if m.any() else None;oldglobal=(m&(W==floatmax)) if m.any() else np.zeros_like(m)
            arrays[key+'__global_max_id']=np.int32(globalid);arrays[key+'__source_max_ids']=rowids
            arrays[key+'__source_tie_bits']=np.packbits(ties,axis=1);arrays[key+'__source_tie_counts']=ties.sum(axis=1).astype(np.int32)
            arrays[key+'__global_tie_count']=np.int32(globalties.sum());arrays[key+'__eligible_cells']=np.int32(m.sum())
            arrays[key+'__source_eligible_cells']=m.sum(axis=1).astype(np.int32)
            arrays[key+'__global_max_sources']=(rowids==globalid)&(rowids>=0)
            details[key]={'universe_cells':int(umask.sum()),'eligible_cells':int(m.sum()),'empty_candidate':e=='candidate' and not m.any(),'available':bool(m.any()),'global_max_id':globalid,'global_tie_count':int(globalties.sum()),'source_tie_rows_changed':row_tiediff,'source_float_maximizer_not_exact_maximum':row_wrong,'global_float_tie_set_changed':not np.array_equal(globalties,oldglobal),'global_float_maximizer_not_exact_maximum':bool(any(S[oldglobal]!=globalid)) if oldglobal.any() else False,'original_approximate_maximum':floatmax}
            if ranks:
                first=np.full(C.shape,-1,np.int32);last=first.copy()
                if m.any():
                    ids,counts=np.unique(S[m],return_counts=True);countmap=dict(zip(ids.tolist(),counts.tolist()));bound={};above=0
                    for sid in sorted(countmap,key=ctx.ratios.__getitem__,reverse=True):bound[sid]=(above+1,above+countmap[sid]);above+=countmap[sid]
                    first[m]=[bound[int(i)][0] for i in S[m]];last[m]=[bound[int(i)][1] for i in S[m]]
                arrays[key+'__weighted__first']=first;arrays[key+'__weighted__last']=last
    return arrays,details

def validate_original_summary(C,W,masks,stored,index):
    for u,mask in masks.items():
        for e in ELIG:
            pre=u+'__'+e;m=mask if e=='unrestricted' else mask&(C>=2)
            assert int(stored[pre+'__cells'][index])==int(m.sum())
            for metric,A in [('count',C),('weighted',W)]:
                maximum=float(A[m].max()) if m.any() else np.nan;expected=stored[pre+'__'+metric+'__maximum'][index]
                assert (math.isnan(maximum) and np.isnan(expected)) or maximum==expected,(pre,metric,index,maximum,expected)
                row=np.array([float(A[g,m[g]].max()) if m[g].any() else np.nan for g in range(len(C))])
                assert np.array_equal(row,stored[pre+'__'+metric+'__row_maxima'][index],equal_nan=True)

def tests():
    assert ratio(12,[6,2])==ratio(12,[4,3])==Fraction(12)
    assert ratio(12,[1])==ratio(12,[6,2])
    assert ratio(12,[])==ratio(12,[12,12])==1
    ctx=ExactContext(np.zeros((1,3),np.int16),[0]);ctx.ratios=[Fraction(1),Fraction(12),Fraction(3)];ctx.ids={f:i for i,f in enumerate(ctx.ratios)}
    C=np.array([[1,2,2]],np.int16);S=np.array([[1,2,0]],np.int32);W=np.array([[math.log(12),math.log(3),0.]])
    mask={'cross_section':np.ones_like(C,bool)};a,d=summarize(ctx,C,S,W,mask,True)
    assert a['cross_section__unrestricted__global_max_id']==1 and a['cross_section__candidate__global_max_id']==2
    C2=np.array([[2,1,2]],np.int16);a,_=summarize(ctx,C2,S,W,mask);assert a['cross_section__candidate__global_max_id']==1
    a,d=summarize(ctx,np.array([[0,0,2]],np.int16),np.zeros_like(S),np.zeros_like(W),mask);assert a['cross_section__candidate__global_max_id']==0 and d['cross_section__candidate']['eligible_cells']==1
    a,d=summarize(ctx,np.ones_like(C),S,W,mask);assert a['cross_section__candidate__global_max_id']==-1 and d['cross_section__candidate']['empty_candidate']
    ctx.maxcache={};S=np.array([[1,1,2]],np.int32);C=np.array([[2,2,2]],np.int16);W=np.array([[math.log(12),np.nextafter(math.log(12),np.inf),math.log(3)]])
    a,d=summarize(ctx,C,S,W,mask,True);assert a['cross_section__candidate__global_tie_count']==2 and a['cross_section__candidate__weighted__last'][0,0]==2 and d['cross_section__candidate']['global_float_tie_set_changed']
    return {'pass':True,'tests':['composite factor identity log2+log6=log3+log4','singleton/composite identity','zero-score versus two zero-weight factors','candidate threshold based on k not weight','draw-specific eligibility','null empty candidate','nextafter split corrected to exact tie'],'comparison':'canonical Fraction, no epsilon/float shortlist'}

def main():
    test=tests();save(D/'TESTS.json',test)
    receipt=D/'RUN_RECEIPT.json'
    if receipt.exists():raise RuntimeError('Existing correction receipt; preserve and explicitly recover failures, do not overwrite completed repair')
    manifest=json.loads((R/'HASHES.json').read_text())
    for rel,h in manifest.items():assert sha(R/rel)==h,rel
    original_pins={str(R/'HASHES.json'):sha(R/'HASHES.json'),str(ROOT/'DESIGN.md'):sha(ROOT/'DESIGN.md'),str(ROOT/'DELIVERY_HASHES.json'):sha(ROOT/'DELIVERY_HASHES.json')}
    pins={str(p):sha(p) for p in [D/'postprocess.py',D/'METHOD.md']}
    state={'status':'RUNNING','pid':os.getpid(),'started_unix':time.time(),'original_manifest_files':len(manifest),'original_pins':original_pins,'correction_pins':pins,'random_draws_executed':0,'python':sys.version,'numpy':np.__version__};save(receipt,state)
    def progress(**msg):state['progress']=msg;save(receipt,state);print(json.dumps(msg),flush=True)
    index=json.loads((R/'INDEX.json').read_text());forms=index['forms'];source=index['source_pages'];original=[set(x) for x in index['source_form_indices']]
    allchanges={};scope=[];panel=[]
    try:
        for policy in POLICIES:
            P=R/policy;O=D/policy;O.mkdir();allchanges[policy]={}
            for kind in ('page','paragraph'):
                progress(policy=policy,kind=kind,phase='observed exact ranks')
                rp=np.load(P/(kind+'_receiver_form_index.npz'));ri=json.loads((P/(kind+'_receiver_index.json')).read_text());ctx=ExactContext(rp['presence'],ri['form_df']);base=np.load(P/(kind+'_observed.npz'));basemasks={u:base[u] for u in UNIVERSES};unitnames=[u['id'] for u in ri['units']]
                observed_ids={};allchanges[policy][kind]={}
                variants=[('base',original,source,basemasks,P/(kind+'_observed.npz')),('no_single_character',[{w for w in ws if len(forms[w])>1} for ws in original],source,basemasks,P/(kind+'_no_single_character.npz'))]
                subtypeindex=json.loads((P/(kind+'_subtype_index.json')).read_text());sgnames=subtypeindex['source_groups'];wordidx={f:i for i,f in enumerate(forms)}
                sgroups=[{wordidx[r['bundle']] for r in index['eligible_label_rows'] if r['folio']+'|'+r['subtype']==name} for name in sgnames];sub=np.load(P/(kind+'_subtype_observed.npz'))
                variants.append(('subtype',sgroups,sgnames,{u:sub[u] for u in UNIVERSES},P/(kind+'_subtype_observed.npz')))
                for variant,groups,names,masks,oldpath in variants:
                    old=np.load(oldpath);C,S,W=ctx.matrices(groups);assert np.array_equal(C,old['count']) and np.array_equal(W,old['weighted'])
                    arrays,details=summarize(ctx,C,S,W,masks,True);arrays['score_ids']=S;arrays['count']=C
                    for key in details:
                        changes=0
                        for end in ('first','last'):
                            field=key+'__weighted__'+end;changes+=int((arrays[field]!=old[field]).sum())
                        details[key]['changed_first_or_last_rank_entries']=changes
                    outfile=O/(kind+'_'+variant+'_EXACT.npz');np.savez_compressed(outfile,**arrays)
                    save(O/(kind+'_'+variant+'_SUMMARY.json'),{'registry':kind+'_EXACT_SCORES.json','source_names':names,'receiver_names':unitnames,'summaries':details})
                    allchanges[policy][kind][variant]=details;scope.append({'original':str(oldpath.relative_to(ROOT)),'corrected':str(outfile.relative_to(ROOT)),'fields':'weighted ranks, exact score IDs, candidate/unrestricted row/global maxima and ties; count matrix verified unchanged'})
                    if variant=='base':
                        observed_ids={k:int(v) for k,v in arrays.items() if k.endswith('__global_max_id')}
                        if policy==PRIMARY:
                            chosen=defaultdict(list)
                            for u,m in masks.items():
                                eligible=m&(C>=2)
                                if eligible.any():
                                    for g,j in np.argwhere(eligible&(C==C[eligible].max())):chosen[(int(g),int(j))].append(u+'__candidate_count_maximum')
                                    sid=observed_ids[u+'__candidate__global_max_id']
                                    for g,j in np.argwhere(eligible&(S==sid)):chosen[(int(g),int(j))].append(u+'__candidate_weighted_maximum')
                            g=source.index('f82v');targets=['f43v','f108v','f75r','f76r'] if kind=='page' else ['f43v.P1','f108v.P7','f75r.P3','f76r.P3']
                            for target in targets:
                                if target in unitnames:chosen[(g,unitnames.index(target))].append('exposed_diagnostic')
                            for (g,j),reasons in sorted(chosen.items()):
                                shared=sorted(w for w in original[g] if ctx.B[w,j]);value=ctx.ratios[int(S[g,j])]
                                panel.append({'policy':policy,'kind':kind,'source':source[g],'receiver':unitnames[j],'reasons':reasons,'candidate':len(shared)>=2,'count':len(shared),'exact_score_id':int(S[g,j]),'registry':policy+'/'+kind+'_EXACT_SCORES.json','numerator':str(value.numerator),'denominator':str(value.denominator),'approximate_original_weight':float(W[g,j]),'forms':[{'form':forms[w],'df':ri['form_df'][w],'leave_one_out_count':len(shared)-1,'leave_one_out_numerator':str((value*Fraction(ctx.factors[w],ctx.q)).numerator),'leave_one_out_denominator':str((value*Fraction(ctx.factors[w],ctx.q)).denominator)} for w in shared]})
                for model in ('section_and_dfbin','section_only'):
                    for drawtype in ('ensemble','diagnostic'):
                        graphfile=P/(model+('_graphs.npz' if drawtype=='ensemble' else '_diagnostic_graphs.npz'));graph=np.load(graphfile);edgeg=graph['edge_source'];assign=graph['assignments'];retained=defaultdict(list);detailrows=[]
                        oldstats=np.load(P/(model+'_'+kind+'_summaries.npz')) if drawtype=='ensemble' else None
                        receipts=json.loads((P/(model+'_draw_receipts.json')).read_text()) if drawtype=='ensemble' else None
                        diag=json.loads((P/(model+'_DIAGNOSTIC_CHAINS.json')).read_text()) if drawtype=='diagnostic' else None
                        for draw,wordrow in enumerate(assign):
                            groups=[set(wordrow[edgeg==g].tolist()) for g in range(len(source))];C,S,W=ctx.matrices(groups)
                            if drawtype=='ensemble':
                                assert arrhash(C)==receipts[draw]['matrix_hashes'][kind]['count'] and arrhash(W)==receipts[draw]['matrix_hashes'][kind]['weighted']
                                validate_original_summary(C,W,basemasks,oldstats,draw)
                            else:
                                previous=diag[draw//10]['checkpoints'][draw%10]['scores'][kind]
                                for u,mask in basemasks.items():
                                    for e in ELIG:
                                        m=mask if e=='unrestricted' else mask&(C>=2)
                                        assert int(m.sum())==previous[u][e]['cells']
                                        for met,A in [('count',C),('weighted',W)]:
                                            mx=float(A[m].max()) if m.any() else None;assert mx==previous[u][e][met]['maximum']
                                            for g,name in enumerate(source):assert (float(A[g,m[g]].max()) if m[g].any() else None)==previous[u][e][met]['source_row_maxima'][name]
                            arrays,details=summarize(ctx,C,S,W,basemasks)
                            for key,value in arrays.items():retained[key].append(value)
                            detailrows.append({'seed':int(graph['seeds'][draw]),'checkpoint':int(graph['checkpoints'][draw]) if drawtype=='diagnostic' else None,'summaries':details})
                            if (draw+1)%25==0:progress(policy=policy,kind=kind,model=model,drawtype=drawtype,completed=draw+1,total=len(assign),exact_scores=len(ctx.ratios),cached_sets=len(ctx.cache))
                        np.savez_compressed(O/(model+'_'+kind+'_'+drawtype+'_EXACT.npz'),**{k:np.array(v) for k,v in retained.items()},seeds=graph['seeds'])
                        save(O/(model+'_'+kind+'_'+drawtype+'_DETAILS.json'),{'registry':kind+'_EXACT_SCORES.json','receivers':unitnames,'sources':source,'draws':detailrows})
                        scope.append({'original':str(graphfile.relative_to(ROOT)),'corrected':str((O/(model+'_'+kind+'_'+drawtype+'_EXACT.npz')).relative_to(ROOT)),'fields':'saved-graph exact weighted row/global maxima and full tie masks; all original approximate summaries and count scores verified'})
                        if drawtype=='ensemble':
                            result={};original_report=json.loads((P/(model+'_ENSEMBLE.json')).read_text())
                            for u in UNIVERSES:
                                result[u]={}
                                for e in ELIG:
                                    pre=u+'__'+e;obs=observed_ids[pre+'__global_max_id'];ids=[int(x) for x in retained[pre+'__global_max_id']];available=[i for i in ids if i>=0];vals=[ctx.ratios[i] for i in available]
                                    old=original_report['receiving_kinds'][kind][u][e]['weighted'];meet=sum(v>=ctx.ratios[obs] for v in vals) if obs>=0 else None
                                    ordered=sorted(vals);median=(ordered[(len(ordered)-1)//2]+ordered[len(ordered)//2])/2 if ordered else None
                                    encode=lambda f:None if f is None else {'numerator':str(f.numerator),'denominator':str(f.denominator)}
                                    result[u][e]={'observed_max_id':obs,'total_draws':len(ids),'available_score_denominator':len(vals),'empty_draws':len(ids)-len(vals),'controls_meeting_or_exceeding_observed':meet,'original_float_controls_meeting_or_exceeding':old['controls_meeting_or_exceeding_observed'],'exceedance_count_changed':meet!=old['controls_meeting_or_exceeding_observed'],'control_min_ratio':encode(min(vals) if vals else None),'control_max_ratio':encode(max(vals) if vals else None),'middle_order_ratios':[] if not ordered else [encode(ordered[(len(ordered)-1)//2]),encode(ordered[len(ordered)//2])],'global_float_tie_set_changed_draws':sum(r['summaries'][pre]['global_float_tie_set_changed'] for r in detailrows),'source_float_tie_rows_changed':sum(r['summaries'][pre]['source_tie_rows_changed'] for r in detailrows),'global_float_nonmaximizer_draws':sum(r['summaries'][pre]['global_float_maximizer_not_exact_maximum'] for r in detailrows)}
                            save(O/(model+'_'+kind+'_EXCEEDANCE.json'),{'registry':kind+'_EXACT_SCORES.json','summary':result})
                ctx.export(O/(kind+'_EXACT_SCORES.json'))
        save(D/'OBSERVED_CHANGES.json',allchanges);save(D/'SCOPE.json',scope);save(D/'EXACT_EXPLANATION_PANEL.json',panel)
        for rel,h in manifest.items():assert sha(R/rel)==h,rel
        for p,h in original_pins.items():assert sha(p)==h,p
        for p,h in pins.items():assert sha(p)==h,p
        state['status']='COMPLETED';state['finished_unix']=time.time();state['elapsed_seconds']=state['finished_unix']-state['started_unix'];state['observed_variant_matrices_corrected']=24;state['saved_graph_kind_comparisons']=3680;save(receipt,state)
        save(D/'HASHES.json',{str(p.relative_to(D)):sha(p) for p in D.rglob('*') if p.is_file() and p.name not in ('HASHES.json','EXECUTION.log') and '__pycache__' not in str(p)})
        print('COMPLETED',state['elapsed_seconds'],flush=True)
    except BaseException as e:
        state['status']='FAILED';state['failure']=repr(e);state['failed_unix']=time.time();save(receipt,state);raise
if __name__=='__main__':
    if '--test-only' in sys.argv:print(json.dumps(tests(),indent=2))
    else:main()
