#!/usr/bin/env python3
"""P06 sensitivity: does the register split hold without the three bucket pages whose membership
depends on word boundaries? (P01, 2026-09-28.) Read-only. Run: python3 sensitivity_boundary_pages.py

f35v.7 co,kol and f56v.9 kch,okaiin join into words holding a list token when the comma (an
uncertain space in the ZL) is read as no space; f68v2.6 holds okor only in its second reading.
prep/zl.py reads a comma as a space and takes the first reading, so all three are in the 21-page
bucket. This script reruns the mint rule (filtered shares) with the three dropped, and with the
three moved to the anchored side. Output: sensitivity_boundary_pages_output.txt beside this file.
"""
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, '../../../resources/tools/provenance/index.html#s-17b20ecd17b24816')
import p06_test as t  # noqa: E402  (no side effects on import; main() is guarded)

BOUNDARY = {'f35v', 'f56v', 'f68v2'}


def controls(pages, latt, bucket, anchored):
    u110 = [p for p in anchored if t.para_token_count(pages, p) < 110]
    ctl = {'overall': (bucket, anchored), 'length control (anchored under 110)': (bucket, u110)}
    for lang in 'AB':
        ctl[f'Currier {lang}'] = ([p for p in bucket if pages[p]['vars'].get('L') == lang],
                                  [p for p in anchored if pages[p]['vars'].get('L') == lang])
    for sec in sorted(set(pages[p]['vars'].get('I', '?') for p in latt)):
        b = [p for p in bucket if pages[p]['vars'].get('I') == sec]
        a = [p for p in anchored if pages[p]['vars'].get('I') == sec]
        if len(b) >= 3 and len(a) >= 3:
            ctl[f'section {sec}'] = (b, a)
    return ctl


def main():
    pages, latt = t.load_pages()
    bucket, anchored = t.classify_bucket(pages, latt)
    variants = {
        f'as fixed ({len(bucket)} pages)': (bucket, anchored),
        'three boundary pages dropped': ([p for p in bucket if p not in BOUNDARY], anchored),
        'three boundary pages moved to anchored': ([p for p in bucket if p not in BOUNDARY],
                                                   anchored + sorted(BOUNDARY & set(bucket))),
    }
    out = []
    for name, (bk, an) in variants.items():
        out.append(name)
        for cname, (b, a) in controls(pages, latt, bk, an).items():
            c = t.build_control(pages, b, a, True)
            bs, as_ = c['bucket']['shares'], c['anchored']['shares']
            out.append(f"    {cname}: {len(b)} vs {len(a)} pages, rule holds {t.rule_holds(c)}; "
                       f"ch/sh {100 * bs['ch_sh']:.1f} vs {100 * as_['ch_sh']:.1f}, "
                       f"d {100 * bs['d']:.1f} vs {100 * as_['d']:.1f}, "
                       f"o {100 * bs['o']:.1f} vs {100 * as_['o']:.1f}")
    text = '\n'.join(out) + '\n'
    with open(os.path.join(HERE, 'sensitivity_boundary_pages_output.txt'), 'w') as f:
        f.write(text)
    print(text, end='')


if __name__ == '__main__':
    main()
