"""Session 85: reproduce retained solved methods and inventory prior coverage.

Run beside lp_core.py and the retained source records. Requires Python/NumPy.
No unknown-page decryption, language ranking, source rewriting or networking.
The expected rune streams are prior retained records, not independent new data.
"""
import hashlib
import json
from pathlib import Path

from lp_core import R, LET, pages, lp, vals, SEQS
from lexical_words import tokenize_words

ROOT = Path(__file__).resolve().parent


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def read(name):
    return json.loads((ROOT / name).read_text())


def advancing_decode(cipher, key, skips):
    plain, consumed = [], []
    counter = 0
    for position, value in enumerate(cipher):
        consumed.append(counter)
        if position in skips:
            assert value == 0
            plain.append(0)
        else:
            plain.append((value - key(counter)) % 29)
            counter += 1
    reconstructed = [p if i in skips else (p + key(consumed[i])) % 29
                     for i, p in enumerate(plain)]
    assert reconstructed == cipher
    return plain, counter


def main():
    master = ROOT / 'liber-primus__transcription--master.txt'
    assert sha(master) == 'b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    rules = read('increment_calibration_plan.json')['known_decode_rules']
    expected = {g['name']: g['values'] for g in read('increment_calibration_sources.json')['groups']}
    specs = [
        ('warning', [0], 'reflection_28', None, []),
        ('welcome', [1, 2], 'repeating_key', rules['welcome_key'], rules['welcome_unenciphered_F_offsets']),
        ('wisdom', [3], 'identity', None, []),
        ('koan', [4, 5, 6, 7], 'reflection_2', None, []),
        ('divinity', [8, 9, 10, 11], 'identity', None, []),
        ('second_koan', [12, 13], 'repeating_key', rules['second_koan_key'], rules['second_koan_unenciphered_F_offsets']),
        ('instruction', [14], 'identity', None, []),
        ('lp2_56', [71], 'prime_minus_one', None, [56]),
        ('lp2_57', [72], 'identity', None, []),
    ]
    records = []
    for name, indices, mechanism, key_runes, offsets in specs:
        source = '%'.join(pages[i] for i in indices)
        cipher = list(map(int, vals(source)))
        skips = set(offsets)
        key_values = list(map(int, vals(key_runes))) if key_runes else None
        if mechanism == 'identity':
            plain = cipher.copy(); recovered = plain; counter = None
        elif mechanism.startswith('reflection_'):
            shift = int(mechanism.split('_')[-1])
            plain = [(shift - c) % 29 for c in cipher]
            recovered = [(shift - p) % 29 for p in plain]; counter = None
        else:
            key = ((lambda k: key_values[k % len(key_values)]) if key_values
                   else (lambda k: int(SEQS['prime_minus_one'][k])))
            plain, counter = advancing_decode(cipher, key, skips)
            recovered = cipher  # advancing_decode checked the inverse explicitly.
        assert plain == expected[name], name
        assert recovered == cipher
        records.append({
            'name': name, 'parsed_page_indices': indices,
            'archive_images': ['01.jpg' if i == 0 else f'{i+2:02d}.jpg' for i in indices],
            'runes': len(cipher), 'mechanism': mechanism,
            'key_runes': key_runes, 'ordinal_key_values': key_values,
            'unenciphered_F_offsets': offsets, 'consumed_key_positions': counter,
            'boundary_behavior': ('No key counter.' if counter is None else
                                 'Counter starts at zero; continues across every internal page and punctuation; declared F exceptions consume no key.'),
            'matches_retained_literal_rune_reference': True, 'exact_reencryption': True,
            'plaintext_rune_values_sha256': hashlib.sha256(bytes(plain)).hexdigest(),
            'validation_limit': 'Known rules and exception locations supplied; this is reproduction, not unknown-key or skip-path recovery.',
        })
    assert sum(r['runes'] for r in records) == 2977
    assert len({i for r in records for i in r['parsed_page_indices']}) == 17
    # Retain the two welcome spelling irregularities, rather than correcting data.
    welcome = ''.join(LET[i] for i in expected['welcome'])
    assert welcome.count('ALOINGTHEWAY') == welcome.count('WIDSOM') == 1
    words = tokenize_words('%'.join(lp[:56]))
    singletons = [w for w in words if len(w['values']) == 1]
    assert len(words) == 2896 and len(singletons) == 83
    assert len({w['values'][0] for w in singletons}) == 28
    reports = [{'session': i, 'file': f'SESSION_{i}.md', 'sha256': sha(ROOT / f'SESSION_{i}.md')}
               for i in range(1, 85)]
    boundary = read('boundary_control_results.json')
    for control in boundary['position_dependent_controls']:
        assert control['full_baseline_matches_reference'] and control['exact_reencryption']
    coverage = read('mechanism_coverage_ledger.json')
    assert all(all(1 <= i <= 84 for i in row['sessions']) for row in coverage['prior_coverage'])
    inputs = ['increment_calibration_plan.json', 'increment_calibration_sources.json',
              'boundary_control_results.json', 'boundary_model.json', 'lp_core.py',
              'word_core.py', 'lexical_words.py', 'mechanism_coverage_ledger.json',
              'selective_F_feasibility_plan.json', 'mechanism_coverage_audit.py']
    result = {
        'session': 85, 'master_sha256': sha(master),
        'solved_text_pages': 17, 'solved_runes': 2977, 'known_method_groups': records,
        'corrected_unsolved_lexical_inventory': {'words': len(words), 'singletons': len(singletons),
                                                'singleton_types': 28},
        'prior_report_manifest': reports,
        'input_hashes': {name: sha(ROOT / name) for name in inputs},
        'selected_gap': coverage['selected_gap'],
        'no_unknown_page_search': True, 'no_new_plaintext': True,
        'source_limit': 'Retained community sources and expected streams; no fresh complete glyph reading or OpenPGP authentication.',
    }
    (ROOT / 'mechanism_coverage_results.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps({'solved_pages': 17, 'runes': 2977, 'reproduced_groups': len(records),
                      'reports_in_manifest': len(reports), 'no_unknown_page_search': True}))


if __name__ == '__main__':
    main()
