"""Session 82: exact section-local quadratic capacity, including rank gaps.

Complete compact affine families over a prime field. No free coordinates are
selected using real plaintext scores. Earlier sources and results are read only.
"""
import itertools
import json

import numpy as np

import product_feedback_audit as p
import quadratic_feedback_audit as q
from lp_core import ROOT, vals
from word_core import FULL_MODEL
from lexical_words import tokenize_words

DIM = 7


def affine_basis(matrix, field):
    """Return independent rows, a RHS-to-particular map and nullspace basis."""
    matrix = np.asarray(matrix, dtype=np.int64).reshape((-1, DIM)) % field
    indices = p.independent_rows(matrix, field)
    rank = len(indices)
    reduced = matrix[indices].copy()
    transform = np.eye(rank, dtype=np.int64)
    pivots = []
    row = 0
    for col in range(DIM):
        choices = np.flatnonzero(reduced[row:, col])
        if not len(choices):
            continue
        pivot = row + int(choices[0])
        reduced[[row, pivot]] = reduced[[pivot, row]]
        transform[[row, pivot]] = transform[[pivot, row]]
        inverse = pow(int(reduced[row, col]), -1, field)
        reduced[row] = reduced[row] * inverse % field
        transform[row] = transform[row] * inverse % field
        for other in range(rank):
            if other != row:
                factor = int(reduced[other, col])
                reduced[other] = (reduced[other] - factor*reduced[row]) % field
                transform[other] = (transform[other] - factor*transform[row]) % field
        pivots.append(col)
        row += 1
        if row == rank:
            break
    assert len(pivots) == rank
    assert np.array_equal(transform @ matrix[indices] % field, reduced)
    particular_map = np.zeros((DIM, rank), dtype=np.int64)
    particular_map[pivots] = transform
    free = [i for i in range(DIM) if i not in pivots]
    nullspace = np.zeros((len(free), DIM), dtype=np.int64)
    for i, col in enumerate(free):
        nullspace[i, col] = 1
        nullspace[i, pivots] = -reduced[:, col] % field
    assert np.all(matrix @ nullspace.T % field == 0)
    assert np.array_equal(matrix[indices] @ particular_map % field,
                          np.eye(rank, dtype=np.int64))
    return indices, pivots, free, particular_map, nullspace


def solve(matrix, allowed, field=29):
    matrix = np.asarray(matrix, dtype=np.int64).reshape((-1, DIM)) % field
    basis, pivots, free, mapping, nullspace = affine_basis(matrix, field)
    rank, dimension = len(basis), len(free)
    assignments = np.array(list(itertools.product(sorted(allowed), repeat=rank)),
                           dtype=np.int64).reshape((-1, rank)) if rank else np.empty((1, 0), dtype=np.int64)
    particulars = assignments @ mapping.T % field
    predicted = particulars @ matrix.T % field
    assert np.array_equal(predicted[:, basis], assignments)
    a_free = bool(np.any(nullspace[:, 0]))
    if a_free:
        counts = np.full(len(particulars), (field-1)*field**(dimension-1), dtype=np.int64)
    else:
        counts = (particulars[:, 0] != 0).astype(np.int64)*field**dimension
    alive = counts != 0
    steps = [{'added_constraint_index': None, 'remaining_keys': int(counts[alive].sum()),
              'remaining_output_assignments': int(alive.sum())}]
    added, certificate = [], None
    for i in range(len(matrix)):
        if i in basis:
            continue
        alive &= np.isin(predicted[:, i], sorted(allowed))
        added.append(i)
        steps.append({'added_constraint_index': i, 'remaining_keys': int(counts[alive].sum()),
                      'remaining_output_assignments': int(alive.sum())})
        if not np.any(alive) and certificate is None:
            certificate = sorted(set(basis+added))
    complete = (counts != 0) & np.all(np.isin(predicted, sorted(allowed)), axis=1)
    assert np.array_equal(alive, complete)
    if not np.any(alive) and certificate is None:
        certificate = basis
    families = [{'basis_outputs': assignments[i].tolist(),
                 'particular_coefficients': particulars[i].tolist(),
                 'bijective_key_count': int(counts[i]),
                 'decoded_values_at_all_constraints': predicted[i].tolist()}
                for i in np.flatnonzero(alive)]
    return {'field': field, 'allowed_values': sorted(allowed), 'basis_rank': rank,
            'basis_constraint_indices': basis, 'basis_feature_rows': matrix[basis].tolist(),
            'pivot_coefficient_columns': pivots, 'free_coefficient_columns': free,
            'particular_map': mapping.tolist(), 'nullspace_basis': nullspace.tolist(),
            'nullspace_dimension': dimension, 'a_varies_with_free_coordinates': a_free,
            'all_basis_output_assignments': assignments.tolist(),
            'all_basis_particular_coefficients': particulars.tolist(),
            'bijective_key_counts_per_basis_assignment': counts.tolist(),
            'all_basis_decoded_constraint_values': predicted.tolist(),
            'basis_assignment_count': len(assignments),
            'compatible_output_assignment_count': len(families),
            'compatible_key_count': int(counts[alive].sum()),
            'compatible_affine_families': families, 'filter_steps': steps,
            'contradiction_constraint_indices': certificate,
            'family_interpretation': 'key = particular + z @ nullspace_basis modulo field; arbitrary free vector z, subject to key[0] != 0. The particular vector is not necessarily bijective or a selected key.'}


def expand(result):
    """For small test fields only; never enumerate rank-gap real keys."""
    field = result['field']
    dimension = result['nullspace_dimension']
    nullspace = np.array(result['nullspace_basis'], dtype=np.int64).reshape((dimension, DIM))
    free = np.array(list(itertools.product(range(field), repeat=dimension)),
                    dtype=np.int64).reshape((-1, dimension)) if dimension else np.empty((1, 0), dtype=np.int64)
    out = set()
    for family in result['compatible_affine_families']:
        keys = (np.array(family['particular_coefficients']) + free @ nullspace) % field
        out.update(tuple(map(int, key)) for key in keys if key[0])
    return out


def includes(result, key):
    field = result['field']
    nullspace = np.array(result['nullspace_basis'], dtype=np.int64).reshape((-1, DIM))
    z = np.array(key, dtype=np.int64)[result['free_coefficient_columns']]
    return bool(key[0]) and any(np.array_equal(
        (np.array(f['particular_coefficients']) + z @ nullspace) % field, key)
        for f in result['compatible_affine_families'])


def toy_checks(seed):
    rng = np.random.default_rng(seed)
    checks = []
    for field, allowed in [(3, {0, 1}), (5, {1, 4})]:
        keys = np.array([(a,)+rest for a in range(1, field)
                         for rest in itertools.product(range(field), repeat=6)], dtype=np.int64)
        cipher = rng.integers(0, field, 160)
        features = q.feature_rows(cipher, field)
        independent = p.independent_rows(features, field)
        assert len(independent) == DIM
        scalar_features = np.array([[int(cipher[i]), int(cipher[i-1]), int(cipher[i-2]),
                                     int(cipher[i-1])*int(cipher[i-2]) % field,
                                     int(cipher[i-1])**2 % field, int(cipher[i-2])**2 % field, 1]
                                    for i in range(2, len(cipher))])
        assert np.array_equal(features, scalar_features)
        fixtures = []
        for rank in range(8):
            basis = features[independent[:rank]]
            matrix = basis.copy()
            if rank:
                matrix = np.vstack((matrix, basis[0], basis[-1],
                                    np.sum(basis, axis=0) % field, 2*basis[0] % field))
            fixtures.append((f'rank_{rank}_dependent_rows', matrix, allowed, rank))
        fixtures.append(('inconsistent_zero_row', np.zeros((1, DIM), dtype=np.int64), {1}, 0))
        a_row = np.zeros((1, DIM), dtype=np.int64)
        a_row[0, 0] = 1
        fixtures.append(('forces_nonbijective_a_zero', a_row, {0}, 1))
        for name, matrix, values, rank in fixtures:
            result = solve(matrix, values, field)
            got = expand(result)
            # Direct enumeration of every admissible key. No modular elimination,
            # basis assignment, free-variable map or counting formula is reused.
            alive = np.ones(len(keys), dtype=bool)
            for row in matrix:
                decoded = sum(int(row[j])*keys[:, j] for j in range(DIM)) % field
                alive &= np.isin(decoded, sorted(values))
            expected = {tuple(map(int, k)) for k in keys[alive]}
            assert got == expected and len(got) == result['compatible_key_count']
            assert result['basis_rank'] == rank
            assert all(includes(result, list(k)) for k in list(expected)[:10])
            checks.append({'field': field, 'fixture': name, 'rank': rank,
                           'constraints': len(matrix), 'enumerated_bijective_keys': len(keys),
                           'compatible_key_count': len(expected), 'exact_set_and_count_match': True})
    assert len(checks) == 20
    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']:
        source = sources[control['source']]
        plain = vals(source)
        cipher = np.array(control['ciphertext_values'], dtype=np.int64)
        records = control['constraint_records']
        matrix = np.array([r['feature_row'] for r in records], dtype=np.int64)
        solved = solve(matrix, {10, 24})
        keys = sorted(expand(solved))
        previous_keys = sorted(tuple(k) for k in control['solver']['all_constraint_compatible_keys'])
        assert keys == previous_keys
        decoded = np.array([q.decode(cipher, k, initial=control['initial_context']) for k in keys])
        cut = control['prefix_runes']
        lengths = [len(w['values']) for w in tokenize_words(source)
                   if w['rune_offset'] + len(w['values']) <= cut]
        scores = FULL_MODEL.score(decoded[:, :cut], lengths)
        order = sorted(range(len(keys)), key=lambda i: (-float(scores[i]), keys[i]))
        planted = tuple(control['planted_coefficients'])
        index = keys.index(planted)
        assert order.index(index) == 0 and np.array_equal(decoded[index], plain)
        assert np.array_equal(q.encode(plain, planted, initial=control['initial_context']), cipher)
        reduced_matrix = matrix[p.independent_rows(matrix, 29)[:5]]
        reduced = solve(reduced_matrix, {10, 24})
        assert reduced['basis_rank'] == 5 and reduced['nullspace_dimension'] == 2
        assert includes(reduced, list(planted))
        # Unique free coordinates reconstruct each planted key exactly.
        assert reduced['compatible_key_count'] > 1
        rows.append({'source': control['source'], 'planted_coefficients': list(planted),
                     'full_rank_key_set_matches_81': True, 'compatible_full_rank_keys': [list(k) for k in keys],
                     'planted_prefix_rank': order.index(index)+1, 'exact_full_message_recovery': True,
                     'rank_five_planted_key_included': True, 'rank_five_solver': reduced,
                     'gate_passed': True})
    assert len(rows) == 6
    return {'rows': rows, 'all_six_gates_passed': True,
            'limit': 'Same six prior encodings of two composite known passages. Rank-five inclusion validates representation of unidentified keys, not unknown-key selection or new language samples.'}


def screen_real(plan):
    out = []
    for target, inventory in zip(p.real_sections(), plan['design_inventory_before_coefficient_screen']):
        matrix = q.feature_rows(target['cipher'])[[r['local_rune_offset']-2 for r in target['records']]]
        records = [{**record, 'feature_row': row.tolist()}
                   for record, row in zip(target['records'], matrix)]
        rank = len(p.independent_rows(matrix, 29))
        assert (target['section'], len(matrix), rank) == (inventory['section'], inventory['singletons'], inventory['rank'])
        branches = {}
        for name, allowed in plan['allowed_words'].items():
            solved = solve(matrix, set(allowed))
            certificate = solved['contradiction_constraint_indices']
            if certificate is not None:
                assert solve(matrix[certificate], set(allowed))['compatible_key_count'] == 0
            if rank == 7:
                old = q.solve(matrix, set(allowed))
                assert expand(solved) == {tuple(k) for k in old['all_constraint_compatible_keys']}
            branches[name] = {'solver': solved,
                              'contradiction_records': [records[i] for i in certificate] if certificate is not None else None}
        row = {'section': target['section'], 'global_start': target['global_start'],
               'runes': len(target['cipher']), 'decoded_positions': len(target['cipher'])-2,
               'singleton_count': len(matrix), 'rank': rank, 'constraint_records': records,
               'feature_rows': matrix.tolist(), 'branches': branches}
        out.append(row)
        print(json.dumps({'section': row['section'], 'rank': rank,
                          'compatible_keys': {k: v['solver']['compatible_key_count'] for k, v in branches.items()}}), flush=True)
    rejected = {name: [r['section'] for r in out if r['branches'][name]['solver']['compatible_key_count'] == 0]
                for name in plan['allowed_words']}
    return {'sections': out, 'rejected_sections': rejected,
            'all_sections_joint_model_has_any_key': {name: not sections for name, sections in rejected.items()},
            'decoded_positions': sum(r['decoded_positions'] for r in out),
            'singleton_count': sum(r['singleton_count'] for r in out),
            'no_real_language_selection_or_continuation_performed': True}


def main():
    plan = json.loads((ROOT/'section_quadratic_plan.json').read_text())
    assert p.sha(ROOT/'liber-primus__transcription--master.txt') == plan['source_policy']['master_sha256']
    sources = ['section_quadratic_plan.json', 'section_quadratic_audit.py',
               'quadratic_feedback_audit.py', 'quadratic_feedback_controls.json',
               'product_feedback_audit.py', 'liber-primus__transcription--master.txt',
               'increment_calibration_sources.json', '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()
    payload = {'session': 82, 'toy_checks': checks, 'controls': controls, 'source_hashes': hashes}
    path = ROOT/'section_quadratic_controls.json'
    path.write_text(json.dumps(payload, indent=2)+'\n')
    control_hash = p.sha(path)
    if not controls['all_six_gates_passed'] or not all(c['exact_set_and_count_match'] for c in checks):
        raise RuntimeError('Control gates failed; real screen is not permitted.')
    result = {'session': 82, 'control_sha256_before_real_screen': control_hash,
              'real_run_permitted': True, 'real': screen_real(plan),
              'source_hashes': {**hashes, path.name: control_hash},
              'limits': plan['limits'], 'new_plaintext_established': False}
    assert p.sha(path) == control_hash
    assert all(p.sha(ROOT/name) == value for name, value in hashes.items())
    (ROOT/'section_quadratic_results.json').write_text(json.dumps(result, indent=2)+'\n')
    print(json.dumps({'toy_checks': len(checks), 'all_six_controls_pass': True,
                      'rejected_sections': result['real']['rejected_sections'],
                      'all_sections_joint_model_has_any_key': result['real']['all_sections_joint_model_has_any_key']}, indent=2), flush=True)


if __name__ == '__main__':
    main()
