#!/usr/bin/env python3
"""Coordinator checks behind the P01 overrides of group D's and the superlatives pass's entries.

Read-only. Text and word boundaries from prep/zl.py. Run: python3 coordinator_checks_DS.py
Output is written beside this file as coordinator_checks_DS_output.txt and printed.

Group D and the superlatives pass tested some claims in a unit or list other than the finding's
own. This script retests each one in the finding's own stated form, then under F-247's six as
exact words and as contained strings, and under the lattice label list, one list at a time.

  rosette   findings 544 and 595: instances per locus, the rosette test's own metric and bands
  wp22      findings 252 and 256: WP22's unit, lines whose raw text holds the token, by page side
  balne     findings 565 and 575: f75r and f76v under each list and unit
  walk      superlatives 448, 453, 477, 478, 526, 542, 566, 568 under each list separately
"""
import os
import re
import sys
from collections import Counter, defaultdict

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

P, ORDER = zl.parse()
SIX = zl.F247_SIX
LAT = zl.LATTICE_LABEL_LIST
OUT = []


def say(s=''):
    OUT.append(s)


def ws(folio, pred=lambda lt: True):
    return [(loc, lt, w) for loc, _, lt, t in P[folio]['lines'] if pred(lt) for w in zl.words(t)]


def n_exact(words, lst):
    return sum(1 for *_, w in words if w in lst)


def n_contains(words, lst):
    return sum(1 for *_, w in words if any(t in w for t in lst))


READINGS = (('six exact', SIX, n_exact), ('six contains', SIX, n_contains),
            ('lattice exact', LAT, n_exact), ('lattice contains', LAT, n_contains))


# ---------------------------------------------------------------- rosette, 544 and 595
say('=' * 78)
say('ROSETTE, findings 544 and 595: instances per locus x 100 against the test bands')
say('bands: $F=a 27 to 73%, $F=z 7 to 40%; falsifier operationalized in the test report as any')
say('$F=a panel under 7% or any $F=z panel over 73%')
PANELS = ('f85r1', 'f85r2', 'f86v3', 'f86v4', 'f86v5', 'f86v6')
OWN = ('otedy', 'otal', 'okaiin', 'qotal', 'qotedy', 'qokaiin')
BAND = {'a': (27, 73), 'z': (7, 40)}


def own_rule(words):
    """The test's own set: bare members counted; words containing a member counted only when no
    word on the panel equals a member."""
    bare = n_exact(words, OWN)
    return bare if bare else n_contains(words, OWN)


for p in PANELS:
    lines = P[p]['lines']
    say(f"  {p}: $I={P[p]['vars'].get('I')} $F={P[p]['vars'].get('F')} loci={len(lines)} "
        f"types={dict(Counter(l[2] for l in lines))}")
# The test report's own counts are hand counts with a shifting qualified-form rule (its f86v4
# figures use 14 loci); they are quoted from the report, with only the ZL locus total applied,
# in the finding notes. The four list readings below are the P01 recount.
readings = [(n, (lambda f, l: (lambda w: f(w, l)))(f, l)) for n, l, f in READINGS]
for name, fn in readings:
    row, ranges, over73 = [], {'a': [], 'z': []}, []
    for p in PANELS:
        w = ws(p)
        k, n = fn(w), len(P[p]['lines'])
        d = 100 * k / n
        F = P[p]['vars'].get('F')
        lo, hi = BAND[F]
        verdict = 'in band' if lo <= d <= hi else ('below' if d < lo else 'above')
        ranges[F].append(d)
        if F == 'z' and d > 73:
            over73.append(p)
        row.append(f'{p} {k}/{n}={d:.1f}% {verdict}')
    a_lo, a_hi = min(ranges['a']), max(ranges['a'])
    z_lo, z_hi = min(ranges['z']), max(ranges['z'])
    overlap = not (a_hi < z_lo or z_hi < a_lo)
    inband = sum('in band' in r for r in row)
    say(f'  {name}: ' + '; '.join(row))
    say(f'      in band {inband} of 6; $F=a {a_lo:.1f} to {a_hi:.1f}, $F=z {z_lo:.1f} to {z_hi:.1f}, '
        f'overlap {overlap}; $F=z over 73%: {over73}')
anch = [l[0] for l in P['f86v4']['lines'] if any(w in SIX for w in zl.words(l[3]))]
say(f'  f86v4 loci holding a word of the six: {anch} ({len(anch)} of 9)')

# ---------------------------------------------------------------- WP22 unit, 252 and 256
say('')
say('=' * 78)
say("WP22 UNIT, findings 252 and 256: lines whose raw text holds the token (grep), page side f\\d+[rv]")


def side(page):
    return re.match(r'f\d+[rv]', page).group(0)


def num(page):
    return int(re.match(r'f(\d+)', page).group(1))


grep = defaultdict(lambda: defaultdict(int))  # side -> token -> lines
skipped = []
for page in ORDER:
    if not re.match(r'f\d+[rv]', page):
        skipped.append(page)
        continue
    for loc, _, lt, text in P[page]['lines']:
        for t in SIX:
            if t in text:
                grep[side(page)][t] += 1
tot = {s: sum(v.values()) for s, v in grep.items()}
say(f'  pages not named f<number><r|v>, left out of the page-side tally: {skipped}')
top = sorted(tot.items(), key=lambda kv: -kv[1])[:6]
say(f"  f86v: {dict(grep['f86v'])} total {tot.get('f86v')} types {len(grep['f86v'])} of 6 "
    f"(WP22 stated 37, 5 of 6); top page sides by total: {top}")
say(f"  f58r otal lines: {grep['f58r'].get('otal', 0)} (WP22 stated 12)")
SECT = {'astro f67 to f73': range(67, 74), 'herbal f1 to f66': range(1, 67),
        'balne f75 to f84': range(75, 85), 'prep f85 to f96': range(85, 97),
        'pharma f99 to f102': range(99, 103), 'recipes f103 to f116': range(103, 117)}
STATED = {('astro f67 to f73', 'oteody'): 9, ('herbal f1 to f66', 'otol'): 55,
          ('herbal f1 to f66', 'otal'): 28, ('balne f75 to f84', 'otedy'): 19,
          ('balne f75 to f84', 'qotal'): 14, ('balne f75 to f84', 'otal'): 18,
          ('pharma f99 to f102', 'otol'): 7, ('pharma f99 to f102', 'otal'): 4,
          ('recipes f103 to f116', 'otedy'): 22, ('recipes f103 to f116', 'otal'): 21,
          ('recipes f103 to f116', 'oteody'): 11}
for sec, rng in SECT.items():
    sides = [s for s in grep if num(s) in rng]
    per = {t: sum(1 for s in sides if grep[s].get(t)) for t in SIX}
    say(f'  {sec}: page sides holding each token {per}')
for (sec, t), v in STATED.items():
    sides = [s for s in grep if num(s) in SECT[sec]]
    got = sum(1 for s in sides if grep[s].get(t))
    say(f'    {sec} {t}: stated {v}, WP22-unit recount {got}')

# ---------------------------------------------------------------- balne, 565 and 575
say('')
say('=' * 78)
say('BALNE, findings 565 and 575')
for p in ('f75r', 'f76v'):
    w = ws(p)
    say(f'  {p}: lines {len(P[p]["lines"])} words {len(w)}')
    for name, lst, fn in READINGS:
        hits = [(loc, x) for loc, lt, x in w if (x in lst if 'exact' in name else any(t in x for t in lst))]
        say(f'    {name}: {len(hits)} {hits}')

# ---------------------------------------------------------------- walk superlatives
say('')
say('=' * 78)
say('WALK SUPERLATIVES, each list on its own')
WALK = ['f57v', 'f78r', 'f1r', 'f85r1', 'f85r2', 'f86v3', 'f86v4', 'f86v5', 'f86v6',
        'f70v1', 'f70v2', 'f76r', 'f67v1', 'f67v2', 'f67r2', 'f68r1', 'f68r2', 'f68v1',
        'f68v2', 'f70r1', 'f70r2', 'f71r', 'f71v', 'f72r1', 'f72r2', 'f72v1', 'f72v2',
        'f73r', 'f73v', 'f69r', 'f69v', 'f75r', 'f75v', 'f76v', 'f87r', 'f87v', 'f88r']
BALNE_ALL = ['f75r', 'f75v', 'f76r', 'f76v', 'f77r', 'f77v', 'f78r', 'f78v', 'f79r', 'f79v',
             'f80r', 'f80v', 'f81r', 'f81v', 'f82r', 'f82v', 'f83r', 'f83v', 'f84r', 'f84v']
BALNE_WALK = ['f78r', 'f76r', 'f75r', 'f75v', 'f76v']


def units(folios):
    """Merge f70v1 and f70v2 as f70v, the way the walk findings name it."""
    out = defaultdict(list)
    for f in folios:
        out['f70v' if f.startswith('f70v') else f].append(f)
    return out


def cnt(pages, lst, contains=False, pred=lambda lt: True):
    k = 0
    for p in pages:
        for loc, lt, w in ws(p, pred):
            if (any(t in w for t in lst) if contains else w in lst):
                k += 1
    return k


def nwords(pages):
    return sum(len(ws(p)) for p in pages)


def nlines(pages, pred=lambda lt: True):
    return sum(1 for p in pages for l in P[p]['lines'] if pred(l[2]))


# 448: bare otedy density, balne section, per word and per paragraph line
for unit_name, den in (('per word', nwords), ('per line', nlines)):
    rows = sorted(((f, cnt([f], ('otedy',)), den([f])) for f in BALNE_ALL), key=lambda r: -r[1] / r[2])
    say(f'  448 bare otedy {unit_name}, balne top 6: ' +
        ', '.join(f'{f} {a}/{b}={100 * a / b:.2f}%' for f, a, b in rows[:6]) +
        f"; f78r rank {[r[0] for r in rows].index('f78r') + 1}")

# 453: combined density on the six rosette panels, per list, per word and per locus
for name, lst, contains in (('six', SIX, False), ('six contains', SIX, True), ('lattice', LAT, False)):
    for unit_name, den in (('per word', nwords), ('per locus', nlines)):
        rows = sorted(((f, cnt([f], lst, contains), den([f])) for f in PANELS), key=lambda r: -r[1] / r[2])
        say(f'  453 {name} {unit_name}: ' + ', '.join(f'{f} {a}/{b}={100 * a / b:.1f}%' for f, a, b in rows[:3]))

# 477: label-position anchors per walked folio, count and share, per list
for name, lst, contains in (('six exact', SIX, False), ('six contains', SIX, True),
                            ('lattice exact', LAT, False), ('lattice contains', LAT, True)):
    rows = []
    for u, pages in units(WALK).items():
        lab = cnt(pages, lst, contains, zl.is_label)
        allk = cnt(pages, lst, contains)
        if lab:
            rows.append((u, lab, allk))
    by_count = sorted(rows, key=lambda r: -r[1])[:4]
    by_share = sorted(rows, key=lambda r: (-r[1] / r[2], -r[1]))[:4]
    say(f'  477 {name}: label count top {[(u, l, a) for u, l, a in by_count]}; '
        f'label share top {[(u, l, a, round(100 * l / a, 1)) for u, l, a in by_share]}')

# 478: first word of a Cc line in the list, whole walk
for name, lst, contains in (('six exact', SIX, False), ('six contains', SIX, True), ('lattice exact', LAT, False)):
    hits = []
    for f in WALK:
        for loc, _, lt, t in P[f]['lines']:
            if lt == 'Cc':
                w = zl.words(t)
                if w and (any(x in w[0] for x in lst) if contains else w[0] in lst):
                    hits.append((loc, w[0]))
    say(f'  478 Cc-line opener {name}: {hits}')

# 526: folios whose bare anchors (exact) all sit on Cc lines, per list
for name, lst in (('six', SIX), ('lattice', LAT)):
    only = []
    for u, pages in units(WALK).items():
        pos = Counter(lt for p in pages for loc, lt, w in ws(p) if w in lst)
        if pos and set(pos) == {'Cc'}:
            only.append((u, sum(pos.values())))
    say(f'  526 bare anchors on Cc lines only, {name}: {only}')

# 542: bare-anchor density per word, whole walk, per list
for name, lst, contains in (('six', SIX, False), ('lattice', LAT, False)):
    rows = sorted(((u, cnt(p, lst, contains), nwords(p)) for u, p in units(WALK).items()),
                  key=lambda r: -r[1] / r[2])
    f73 = next(r for r in rows if r[0] == 'f73r')
    say(f'  542 {name} exact per word, top 4: ' +
        ', '.join(f'{u} {a}/{b}={100 * a / b:.1f}%' for u, a, b in rows[:4]) +
        f'; f73r {f73[1]}/{f73[2]}={100 * f73[1] / f73[2]:.1f}% rank {[r[0] for r in rows].index("f73r") + 1}')

# 566: otoly corpus loci, exact and contains
ex = [(loc, w) for pg in ORDER if pg.startswith('f') for loc, lt, w in ws(pg) if w == 'otoly']
co = [(loc, w) for pg in ORDER if pg.startswith('f') for loc, lt, w in ws(pg) if 'otoly' in w]
say(f'  566 otoly exact {len(ex)} {ex}')
say(f'  566 otoly contains {len(co)} {co}')

# 568: anchor types and instances on the balne walk folios, per list and unit
for name, lst, contains in (('six exact', SIX, False), ('six contains', SIX, True),
                            ('lattice exact', LAT, False), ('lattice contains', LAT, True)):
    rows = []
    for f in BALNE_WALK:
        hits = [w for loc, lt, w in ws(f) if (any(t in w for t in lst) if contains else w in lst)]
        types = sorted({t for w in hits for t in lst if (t in w if contains else w == t)})
        rows.append((f, len(types), len(hits), types))
    say(f'  568 {name}: ' + '; '.join(f'{f} types {n} instances {k} {t}' for f, n, k, t in rows))

# ---------------------------------------------------------------- follow-up, own stated forms
say('')
say('=' * 78)
say('FOLLOW-UP, each claim in its own stated form')
# The 20 labels the lattice label list was picked from (research register message 22147,
# 2026-04-27 16:29:23, "CROSS-SECTION ANCHOR TOKEN LOCATIONS").
APRIL = {'f73r.1', 'f73r.6', 'f84r.47', 'f88r.6', 'f99v.6', 'f73v.23', 'f84r.8', 'f83v.35',
         'f88v.14', 'f82r.34', 'f99r.8', 'f75v.50', 'f99v.27', 'f84r.11', 'f101v.8', 'f73r.23',
         'f99r.11', 'f73v.1', 'f88r.15', 'f101v.10'}
assert len(APRIL) == 20


def hits(pages, lst, contains=False, pred=lambda lt: True):
    return [(loc, lt, w) for p in pages for loc, lt, w in ws(p, pred)
            if (any(t in w for t in lst) if contains else w in lst)]


# 252: WP22 section counts with f57v counted as astro and f58r left out of herbal
herbal = [s for s in grep if num(s) in range(1, 67) and s not in ('f57v', 'f58r')]
astro57 = [s for s in grep if num(s) in range(67, 74)] + ['f57v']
say(f"  252 herbal without f57v and f58r: otol {sum(1 for s in herbal if grep[s].get('otol'))} "
    f"(stated 55), otal {sum(1 for s in herbal if grep[s].get('otal'))} (stated 28); "
    f"f57v {dict(grep['f57v'])}, f58r {dict(grep['f58r'])}")
say(f"  252 astro with f57v: oteody {sum(1 for s in astro57 if grep[s].get('oteody'))} (stated 9)")

# 448: f78r paragraph openers and otedy positions
paras = [(loc, zl.words(t)) for loc, l2, lt, t in P['f78r']['lines'] if l2.startswith('@P')]
say(f"  448 f78r paragraphs {len(paras)}; openers {[(loc, w[0]) for loc, w in paras if w]}; "
    f"otedy openers {sum(1 for _, w in paras if w and w[0] == 'otedy')}")
for unit_name, den in (('per word', nwords), ('per line', nlines)):
    rows = sorted(((f, cnt([f], ('otedy',), True), den([f])) for f in BALNE_ALL), key=lambda r: -r[1] / r[2])
    say(f'  448 words containing otedy {unit_name}, balne top 4: ' +
        ', '.join(f'{f} {a}/{b}={100 * a / b:.2f}%' for f, a, b in rows[:4]) +
        f"; f78r rank {[r[0] for r in rows].index('f78r') + 1}")
say(f"  448 f78r otedy loci and word index: "
    f"{[(loc, zl.words(t).index('otedy')) for loc, _, lt, t in P['f78r']['lines'] if 'otedy' in zl.words(t)]}")

# 478: lattice label list as contained strings, Cc openers
co478 = [(loc, zl.words(t)[0]) for f in WALK for loc, _, lt, t in P[f]['lines']
         if lt == 'Cc' and zl.words(t) and any(x in zl.words(t)[0] for x in LAT)]
say(f'  478 Cc-line opener lattice contains: {co478}')

# 511: the finding's own falsifier, a prior walk folio with 3 or more anchors in 246 or fewer
# tokens spanning paragraph (P) and circular (C) lines; and the dispatch it names
DISPATCH = ['f67r2', 'f68r1', 'f68r2', 'f68v1', 'f68v2', 'f70r1', 'f70r2', 'f71r']
prior = units(WALK[:WALK.index('f70r2')])
for name, lst, fn in READINGS:
    contains = 'contains' in name
    h = hits(['f70r2'], lst, contains)
    own = f"f70r2 {len(h)}/{nwords(['f70r2'])} {[(l, w) for l, _, w in h]}"
    trips = []
    for u, pages in prior.items():
        hh = hits(pages, lst, contains)
        fam = {lt[0] for _, lt, _ in hh}
        if len(hh) >= 3 and nwords(pages) <= 246 and {'P', 'C'} <= fam:
            trips.append((u, len(hh), nwords(pages)))
    dens = sorted(((f, len(hits([f], lst, contains)), nwords([f])) for f in DISPATCH),
                  key=lambda r: -r[1] / r[2])
    say(f'  511 {name}: {own}; prior walk folios meeting the falsifier {trips}; dispatch by density '
        + ', '.join(f'{f} {a}/{b}' for f, a, b in dens[:4]))

# 524: bare otal on label lines, walk order up to f72r2
seq = [(loc, w) for f in WALK[:WALK.index('f72r2') + 1] for loc, lt, w in ws(f, zl.is_label) if w == 'otal']
say(f'  524 bare otal at label lines in walk order through f72r2: {seq}')

# 542, 549, 568: list hits that are among the April source labels
say(f"  542 f73r lattice exact label hits: {[(l, w, l in APRIL) for l, lt, w in hits(['f73r'], LAT, pred=zl.is_label)]}")
say(f"  542 f73r six exact label hits: {[(l, w) for l, lt, w in hits(['f73r'], SIX, pred=zl.is_label)]}; "
    f"six contains {[(l, w) for l, lt, w in hits(['f73r'], SIX, True, zl.is_label)]}")
say(f"  549 okol f73v.1 in April list {'f73v.1' in APRIL}; okary f73r.23 {'f73r.23' in APRIL}; "
    f"okaiin f72v2.21 {'f72v2.21' in APRIL}")
say(f"  568 f75v lattice exact hits: {[(l, lt, w, l in APRIL) for l, lt, w in hits(['f75v'], LAT)]}")
say(f"  568 f75v six exact hits: {[(l, lt, w) for l, lt, w in hits(['f75v'], SIX)]}")

# 550: first walk folio with a list word on a line of each position type
for name, lst in (('six', SIX), ('lattice', LAT)):
    first = {}
    for f in WALK:
        for loc, l2, lt, t in P[f]['lines']:
            for w in zl.words(t):
                if w in lst and l2 in ('@P0', '+P0', '@Ro') and l2 not in first:
                    first[l2] = (loc, w, WALK.index(f))
    say(f"  550 {name} exact, first walk locus per position type (walk index; f69r is "
        f"{WALK.index('f69r')}): {first}")

text = '\n'.join(OUT) + '\n'
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'coordinator_checks_DS_output.txt'), 'w') as fh:
    fh.write(text)
print(text, end='')
