"""Bind the secondary visual screen to the underlying transcriptions and retained controls."""
import hashlib
import json
from math import comb, exp, factorial
from pathlib import Path
import re

O=Path(__file__).resolve().parent
H=Path('../../../resources/readers/provenance/source-c39881c5e485eb1b.html')
V=H/'Voynich'
W=H/'working'
Z=V/'analysis/transcriptions/ZL_ivtff_2b.txt'
S=V/'analysis/transcriptions/stolfi_inter.evt'
ASTRO=V/'hartlieb_deep_dig_2026-10-01'
C=W/'voynich_consolidation_2026-11-18/campaign_execution_2026-11-18'
lines=Z.read_text().splitlines()
index={}
for n,line in enumerate(lines,1):
    m=re.match(r'<(f[^,>]+),[^>]*>\s*(.*)',line)
    if m:index[m.group(1)]=(n,line,m.group(2))
notes=json.loads((O/'NATIVE_OBSERVATIONS.json').read_text())
frame=json.loads((O/'PROTOCOL.json').read_text())['diagram_frame']

def cited(locus):
    ln,raw,_=index[locus]
    return {'locus':locus,'file_line':ln,'raw':raw}
def witness(path):
    return {'path':str(path),'sha256':hashlib.sha256(path.read_bytes()).hexdigest()}
focus={
 'f67r1':(['f67r1.1'], 'Illuminated blades of the same type repeat in several wedges. Different local fields visible. Neither fill class alone chooses a unique written receiver here.','Nearest or same wedge can account for placement.'),
 'f67r2':(['f67r2.1','f67r2.10'], 'Five or more visually repeated red lunules and other disc types occupy distinct sectors. The 12 near-face positions and seven editor-identified headings are different inventories. A lunule colour alone remains ambiguous.','Angle/wedge with local inscription rather than colour alone.'),
 'f67v1':(['f67v1.13','f67v1.14'], 'More than one green star and many light stars occur beside different radial text lines. No unique green-star receiver from color by itself.','Local angle and nearest radial text.'),
 'f67v2':(['f67v2.2','f67v2.22'],'Exposed known local routing to inscriptions beside crossed and bent figure arrangements.','Figure location/nearest inscription.'),
 'f68r1':(['f68r1.5','f68r1.6','f68r1.7','f68r1.37'],'Rayed medallion at top encloses three short inscriptions; crescent below has one surrounding inscription. A query specifying the picture selects a distinct written region. Grove reads the first short group oty where ZL uses yky.','Local enclosure/proximity agrees. Fixed top for crescent fails on this panel.'),
 'f68r2':(['f68r2.6','f68r2.31'],'Crescent at top and rayed face at bottom have separate surrounding inscriptions. The placement is reversed relative to f68r1. Both circular strings contain editorially unresolved forms.','Local enclosure/proximity agrees. Fixed top for rays fails on this panel.'),
 'f68r3':(['f68r3.10','f68r3.11','f68r3.12','f68r3.22'],'The lone star, small grouped stars and adjoining curved stroke in the upper-left sector correspond to three separately transcribed text items. The curve approaches the face or its rim at the centre, whose circular text is a fourth referent. No visible arrowhead establishes direction. The cluster reading has the Grove doary variant.','Adjacent writing/graphic attachment places the groups. Nothing here independently selects a direction or identifies astronomical objects by name.'),
 'f70v1':([], 'April dark ram. Generic April gives both ram panels.','Month alone ties.'),
 'f71r':([], 'April pale ram. Clothing/color and central animal treatment differentiate the pictures given an external cue.','Month alone ties.'),
 'f71v':([], 'May pale bull. Two nearby wheel centers offer the same month heading.','Month alone ties.'),
 'f72r1':([], 'May red bull. Its paint differentiates the picture if red is supplied, while the two captions agree on May.','Month alone ties.')
}
records=[]
for obj in notes['records']:
    f=obj['locus']
    if f not in focus: continue
    ids,reading,rival=focus[f]
    candidate={**obj,'source_rows':[cited(l) for l in ids],
               'outcome':reading,'rival':rival,'action_or_lexical_translation':None,
               'status':'retrospective graphic retrieval' if f in ['f68r1','f68r2','f68r3','f67v2'] else 'nonunique input or no discriminating receiver for screened feature',
               'study_role':'exposed positive case' if f=='f67v2' else ('exposed month tie' if f not in frame['nearby'] else 'new screen of previously catalogued and described physical case'),
               'prospective_score':False}
    if not ids:
        candidate['caption_crop']=witness(ASTRO/'T2B_crops'/f'{f}_label.jpg')
    records.append(candidate)
assert len(records)==11
sfile=S.read_bytes().decode('latin1').splitlines()
snips={k:[{'file_line':i,'text':sfile[i-1]} for i in inds] for k,inds in {
 'f68r1_medallions':[15639,15642,15643,15650,15651,15681,15687,15688,15689,15825],
 'f68r2_medallions':[15874,15875,15879,15880,15886,15887,15923,16094],
 'f68r3_cluster_and_tail':[16147,16148,16149,16151,16152,16231,16232,16233,16234,16236,16237,16238,16239,16241]
 }.items()}
(O/'DIAGRAM_RESULTS.json').write_text(json.dumps({'sources':[witness(Z),witness(S),witness(ASTRO/'T2B_ZODIAC_CALENDARS.md')],'scope':'Six nearby diagrams on three catalogue canvases, previously exposed f67v2 calibration and four zodiac panels forming two month pairs. Same canvas and common editorial sources preserved.','source_position_record':snips,'cases':records,'medallions_exposure':'Earlier Stolfi commentary names Sun over Moon and Moon over Sun. The November inspection recorded the reversal before reading those positional comparisons. No independent prospective manuscript validation claimed.','support':'For a reader supplied a graphic target, the containing inscription changes with the chosen medallion. Physical placement and visual identity agree on observed groups. Source role of cue, historical reason for asking the question and outcome of reading each inscription remain unknown.'},indent=2,ensure_ascii=False)+'\n')

rl=W/'f57v_local_selector_2026-10-23/RESULT.json'
ring=json.loads(rl.read_text())
whole=W/'f57v_whole_folio_cycle_2026-10-21/RESULT.json'
full=json.loads(whole.read_text())
seam=W/'f57v_nw_crossstroke_2026-10-23/RESULT.md'
elig=C/'VMS-SELECTOR-01/CANDIDATE_ELIGIBILITY.json'
prior=json.loads(elig.read_text())['candidates'][:4]
cells=index['f57v.3'][2].split('>')[-1].split('.')
cycles=[cells[i:i+17] for i in range(0,len(cells),17)]
assert len(cells)==68
grid=list(zip(*cycles))
assert sum(len(set(x))==1 for x in grid)==14
ros=V/'cipher_battery_rerun_2026-09-02/PROBE2_ROSETTE_CONTRAST_PAIRS_2026-09-02.md'
rt=ros.read_text()
# Re-read printed components so any change to source tables is visible.
pair=[]
for label in ('text','cosmological'):
    m=re.search(r'(?m)^\| '+label+r' \(f[^|]+\| (\d+) \| (\d+) \|$',rt)
    assert m
    pair.append([int(i) for i in m.groups()])
vec={}
for a,b,c in re.findall(r'(?m)^\| (p|qo|y|o|da|yk|t|dc|sh)- \| (\d+) \| (\d+) \|$', rt):
    vec[a]=[int(b),int(c)]
assert len(vec)==9
n1,n2=map(sum,pair); ka=pair[0][0]+pair[1][0]; n=n1+n2
def hyper(x):return comb(ka,x)*comb(n-ka,n1-x)/comb(n,n1)
prob=hyper(pair[0][0])
fisher=sum(hyper(x) for x in range(max(0,n1-(n-ka)),min(ka,n1)+1) if hyper(x)<=prob*(1+1e-12))
total=sum(sum(x) for x in vec.values()); marg=[sum(x[i] for x in vec.values()) for i in range(2)]
chi=0.
for vals in vec.values():
    for i in range(2):
        expect=sum(vals)*marg[i]/total
        chi+=(vals[i]-expect)**2/expect
con=chi/2; chi_p=exp(-con)*sum(con**i/factorial(i) for i in range(4))
record={'source_inputs':[witness(x) for x in [Z,rl,whole,seam,elig,ros]],
 'ring':{'source_rows':[cited(l) for l in ['f57v.3','f57v.8','f77v.3','f66r.37','f66r.38','f66r.39','f66r.40','f66r.41']],
  'passes':cycles,'strict_invariant_count':14,'slot3':list(grid[2]),'slot9':list(grid[8]),'slot16':list(grid[15]),
  'phase_controls_with_equal_or_better_strict_hits':ring['phases_at_least_primary_strict_coverage'],'source_cycle_result':ring['primary_verdict'],
  'prior_whole_folio_findings':full['observations'],'retained_boundary_results':[{k:x[k] for k in ('candidate_id','retained_result','missing_observable')} for x in prior],
  'scoring':'No new scored forward prediction. No independent historical start plus directed switch-to-different-receiver rule in inspected ring, nearby seam or two named cross-folio cases.'},
 'rosettes':{'reported_finite_sample':'Original six related panels, three text and three cosmological. No new independently witnessed destination or distinct start among this reuse. The original association is with whole-group opening.',
  'contrast_2x2':pair,'fisher_exact_twosided_recomputed_from_printed_counts':fisher,'full_class_counts_second_tuple':vec,
  'chi_square':chi,'df':8,'p_against_chi_square_8_df':chi_p,'interpretation':'Restricted p/o contrast reproduces; fuller profile on second tuple gives p near .107. Per-panel exceptions persist. This is same-data verification, not new held validation or an entry-selection outcome.'}}
(O/'RING_ROSETTE_RESULT.json').write_text(json.dumps(record,indent=2,ensure_ascii=False)+'\n')
print('Eleven diagram/panel rows. Six-panel Fisher p',fisher,'full-vector p',chi_p)
