"""Session 83: complete singleton deletion sensitivity through two per section.

Earlier source, alphabet, history and cipher rules remain unchanged. Deleting a
constraint never deletes ciphertext. No language score chooses real exceptions.
"""
import itertools
import json

import numpy as np

import section_quadratic_audit as base
import quadratic_feedback_audit as q
import product_feedback_audit as p
from lp_core import ROOT, vals


def compact(solved):
    fields = ('field', 'allowed_values', 'basis_rank', 'basis_constraint_indices',
              'basis_feature_rows', 'pivot_coefficient_columns', 'free_coefficient_columns',
              'particular_map', 'nullspace_basis', 'nullspace_dimension',
              'a_varies_with_free_coordinates', 'compatible_output_assignment_count',
              'compatible_key_count', 'compatible_affine_families', 'family_interpretation')
    return {name: solved[name] for name in fields}


def search(matrix, allowed, budget=2, field=29, all_levels=False):
    """Inspect every deletion set at each level; keep all first-level families."""
    matrix = np.asarray(matrix, dtype=np.int64).reshape((-1, 7))
    nodes, levels, minimum_witnesses = [], [], []
    minimum = None
    for level in range(min(budget, len(matrix))+1):
        start = len(nodes)
        feasible = 0
        witnesses = []
        for omitted in itertools.combinations(range(len(matrix)), level):
            kept = [i for i in range(len(matrix)) if i not in omitted]
            solved = base.solve(matrix[kept], allowed, field)
            count = solved['compatible_key_count']
            node = {'omitted_constraint_indices': list(omitted),
                    'retained_constraint_indices': kept,
                    'retained_rank': solved['basis_rank'], 'compatible_key_count': count}
            nodes.append(node)
            if count:
                feasible += 1
                if minimum is None:
                    witnesses.append({**node, 'solver': compact(solved)})
        levels.append({'omitted_word_count': level, 'deletion_sets_tested': len(nodes)-start,
                       'feasible_deletion_sets': feasible})
        if minimum is None and feasible:
            minimum = level
            minimum_witnesses = witnesses
        if minimum is not None and not all_levels:
            break
    lower = minimum if minimum is not None else budget+1
    return {'budget': budget, 'minimum_exceptions': minimum, 'minimum_exceptions_lower_bound': lower,
            'minimum_is_exact': minimum is not None,
            'levels': levels, 'inspected_deletion_sets': nodes,
            'minimum_level_witnesses': minimum_witnesses,
            'unique_minimum_exception_compatible_keys': sum(w['compatible_key_count'] for w in minimum_witnesses),
            'count_limit': 'Sum is over disjoint sets at the minimum level only. Larger-budget deletion counts overlap and are not summed.'}


def toy_checks(seed):
    rng = np.random.default_rng(seed)
    checks = []
    for field, allowed in [(3, {1, 2}), (5, {1, 4})]:
        keys = np.array([(a,)+other for a in range(1, field)
                         for other in itertools.product(range(field), repeat=6)], dtype=np.int64)
        planted = [int(rng.integers(1, field))]+rng.integers(0, field, 6).tolist()
        for attempt in range(64):
            cipher = rng.integers(0, field, 320)
            features = q.feature_rows(cipher, field)
            plain = q.decode(cipher, planted, field)
            eligible = features[np.isin(plain, sorted(allowed))]
            independent = p.independent_rows(eligible, field)
            if len(independent) == 7:
                break
        else:
            raise AssertionError('No rank-seven planted fixture.')
        for rank in (0, 3, 5, 7):
            ordinary = eligible[independent[:rank]]
            if rank:
                ordinary = np.vstack((ordinary, ordinary[0], ordinary[-1]))
            for errors in range(4):
                # A zero feature row is an impossible ordinary-word constraint
                # when zero is excluded, regardless of coefficients. This is a
                # generic algebra fixture, not a claimed rune context.
                matrix = np.vstack((ordinary, np.zeros((errors, 7), dtype=np.int64)))
                got = search(matrix, allowed, 2, field)
                violations = np.zeros((len(keys), len(matrix)), dtype=bool)
                for i, row in enumerate(matrix):
                    direct = sum(int(row[j])*keys[:, j] for j in range(7)) % field
                    violations[:, i] = ~np.isin(direct, sorted(allowed))
                counts = violations.sum(axis=1)
                expected_minimum = int(counts.min())
                assert expected_minimum == errors
                assert got['minimum_exceptions'] == (errors if errors <= 2 else None)
                assert got['minimum_exceptions_lower_bound'] == errors
                for node in got['inspected_deletion_sets']:
                    kept = node['retained_constraint_indices']
                    expected_count = int(np.count_nonzero(~np.any(violations[:, kept], axis=1)))
                    assert node['compatible_key_count'] == expected_count
                expanded = set()
                for witness in got['minimum_level_witnesses']:
                    current = base.expand(witness['solver'])
                    assert not expanded.intersection(current)
                    expanded.update(current)
                expected = {tuple(map(int, k)) for k in keys[counts == errors]} if errors <= 2 else set()
                assert expanded == expected
                assert got['unique_minimum_exception_compatible_keys'] == len(expected)
                if errors <= 2:
                    assert tuple(planted) in expanded
                checks.append({'field': field, 'rank': rank, 'injected_impossible_rows': errors,
                               'constraints': len(matrix), 'enumerated_bijective_keys': len(keys),
                               'subset_counts_checked': len(got['inspected_deletion_sets']),
                               'minimum_exceptions': got['minimum_exceptions'],
                               'minimum_exceptions_lower_bound': got['minimum_exceptions_lower_bound'],
                               'minimum_compatible_keys': len(expected),
                               'exact_subsets_minimum_and_set_match': True})
    assert len(checks) == 32
    return checks


def control_checks():
    old = json.loads((ROOT/'quadratic_feedback_controls.json').read_text())
    sources = dict(p.control_sources())
    rows = []
    for control in old['controls']['rows']:
        plain = vals(sources[control['source']])
        cipher = np.array(control['ciphertext_values'], dtype=np.int64)
        matrix = np.array([r['feature_row'] for r in control['constraint_records']], dtype=np.int64)
        existing = {r['local_rune_offset'] for r in control['constraint_records']}
        bad_positions = [i for i in range(2, control['prefix_runes'])
                         if int(plain[i]) not in (10, 24) and i not in existing][:2]
        features = q.feature_rows(cipher)
        for errors in (1, 2):
            full_matrix = np.vstack((matrix, features[np.array(bad_positions[:errors])-2]))
            found = search(full_matrix, {10, 24}, errors, all_levels=True)
            omitted = list(range(len(matrix), len(full_matrix)))
            node = next(n for n in found['inspected_deletion_sets']
                        if n['omitted_constraint_indices'] == omitted)
            restored = base.solve(full_matrix[node['retained_constraint_indices']], {10, 24})
            planted = control['planted_coefficients']
            assert base.includes(restored, planted)
            assert np.array_equal(q.decode(cipher, planted, initial=control['initial_context']), plain)
            assert np.array_equal(q.encode(plain, planted, initial=control['initial_context']), cipher)
            assert restored['compatible_key_count'] == control['solver']['compatible_key_count']
            assert found['minimum_exceptions'] is not None and found['minimum_exceptions'] <= errors
            rows.append({'source': control['source'], 'planted_coefficients': planted,
                         'false_claim_rune_offsets': bad_positions[:errors],
                         'known_plaintext_at_false_claims': [int(plain[i]) for i in bad_positions[:errors]],
                         'false_claim_count': errors, 'budget': errors,
                         'minimum_found': found['minimum_exceptions'],
                         'deletion_sets_tested': len(found['inspected_deletion_sets']),
                         'correct_false_claim_mask': omitted,
                         'correct_mask_compatible_keys': node['compatible_key_count'],
                         'planted_included_at_correct_mask': True,
                         'known_planted_full_message_recovers_exactly': True,
                         'all_subset_counts': found['inspected_deletion_sets'], 'gate_passed': True})
    assert len(rows) == 12
    return {'rows': rows, 'all_twelve_gates_passed': True,
            'limit': 'Twelve false-claim fixtures reuse six prior encryptions of two composite known messages. Known-planted recovery validates inclusion; no score chooses an exception mask.'}


def real_screen(plan):
    prior = json.loads((ROOT/'section_quadratic_results.json').read_text())
    out = []
    for section in prior['real']['sections']:
        matrix = np.array(section['feature_rows'], dtype=np.int64)
        branches = {}
        for name, allowed in plan['branches'].items():
            found = search(matrix, set(allowed), plan['maximum_additional_word_exceptions_per_section'])
            assert found['inspected_deletion_sets'][0]['compatible_key_count'] == section['branches'][name]['solver']['compatible_key_count']
            for witness in found['minimum_level_witnesses']:
                witness['omitted_word_records'] = [section['constraint_records'][i]
                                                    for i in witness['omitted_constraint_indices']]
            branches[name] = found
        out.append({'section': section['section'], 'runes': section['runes'],
                    'singleton_count': section['singleton_count'], 'constraint_records': section['constraint_records'],
                    'feature_rows': section['feature_rows'], 'branches': branches})
        print(json.dumps({'section': section['section'],
                          'minimum_exceptions': {name: found['minimum_exceptions'] for name, found in branches.items()},
                          'lower_bounds': {name: found['minimum_exceptions_lower_bound'] for name, found in branches.items()}}), flush=True)
    aggregate = {}
    for name in plan['branches']:
        aggregate[name] = {'total_exception_lower_bound': sum(s['branches'][name]['minimum_exceptions_lower_bound'] for s in out),
                           'total_minimum_is_exact': all(s['branches'][name]['minimum_is_exact'] for s in out),
                           'sections_failing_two_exception_budget': [s['section'] for s in out if not s['branches'][name]['minimum_is_exact']]}
    return {'sections': out, 'aggregate': aggregate, 'real_candidate_selection_performed': False,
            'new_word_exemptions_adopted': False, 'master_edited': False}


def main():
    plan = json.loads((ROOT/'quadratic_exception_plan.json').read_text())
    assert plan['maximum_additional_word_exceptions_per_section'] == 2
    assert p.sha(ROOT/'liber-primus__transcription--master.txt') == 'b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    sources = ['quadratic_exception_plan.json', 'quadratic_exception_audit.py',
               'section_quadratic_plan.json', 'section_quadratic_audit.py', 'section_quadratic_results.json',
               'quadratic_feedback_audit.py', 'quadratic_feedback_controls.json',
               'product_feedback_audit.py', 'increment_calibration_sources.json',
               'liber-primus__transcription--master.txt', 'lp_core.py', 'word_core.py', 'lexical_words.py']
    hashes = {name: p.sha(ROOT/name) for name in sources}
    checks = toy_checks(plan['controls']['seed'])
    controls = control_checks()
    control_path = ROOT/'quadratic_exception_controls.json'
    control_path.write_text(json.dumps({'session': 83, 'toy_checks': checks, 'controls': controls,
                                       'source_hashes': hashes}, indent=2)+'\n')
    control_hash = p.sha(control_path)
    if not controls['all_twelve_gates_passed'] or not all(c['exact_subsets_minimum_and_set_match'] for c in checks):
        raise RuntimeError('Control gates failed; real sensitivity screen not permitted.')
    real = real_screen(plan)
    assert p.sha(control_path) == control_hash
    assert all(p.sha(ROOT/name) == value for name, value in hashes.items())
    result = {'session': 83, 'real_run_permitted': True,
              'control_sha256_before_real_search': control_hash, 'real': real,
              'source_hashes': {**hashes, control_path.name: control_hash},
              'limits': plan['limits'], 'new_plaintext_established': False}
    (ROOT/'quadratic_exception_results.json').write_text(json.dumps(result, indent=2)+'\n')
    print(json.dumps({'toy_checks': len(checks), 'control_gates': len(controls['rows']),
                      'aggregate': real['aggregate']}, indent=2), flush=True)


if __name__ == '__main__':
    main()
