"""Check the all-verse g|s|a|w number before/after 2:154 <-> 2:286.
Reads existing numerical inputs without modifying them.
"""
from pathlib import Path
import json
from independent_swap_audit import read_table, stream_mod, digit_mod, make_record, FORMATS

root = Path(__file__).resolve().parent.parent
source = read_table(root / 'kuran.txt', ('g', 's', 'a', 'w', 'h'))
by_ref = {(r['s'], r['a']): r for r in source}
left, right = by_ref[2, 154], by_ref[2, 286]
replacement = {(2, 154): right['w'], (2, 286): left['w']}

def check(rows, fields, swap=False):
    text = ''.join(make_record(r, fields, replacement.get((r['s'], r['a'])) if swap else None) for r in rows)
    residue = stream_mod(text)
    assert residue == digit_mod(text)
    return {'digits': len(text), 'digits_mod19': len(text) % 19, 'number_mod19': residue}

selected = read_table(root / 'AllahKelimesi/17138.txt', ('g', 's', 'a', 'an', 'ah'))
joined = [by_ref[r['s'], r['a']] | r for r in selected]
a, b = [next(r for r in joined if (r['s'], r['a']) == ref) for ref in ((2, 154), (2, 286))]
assert a['an'] == b['an'] and a['ah'] == b['ah']
result = {
    'source_rows': len(source),
    'swap': {'left': a, 'right': b},
    'all_verse_g_s_a_w': {'before': check(source, ('g','s','a','w')), 'after': check(source, ('g','s','a','w'), True)},
    'allah_formats': {name: {'before': check(joined, fields), 'after': check(joined, fields, True)} for name, fields in FORMATS.items()},
    'verification': '128-digit chunk modulus independently checked by digit-by-digit modulus; input files unchanged.'
}
print(json.dumps(result, ensure_ascii=False, indent=2))
