"""Geometry-only selection. Run with earlier notebook modules available: python -B layout_205_select.py layout_205_slots.json.
No decryption or rune-value inspection. geometry_tokens and select can be imported on solved source text.
"""
import json,re,sys,hashlib
from itertools import combinations
from collections import defaultdict,Counter
from pathlib import Path
R='ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
SENT='\x00'
def evidence_dir():
    here=Path(__file__).resolve().parent
    if (here/'liber-primus__transcription--master.txt').is_file():return here
    # Resolve the installed notebook path without importing any rune-processing module.
    from importlib.util import find_spec
    return Path(find_spec('lp_core').origin).resolve().parent
EXCLUDE=((9741,9745),(10256,10260),(11240,11244),(12203,12207))
def mask(raw):
    assert SENT not in raw
    return raw.translate(dict.fromkeys(map(ord,R),SENT))
def norm(raw):return ''.join(c for c in raw if c not in '/%' and not c.isspace())
def geometry_tokens(source):
    m=mask(source)
    return tokens_masked(m)
def tokens_masked(m):
    assert not any(ch in R for ch in m)
    tokens=[];p=s=g=po=0;curr=None
    for ix,c in enumerate(m):
        if c==SENT:
            if curr is None:
                curr=dict(offset=g,length=0,page=p,end_page=p,section=s,page_offset=po,first_ix=ix,last_ix=ix)
                tokens.append(curr)
            curr['last_ix']=ix;curr['end_page']=p;curr['length']+=1;g+=1;po+=1
        elif c=='%':p+=1;po=0
        elif c=='/' or c.isspace():pass
        elif c in "'’" and 0<ix<len(m)-1 and m[ix-1]==SENT==m[ix+1]:pass
        else:
            curr=None
            if c=='$':s+=1
    for i,t in enumerate(tokens):
        t['raw_before']=m[tokens[i-1]['last_ix']+1 if i else 0:t['first_ix']]
        t['raw_after']=m[t['last_ix']+1:tokens[i+1]['first_ix'] if i+1<len(tokens) else len(m)]
        assert SENT not in t['raw_before']+t['raw_after']
        t['before']=norm(t['raw_before']);t['after']=norm(t['raw_after'])
    return tokens
def overlap(a,b,c,d):return a<d and c<b
def select(tokens,section,exclude=(),limit=3,*,marked_only=False,reserved=()):
    groups=defaultdict(list)
    for i in range(len(tokens)):
        for n in range(2,5):
            ws=tokens[i:i+n]
            if len(ws)!=n or any(w['section']!=section or w['page']!=ws[0]['page'] or w['end_page']!=ws[0]['page'] for w in ws):continue
            a=ws[0]['offset'];b=ws[-1]['offset']+ws[-1]['length'];ls=tuple(t['length'] for t in ws);assert b-a==sum(ls)
            ds=tuple([ws[0]['before']]+[w['after'] for w in ws]);raw=[ws[0]['raw_before']]+[w['raw_after'] for w in ws]
            if b-a<6 or any(overlap(a,b,c,d) for c,d in exclude) or any(ch.isdigit() for v in ds for ch in v):continue
            groups[ls,ds].append(dict(offset=a,page=ws[0]['page'],local=ws[0]['page_offset'],word_starts=[w['offset'] for w in ws],raw=raw))
    pairs=[];paircounts=Counter();occurrences=Counter()
    for (ls,ds),group in groups.items():
        marked=any(c not in '-$&§' for q in ds for c in q);n=len(ls);L=sum(ls);freq=len(group);tag=f'{n}{"_marked" if marked else "_ordinary"}'
        occurrences[tag]+=freq
        for v,w in combinations(group,2):
            a,b=v['offset'],w['offset']
            if b<a+L:continue
            paircounts[tag+'_nonoverlap']+=1
            if (b-a)%4==0:continue
            paircounts[tag+'_informative']+=1
            obj=dict(a=a,b=b,length=L,word_lengths=ls,delimiters=ds,marked=marked,signature_frequency=freq,phase=(b-a)%4,page_a=v['page'],page_b=w['page'],local_a=v['local'],local_b=w['local'],starts_a=v['word_starts'],starts_b=w['word_starts'],raw_punctuation_a=v['raw'],raw_punctuation_b=w['raw'])
            pairs.append(((-n,-int(marked),freq,-L,a,b),obj))
    used=list(reserved);picked=[]
    for _,row in sorted(pairs,key=lambda v:v[0]):
        if len(picked)>=limit:break
        if marked_only and not row['marked']:continue
        a,b=row['a'],row['b'];L=row['length'];sp=[(a,a+L),(b,b+L)]
        if any(overlap(s,e,t,u) for s,e in used for t,u in sp):continue
        used+=sp;picked.append(row)
    return dict(selected=picked,all_eligible_pairs=len(pairs),occurrences=dict(sorted(occurrences.items())),pairs=dict(sorted(paircounts.items())))
def main():
    # Input path/pagination are the same fixed archive conventions as lp_core; only a fixed marker
    # locates the start of the book before every glyph in the entire selected slice is masked.
    f=evidence_dir()/'liber-primus__transcription--master.txt';bs=f.read_bytes();digest=hashlib.sha256(bs).hexdigest()
    assert digest=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    raw=bs.decode();pages=raw[raw.index('ᚱ-'):].split('%')[:73];m=mask('%'.join(pages[15:71]));ts=tokens_masked(m)
    result=select(ts,8,EXCLUDE);return dict(source_sha256=digest,masked_utf8_sha256=hashlib.sha256(m.encode()).hexdigest(),section=8,excluded_half_open=EXCLUDE,n_section_words=sum(t['section']==8 for t in ts),rule='n words descending; marked first; occurrence count ascending; total runes descending; earliest two offsets. 2–4 words >=6 runes, bracket punctuation exact, distinct phase mod4; three disjoint selections. Numeral-bearing contexts excluded.',**result)
if __name__=='__main__':Path(sys.argv[1]).write_text(json.dumps(main(),indent=2,ensure_ascii=False)+'\n')
