"""Session 79: diagnose convergence in the unchanged Session 78 state rule.

No model fitting, parameter selection, network calls or changes to earlier outputs.
Python, NumPy and matplotlib; run beside the retained companion evidence files.
"""
import json
from collections import Counter

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import plaintext_swap_audit as frozen
from key_increment_audit import sha

ROOT = frozen.ROOT
N = 29


def forward_symbol(p, key, reserved, previous):
    ordinary = (p + key) % N
    if previous is None:
        return ordinary
    trigger = (previous - key) % N
    if p == reserved:
        return previous
    if p == trigger:
        return (reserved + key) % N
    return ordinary


def trace(cipher, parameters):
    parameters = np.asarray(parameters, dtype=np.int64)
    reserved = parameters[:, 0]
    key = parameters[:, 1].copy()
    states = np.empty((len(parameters), len(cipher) + 1), dtype=np.int16)
    plain = np.empty((len(parameters), len(cipher)), dtype=np.int16)
    states[:, 0] = key
    previous = None
    for offset, symbol in enumerate(cipher):
        current = int(symbol)
        p = (current - key) % N
        if previous is not None:
            p = reserved.copy() if current == previous else np.where(
                p == reserved, (previous - key) % N, p)
        plain[:, offset] = p
        key = (key + p * p) % N
        states[:, offset + 1] = key
        previous = current
    assert np.array_equal(plain, frozen.decode_many(cipher, parameters))
    return states, plain


def scalar_check(cipher, reserved, initial, states, plain):
    key, previous = int(initial), None
    assert int(states[0]) == key
    for offset, symbol in enumerate(cipher):
        current = int(symbol)
        possible = [p for p in range(N)
                    if forward_symbol(p, key, reserved, previous) == current]
        assert len(possible) == 1
        p = possible[0]
        assert p == int(plain[offset])
        key = (key + p * p) % N
        assert key == int(states[offset + 1])
        previous = current
    return len(cipher)


def cohort(states, plain, initials, cut):
    ordered = np.sort(states, axis=0)
    counts = 1 + np.count_nonzero(np.diff(ordered, axis=0), axis=0)
    assert counts[0] == len(initials)
    assert np.all(np.diff(counts) <= 0)
    # Each pair that merges remains equal at every later state and plaintext.
    for a in range(len(initials)):
        for b in range(a + 1, len(initials)):
            equal = np.flatnonzero(states[a] == states[b])
            if len(equal):
                start = int(equal[0])
                assert np.array_equal(states[a, start:], states[b, start:])
                assert np.array_equal(plain[a, start:], plain[b, start:])
    common = np.flatnonzero(counts == 1)
    first = int(common[0]) if len(common) else None
    last_differences = np.flatnonzero(np.any(plain != plain[:1], axis=0))
    common_suffix = int(last_differences[-1] + 1) if len(last_differences) else 0
    if first is not None:
        assert common_suffix == first
    classes = {}
    for i, value in enumerate(states[:, -1]):
        classes.setdefault(int(value), []).append(int(initials[i]))
    assert len({tuple(map(int, row)) for row in plain}) == len(initials)
    return {
        'initial_states': list(map(int, initials)),
        'distinct_state_counts_by_consumed_runes': counts.tolist(),
        'first_all_states_equal_after_runes': first,
        'first_common_finite_plaintext_suffix_offset': common_suffix,
        'distinct_states_at_prefix_cut': int(counts[cut]),
        'terminal_state_classes': [
            {'running_state': k, 'initial_seeds': v} for k, v in sorted(classes.items())],
        'distinct_full_plaintext_streams': len(initials),
        'distinct_continuation_streams': len({tuple(map(int, row[cut:])) for row in plain})
    }


def exact_maps():
    initial_sizes = Counter()
    shapes = {'repeat': Counter(), 'nonrepeat': Counter()}
    witness = None
    for current in range(N):
        outputs = [(k + (current - k) ** 2) % N for k in range(N)]
        initial_sizes[len(set(outputs))] += 1
        assert len(set(outputs)) == 15
        for a in range(N):
            for b in range(a + 1, N):
                assert (outputs[a] == outputs[b]) == ((a + b) % N == (2 * current - 1) % N)
    for reserved in range(N):
        for previous in range(N):
            for current in range(N):
                params = np.array([[reserved, k] for k in range(N)])
                # Supply previous ciphertext directly, without an initial step.
                p = (current - params[:, 1]) % N
                p = np.full(N, reserved) if current == previous else np.where(
                    p == reserved, (previous - params[:, 1]) % N, p)
                outputs = (params[:, 1] + p * p) % N
                mode = 'repeat' if current == previous else 'nonrepeat'
                size = len(set(map(int, outputs)))
                fiber = int(np.bincount(outputs, minlength=N).max())
                shapes[mode][(size, fiber)] += 1
                assert size == N if mode == 'repeat' else 14 <= size <= 16
                for k, plain in enumerate(p):
                    assert forward_symbol(int(plain), k, reserved, previous) == current
                if witness is None and mode == 'nonrepeat':
                    for a in range(N):
                        matches = [b for b in range(a + 1, N) if outputs[b] == outputs[a]]
                        if matches:
                            b = matches[0]
                            witness = {
                                'reserved_rune': reserved,
                                'previous_ciphertext': previous,
                                'current_ciphertext': current,
                                'before_states': [a, b],
                                'decoded_plaintext_values': [int(p[a]), int(p[b])],
                                'common_after_state': int(outputs[a])
                            }
                            break
    return {
        'initial_contexts': N,
        'initial_map_image_size_counts': dict(sorted(initial_sizes.items())),
        'later_contexts': N ** 3,
        'later_state_cases': N ** 4,
        'later_map_shapes': {
            mode: [{'image_size': size, 'largest_fiber': fiber, 'contexts': amount}
                   for (size, fiber), amount in sorted(table.items())]
            for mode, table in shapes.items()},
        'ordinary_quadratic_collision_identity_checked': True,
        'one_step_collision_witness': witness
    }


def constant_counterexample():
    checked = 0
    for current in range(N):
        for reserved in range(N):
            parameters = np.array([[reserved, k] for k in range(N)])
            states, plain = trace([current] * 128, parameters)
            ordered = np.sort(states, axis=0)
            counts = 1 + np.count_nonzero(np.diff(ordered, axis=0), axis=0)
            assert counts[0] == 29 and np.all(counts[1:] == 15)
            assert np.all(plain[:, 1:] == reserved)
            assert np.all((np.diff(states[:, 1:].astype(int), axis=1) % N) == reserved ** 2 % N)
            checked += 1
    return {'constant_ciphertext_cases': checked, 'runes_per_case': 128,
            'initial_states': 29, 'states_after_first_and_every_later_rune': 15,
            'interpretation': 'After the first quadratic step, repeated ciphertext adds R^2 to every state. The 15 states remain distinct indefinitely.'}


def real_coordinate(global_offset):
    start = 0
    for page, source in enumerate(frozen.lp[:56]):
        size = len(frozen.vals(source))
        if start <= global_offset < start + size:
            return {'lp2_page': page, 'page_rune_offset': global_offset - start}
        start += size
    raise AssertionError(global_offset)


def main():
    plan = json.loads((ROOT / 'plaintext_state_plan.json').read_text())
    prior = json.loads((ROOT / 'plaintext_swap_results.json').read_text())
    controls = json.loads((ROOT / 'plaintext_swap_controls.json').read_text())
    for payload in (prior, controls):
        for name, digest in payload['source_hashes'].items():
            assert sha(ROOT / name) == digest, name
    original_hashes = {name: sha(ROOT / name) for name in (
        'plaintext_swap_results.json', 'plaintext_swap_controls.json',
        'plaintext_swap_witnesses.json', 'liber-primus__transcription--master.txt')}
    maps = exact_maps()
    counterexample = constant_counterexample()
    real_rows, control_rows = [], []
    scalar_runes = 0
    for target in frozen.real_targets():
        states, plain = trace(target['cipher'], frozen.PARAMETERS)
        old = next(x for x in prior['real']['section_local_rows'] if x['section'] == target['id'])
        groups = []
        for reserved in range(N):
            block = slice(reserved * N, (reserved + 1) * N)
            groups.append({'reserved_rune': reserved, 'reserved_label': frozen.LET[reserved],
                           **cohort(states[block], plain[block], range(N), target['cut'])})
        selected = None
        if old['readings']:
            indices = [x['parameter_index'] for x in old['readings']]
            reserved = old['readings'][0]['reserved_rune']
            assert all(x['reserved_rune'] == reserved for x in old['readings'])
            seeds = [x['initial_key'] for x in old['readings']]
            for old_reading in old['readings']:
                index = old_reading['parameter_index']
                assert np.array_equal(plain[index], old_reading['decoded_values'])
                scalar_runes += scalar_check(target['cipher'], reserved,
                                            old_reading['initial_key'], states[index], plain[index])
            selected = {'reserved_rune': reserved, 'reserved_label': frozen.LET[reserved],
                        'parameter_indices': indices,
                        **cohort(states[indices], plain[indices], seeds, target['cut'])}
            after = selected['first_all_states_equal_after_runes']
            offset = after - 1
            selected['merge_witness'] = {
                'consumed_runes': after, 'section_rune_offset': offset,
                'global_rune_offset': target['global_start'] + offset,
                **real_coordinate(target['global_start'] + offset),
                'current_ciphertext': int(target['cipher'][offset]),
                'before_states': states[indices, offset].tolist(),
                'decoded_values_at_merge': plain[indices, offset].tolist(),
                'after_states': states[indices, after].tolist()
            }
        real_rows.append({'section': target['id'], 'runes': len(target['cipher']),
                          'prefix_runes': target['cut'], 'global_start': target['global_start'],
                          'designated_rune_cohorts': groups, 'selected_cohort': selected})
    for old in controls['rows']:
        reserved, initial = old['planted_pair']
        parameters = np.array([[reserved, k] for k in range(N)])
        states, plain = trace(old['ciphertext_values'], parameters)
        correct = np.array(old['correct_reading']['decoded_values'])
        cut = old['correct_reading']['prefix_runes']
        assert np.array_equal(plain[initial], correct)
        scalar_runes += scalar_check(old['ciphertext_values'], reserved, initial,
                                    states[initial], plain[initial])
        summary = cohort(states, plain, range(N), cut)
        summary['full_plaintext_exact_seeds'] = [k for k in range(N) if np.array_equal(plain[k], correct)]
        summary['continuation_exact_seeds'] = [k for k in range(N) if np.array_equal(plain[k, cut:], correct[cut:])]
        assert summary['full_plaintext_exact_seeds'] == [initial]
        control_rows.append({'source': old['source'], 'planted_pair': [reserved, initial],
                             'runes': len(correct), 'prefix_runes': cut, **summary})
    cohort_rows = [g for row in real_rows for g in row['designated_rune_cohorts']]
    times = [g['first_all_states_equal_after_runes'] for g in cohort_rows]
    summary = {
        'real_paths_traced': len(real_rows) * N * N,
        'real_designated_rune_cohorts': len(cohort_rows),
        'cohorts_fully_merged_by_section_end': sum(t is not None for t in times),
        'cohorts_fully_merged_by_prefix_cut': sum(g['distinct_states_at_prefix_cut'] == 1 for g in cohort_rows),
        'smallest_full_coalescence_runes': min(t for t in times if t is not None),
        'largest_full_coalescence_runes': max(t for t in times if t is not None),
        'control_cohorts_merged_by_cut': sum(g['distinct_states_at_prefix_cut'] == 1 for g in control_rows),
        'control_continuations_matching_for_all_29_seeds': sum(len(g['continuation_exact_seeds']) == N for g in control_rows),
        'independent_scalar_inverse_runes_checked': scalar_runes,
        'new_plaintext_established': False,
        'parameter_selection_changed': False
    }
    source_names = ['plaintext_state_plan.json', 'plaintext_state_audit.py',
                    'plaintext_swap_audit.py', 'plaintext_swap_plan.json',
                    'plaintext_swap_controls.json', 'plaintext_swap_results.json',
                    'plaintext_swap_witnesses.json', 'liber-primus__transcription--master.txt',
                    'lp_core.py', 'word_core.py', 'lexical_words.py', 'key_increment_audit.py',
                    'increment_calibration_sources.json']
    result = {'session': 79, 'role': plan['role'], 'timing': plan['timing'],
              'one_step_maps': maps, 'nonmerging_counterexample': counterexample,
              'controls': control_rows, 'real_sections': real_rows, 'summary': summary,
              'source_hashes': {name: sha(ROOT / name) for name in source_names},
              'limits': plan['limits']}
    (ROOT / 'plaintext_state_results.json').write_text(json.dumps(result, indent=2) + '\n')
    fig, axes = plt.subplots(1, 2, figsize=(11, 4.6), layout='constrained', sharey=True)
    for row in real_rows:
        if row['selected_cohort']:
            selected = row['selected_cohort']
            group = row['designated_rune_cohorts'][selected['reserved_rune']]
            y = group['distinct_state_counts_by_consumed_runes']
            axes[0].step(range(min(101, len(y))), y[:101], where='post',
                         label=f"Section {row['section']}, R={selected['reserved_label']} (all 29 seeds)", lw=2)
            y = selected['distinct_state_counts_by_consumed_runes']
            axes[0].step(range(min(101, len(y))), y[:101], where='post', ls='--',
                         label=f"Section {row['section']} (3 selected seeds)", lw=1.4)
    for row in control_rows:
        y = row['distinct_state_counts_by_consumed_runes']
        r, k = row['planted_pair']
        axes[1].step(range(101), y[:101], where='post', lw=1.5,
                     label=f"{row['source'].replace('_', ' ')}: R={frozen.LET[r]}, planted K={k}")
    for ax in axes:
        ax.set_xlim(0, 100)
        ax.set_ylim(.5, 30)
        ax.set_yticks([1, 3, 5, 10, 15, 20, 25, 29])
        ax.set_xlabel('Ciphertext runes consumed')
        ax.grid(alpha=.2)
        ax.legend(fontsize=8, loc='upper right')
    axes[0].set_ylabel('Distinct running states within a fixed R cohort')
    axes[0].set_title('Saved real candidates: state differences disappear')
    axes[1].set_title('Constructed controls: the same loss of initial state')
    fig.savefig(ROOT / 'plaintext_state_convergence.png', dpi=150)
    plt.close(fig)
    for name, digest in original_hashes.items():
        assert sha(ROOT / name) == digest, name
    print(json.dumps({'summary': summary,
                      'selected_real_merges': [r['selected_cohort']['merge_witness']
                                               for r in real_rows if r['selected_cohort']],
                      'control_merges': [{'source': r['source'], 'pair': r['planted_pair'],
                                          'after_runes': r['first_all_states_equal_after_runes']}
                                         for r in control_rows],
                      'earlier_evidence_unchanged': True}, indent=2), flush=True)


if __name__ == '__main__':
    main()
