"""Descriptive exact background profiles on already retained graphs; no RNG."""
from pathlib import Path
import json, hashlib, time
import numpy as np
D=Path(__file__).resolve().parent
B=D.parent
R=B/'gap_boundary_controls/results'
P=R/'comma_unresolved__no_Pb'
profiles=B/'receiver_background_profile/ALL_FORMS.json'
metric=B/'receiver_background_profile/review/SAVED_GRAPH_METRIC.md'
inputs=[R/'INDEX.json', profiles, metric, Path(__file__)]
models=('section_and_dfbin','section_only')
inputs += [P/(m+'_graphs.npz') for m in models]
pins={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in inputs}
with (D/'RUN_INTENT.json').open('x') as f:
    json.dump({'started_unix':time.time(),'input_pins':pins,'random_draws':0},f,indent=2)
idx=json.loads(inputs[0].read_text())
raw=json.loads(profiles.read_text())
assert [r['form'] for r in raw['forms']]==idx['forms']
assert len(raw['groups']['L']['A'])==114 and len(raw['groups']['L']['B'])==79
adf=[];bdf=[]
for row in raw['forms']:
    for axis,out in [('A',adf),('B',bdf)]:
        q=row['groups']['L'][axis]
        assert q['numerator']==len(set(q['pages']))
        assert set(q['pages'])<=set(raw['groups']['L'][axis])
        out.append(q['numerator'])
adf=np.array(adf,dtype=np.int64);bdf=np.array(bdf,dtype=np.int64)
delta=114*bdf-79*adf
observed=np.array([sum(int(delta[w]) for w in row) for row in idx['source_form_indices']],dtype=np.int64)
sections=np.array(idx['source_sections'])
section_totals={s:int(observed[sections==s].sum()) for s in sorted(set(sections))}
all_summaries={};checks={}
for model in models:
    z=np.load(P/(model+'_graphs.npz'))
    assignments=z['assignments'];sources=z['edge_source'];seeds=z['seeds']
    assert assignments.shape==(200,755) and sources.shape==(755,)
    assert np.array_equal(seeds,np.arange(10000,10200))
    assert np.array_equal(np.bincount(sources,minlength=53),idx['source_degrees'])
    values=np.zeros((200,53),dtype=np.int64)
    a_sums=np.zeros_like(values);b_sums=np.zeros_like(values)
    original_degrees=np.bincount(np.concatenate(idx['source_form_indices']),minlength=627)
    for n,forms in enumerate(assignments):
        assert len(set(zip(map(int,sources),map(int,forms))))==755
        assert np.array_equal(np.bincount(forms,minlength=627),original_degrees)
        np.add.at(values[n],sources,delta[forms])
        np.add.at(a_sums[n],sources,adf[forms])
        np.add.at(b_sums[n],sources,bdf[forms])
        assert np.array_equal(values[n],114*b_sums[n]-79*a_sums[n])
        assert int(values[n].sum())==int(observed.sum())
        for s,total in section_totals.items():
            assert int(values[n,sections==s].sum())==total
    np.savez_compressed(D/(model+'_VALUES.npz'),numerators=values,A_df_sums=a_sums,B_df_sums=b_sums,seeds=seeds)
    summaries=[]
    for j,name in enumerate(idx['source_pages']):
        v=sorted(map(int,values[:,j]));o=int(observed[j]);aa=sum(int(adf[w]) for w in idx['source_form_indices'][j]);bb=sum(int(bdf[w]) for w in idx['source_form_indices'][j])
        summaries.append({'source':name,'section':str(sections[j]),'degree':idx['source_degrees'][j],
          'observed_numerator':o,'denominator':9006,'observed_A_expected_overlap':{'numerator':aa,'denominator':114},'observed_B_expected_overlap':{'numerator':bb,'denominator':79},
          'controls':{'draws':200,'minimum_numerator':v[0],'median_central_numerators':[v[99],v[100]],'maximum_numerator':v[-1],'distinct_numerators':len(set(v)),'meeting_or_exceeding_observed':sum(x>=o for x in v),'equal_to_observed':v.count(o)},
          'interpretation':'Exploratory fixed-background descriptive profile, not a calibrated probability or referral test.'})
    all_summaries[model]=summaries
    checks[model]={'draws_consumed':200,'degree_simplegraph_and_total_checks':'PASS'}
result={'status':'COMPLETED','random_draws_executed':0,'background_exclusions':raw['excluded_pages'],'background_language_pages':{'A':114,'B':79,'MISSING':9},'sources':idx['source_pages'],'observed_grand_numerator':int(observed.sum()),'observed_section_numerators':section_totals,'models':all_summaries,'checks':checks}
(D/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n')
for p,h in pins.items():assert hashlib.sha256(Path(p).read_bytes()).hexdigest()==h
(D/'RUN_RECEIPT.json').write_text(json.dumps({'status':'COMPLETED','finished_unix':time.time(),'input_pins':pins,'new_random_draws':0,'saved_graphs_consumed':400},indent=2)+'\n')
for m,rows in all_summaries.items():print(m,next(r for r in rows if r['source']=='fRos'))
