"""P06, register-split rerun under the mint rule (P01, Ed GO 2026-09-28 21:20 CT).

Read-only. Reproduces every number in REPORT.md and bucket.json. Text via
prep/zl.py (parse/words/is_para), never check2_raw_ivtff.py. Pages are the 226
lattice pages (Voynich/lattice_assemblies/*.md, excluding INDEX.md), mapped to
ZL pages; $L gives Currier language, $I gives section.

Run: python3 p06_test.py
"""
import glob
import json
import os
import sys
from collections import Counter

sys.path.insert(0, '../../../resources/tools/provenance/index.html#s-17b20ecd17b24816')
import zl  # noqa: E402

LATTICE_DIR = '../../../resources/readers/provenance/source-67a34d1930f7dad1.html'
OUT_DIR = os.path.dirname(os.path.abspath(__file__))

BOTH_LISTS = tuple(sorted(set(zl.F247_SIX) | set(zl.LATTICE_LABEL_LIST)))

INITIAL_FAMILIES = {
    'ch_sh': lambda w: w.startswith('ch') or w.startswith('sh'),
    'o': lambda w: w.startswith('o'),
    'q': lambda w: w.startswith('q'),
    'd': lambda w: w.startswith('d'),
}


def contains_any_list_token(word, tokens=BOTH_LISTS):
    return any(t in word for t in tokens)


def load_pages():
    pages, order = zl.parse()
    latt = sorted(
        os.path.basename(f)[:-3]
        for f in glob.glob(os.path.join(LATTICE_DIR, '*.md'))
        if not f.endswith('INDEX.md')
    )
    missing = [p for p in latt if p not in pages]
    if missing:
        raise SystemExit(f'lattice pages missing from ZL parse: {missing}')
    return pages, latt


def page_all_words(pages, page):
    """Every word on the page, every locus type (labels, paragraphs, circular, etc)."""
    out = []
    for _locus, _loctype2, _ltype, text in pages[page]['lines']:
        out.extend(zl.words(text))
    return out


def page_para_words(pages, page):
    """Words on paragraph-type loci only (is_para)."""
    out = []
    for _locus, _loctype2, ltype, text in pages[page]['lines']:
        if zl.is_para(ltype):
            out.extend(zl.words(text))
    return out


def classify_bucket(pages, latt):
    """Bucket = pages with no word (any locus) containing any token of either list."""
    bucket, anchored = [], []
    for p in latt:
        words = page_all_words(pages, p)
        if any(contains_any_list_token(w) for w in words):
            anchored.append(p)
        else:
            bucket.append(p)
    return bucket, anchored


def para_token_count(pages, page):
    return len(page_para_words(pages, page))


def initial_shares(pages, page_list, filtered):
    """Return (total_tokens, counts per family) over paragraph tokens for page_list.

    filtered=True removes every word containing any token of either list before
    counting (both the denominator and the family numerators).
    """
    total = 0
    counts = Counter()
    for p in page_list:
        words = page_para_words(pages, p)
        if filtered:
            words = [w for w in words if not contains_any_list_token(w)]
        total += len(words)
        for w in words:
            for fam, test in INITIAL_FAMILIES.items():
                if test(w):
                    counts[fam] += 1
    return total, counts


def shares_row(pages, page_list, filtered):
    total, counts = initial_shares(pages, page_list, filtered)
    if total == 0:
        return {'pages': len(page_list), 'tokens': 0, 'shares': {k: None for k in INITIAL_FAMILIES}}
    return {
        'pages': len(page_list),
        'tokens': total,
        'shares': {k: counts.get(k, 0) / total for k in INITIAL_FAMILIES},
        'counts': {k: counts.get(k, 0) for k in INITIAL_FAMILIES},
    }


def build_control(pages, bucket, anchored_subset, filtered):
    b = shares_row(pages, bucket, filtered)
    a = shares_row(pages, anchored_subset, filtered)
    return {'bucket': b, 'anchored': a}


def rule_holds(control):
    """ch/sh surplus, d surplus, o deficit, all bucket vs anchored, on filtered shares."""
    b, a = control['bucket']['shares'], control['anchored']['shares']
    if b['ch_sh'] is None or a['ch_sh'] is None:
        return None  # no cells
    ch_sh_surplus = b['ch_sh'] > a['ch_sh']
    d_surplus = b['d'] > a['d']
    o_deficit = b['o'] < a['o']
    return ch_sh_surplus and d_surplus and o_deficit


def main():
    pages, latt = load_pages()
    bucket, anchored = classify_bucket(pages, latt)

    result = {
        'lattice_page_count': len(latt),
        'bucket_size': len(bucket),
        'anchored_size': len(anchored),
        'bucket_pages': [],
        'controls': {},
    }

    # bucket.json membership with $L, $I, paragraph token counts
    for p in sorted(bucket):
        v = pages[p]['vars']
        result['bucket_pages'].append({
            'page': p,
            'L': v.get('L', '?'),
            'I': v.get('I', '?'),
            'para_tokens': para_token_count(pages, p),
        })

    # length control: anchored pages under 110 paragraph tokens
    anchored_under110 = [p for p in anchored if para_token_count(pages, p) < 110]

    controls = {}

    # overall
    controls['overall'] = {
        'unfiltered': build_control(pages, bucket, anchored, filtered=False),
        'filtered': build_control(pages, bucket, anchored, filtered=True),
    }

    # within Currier A / Currier B
    for lang in ('A', 'B'):
        b_lang = [p for p in bucket if pages[p]['vars'].get('L') == lang]
        a_lang = [p for p in anchored if pages[p]['vars'].get('L') == lang]
        controls[f'currier_{lang}'] = {
            'unfiltered': build_control(pages, b_lang, a_lang, filtered=False),
            'filtered': build_control(pages, b_lang, a_lang, filtered=True),
        }

    # within each section ($I) where both cells have >=3 pages
    sections = sorted(set(pages[p]['vars'].get('I', '?') for p in latt))
    for sec in sections:
        b_sec = [p for p in bucket if pages[p]['vars'].get('I') == sec]
        a_sec = [p for p in anchored if pages[p]['vars'].get('I') == sec]
        if len(b_sec) >= 3 and len(a_sec) >= 3:
            controls[f'section_{sec}'] = {
                'unfiltered': build_control(pages, b_sec, a_sec, filtered=False),
                'filtered': build_control(pages, b_sec, a_sec, filtered=True),
            }

    # bucket against the length control (anchored under 110 paragraph tokens)
    controls['length_control_under110'] = {
        'unfiltered': build_control(pages, bucket, anchored_under110, filtered=False),
        'filtered': build_control(pages, bucket, anchored_under110, filtered=True),
    }

    result['controls'] = controls
    result['anchored_under110_size'] = len(anchored_under110)

    # verdict: pass only if rule holds on filtered, in every control that has cells
    verdicts = {}
    all_pass = True
    any_cell = False
    for name, c in controls.items():
        v = rule_holds(c['filtered'])
        verdicts[name] = v
        if v is not None:
            any_cell = True
            if not v:
                all_pass = False
    result['verdicts'] = verdicts
    result['pass'] = bool(all_pass and any_cell)

    with open(os.path.join(OUT_DIR, 'bucket.json'), 'w') as f:
        json.dump({
            'bucket_size': len(bucket),
            'members': result['bucket_pages'],
        }, f, indent=2)

    with open(os.path.join(OUT_DIR, 'full_result.json'), 'w') as f:
        json.dump(result, f, indent=2)

    print(json.dumps({
        'bucket_size': result['bucket_size'],
        'anchored_size': result['anchored_size'],
        'anchored_under110_size': result['anchored_under110_size'],
        'pass': result['pass'],
        'verdicts': result['verdicts'],
    }, indent=2))


if __name__ == '__main__':
    main()
