"""Session 80: exact singleton screen for a two-predecessor product cipher.

Python + NumPy. Local retained sources; no network or external solver.
Positive unknown-key recovery gates precede the real coefficient screen.
"""
import hashlib
import itertools
import json

import numpy as np

from lp_core import ROOT, LET, lp, pages, vals
from word_core import FULL_MODEL, GROUPS, replace_values
from lexical_words import tokenize_words

B = 29
EXEMPT = {(6, 75), (54, 0)}


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


def feature_rows(cipher, field=B, initial=None):
    cipher = np.asarray(cipher, dtype=np.int64)
    if initial is None:
        current, u, v = cipher[2:], cipher[1:-1], cipher[:-2]
    else:
        newer, older = initial
        current = cipher
        u = np.r_[newer, cipher[:-1]]
        v = np.r_[older, newer, cipher[:-2]]
    return np.column_stack((current, u, v, u*v % field,
                            np.ones(len(current), dtype=np.int64))) % field


def encode(plain, coefficients, field=B, initial=(17, 9)):
    a, b, d, e, k = map(int, coefficients)
    assert 0 < a < field
    inverse = pow(a, -1, field)
    u, v = initial
    cipher = []
    for p in plain:
        current = (inverse * (int(p) - b*u - d*v - e*u*v - k)) % field
        cipher.append(current)
        u, v = current, u
    return np.array(cipher, dtype=np.int64)


def decode(cipher, coefficients, field=B, initial=None):
    return feature_rows(cipher, field, initial) @ np.asarray(coefficients, dtype=np.int64).T % field


def independent_rows(matrix, field):
    pivots, indices = {}, []
    for index, row in enumerate(matrix):
        vector = np.array(row, dtype=np.int64) % field
        for pivot in sorted(pivots):
            vector = (vector - int(vector[pivot]) * pivots[pivot]) % field
        nonzero = np.flatnonzero(vector)
        if len(nonzero):
            pivot = int(nonzero[0])
            pivots[pivot] = vector * pow(int(vector[pivot]), -1, field) % field
            indices.append(index)
        if len(indices) == matrix.shape[1]:
            break
    return indices


def inverse_matrix(matrix, field):
    matrix = np.asarray(matrix, dtype=np.int64)
    n = len(matrix)
    augmented = np.column_stack((matrix % field, np.eye(n, dtype=np.int64)))
    for col in range(n):
        pivot = next(row for row in range(col, n) if augmented[row, col] % field)
        augmented[[col, pivot]] = augmented[[pivot, col]]
        augmented[col] = augmented[col] * pow(int(augmented[col, col]), -1, field) % field
        for row in range(n):
            if row != col:
                augmented[row] = (augmented[row] - augmented[row, col] * augmented[col]) % field
    assert np.array_equal(augmented[:, :n], np.eye(n, dtype=np.int64))
    inverse = augmented[:, n:]
    assert np.array_equal(matrix @ inverse % field, np.eye(n, dtype=np.int64))
    return inverse


def solve_constraints(matrix, allowed, field=B):
    matrix = np.asarray(matrix, dtype=np.int64)
    basis = independent_rows(matrix, field)
    assert len(basis) == 5, f'Rank {len(basis)} is insufficient for this exact five-row method.'
    inverse = inverse_matrix(matrix[basis], field)
    assignments = np.array(list(itertools.product(sorted(allowed), repeat=5)), dtype=np.int64)
    coefficients = assignments @ inverse.T % field
    assert np.array_equal(coefficients @ matrix[basis].T % field, assignments)
    bijective = coefficients[:, 0] != 0
    valid = coefficients[bijective]
    predicted = valid @ matrix.T % field
    compatible = np.all(np.isin(predicted, sorted(allowed)), axis=1)
    alive = np.ones(len(valid), dtype=bool)
    steps = [{'added_constraint_index': None, 'remaining_keys': len(valid)}]
    added = []
    certificate = None
    for index in range(len(matrix)):
        if index in basis:
            continue
        alive &= np.isin(predicted[:, index], sorted(allowed))
        added.append(index)
        steps.append({'added_constraint_index': index, 'remaining_keys': int(alive.sum())})
        if not np.any(alive) and certificate is None:
            certificate = sorted(set(basis + added))
    assert np.array_equal(alive, compatible)
    return {'basis_constraint_indices': basis, 'basis_feature_rows': matrix[basis].tolist(),
            'basis_inverse_modulo_field': inverse.tolist(), 'basis_rank': len(basis),
            'assignment_count': len(assignments), 'a_zero_assignments_excluded': int((~bijective).sum()),
            'basis_compatible_bijective_keys': valid.tolist(),
            'decoded_values_at_all_constraints': predicted.tolist(),
            'all_constraint_compatible_keys': valid[compatible].tolist(),
            'compatible_key_count': int(compatible.sum()),
            'filter_steps': steps, 'contradiction_constraint_indices': certificate}


def exhaustive_checks():
    checks = 0
    for a in range(1, B):
        for bias in range(B):
            cipher = [(pow(a, -1, B) * (p-bias)) % B for p in range(B)]
            assert len(set(cipher)) == B
            assert [(a*c+bias) % B for c in cipher] == list(range(B))
            checks += B
    rng = np.random.default_rng(330180)
    rows = []
    for field, allowed in [(3, {0,1}), (5, {1,4}), (5, {0,2,4})]:
        for case in range(3):
            key = [int(rng.integers(1, field))] + rng.integers(0, field, 4).tolist()
            for attempt in range(64):
                plain = rng.choice(sorted(allowed), 20)
                cipher = encode(plain, key, field, (1,2))
                features = feature_rows(cipher, field)
                if len(independent_rows(features, field)) == 5:
                    break
            else:
                raise AssertionError('No full-rank small-field fixture.')
            result = solve_constraints(features, allowed, field)
            got = {tuple(v) for v in result['all_constraint_compatible_keys']}
            brute = set()
            for a in range(1, field):
                for other in itertools.product(range(field), repeat=4):
                    candidate = (a,) + other
                    # Independent scalar formula at each observed history.
                    values = [(a*int(cipher[i]) + other[0]*int(cipher[i-1])
                               + other[1]*int(cipher[i-2])
                               + other[2]*int(cipher[i-1])*int(cipher[i-2]) + other[3]) % field
                              for i in range(2, len(cipher))]
                    if all(p in allowed for p in values):
                        brute.add(candidate)
            assert got == brute and tuple(key) in got
            assert np.array_equal(decode(cipher, key, field, (1,2)), plain)
            rows.append({'field': field, 'allowed': sorted(allowed), 'case': case,
                         'brute_force_parameter_settings': (field-1)*field**4,
                         'rank_solver_matches_brute_force': True,
                         'compatible_keys': len(got), 'planted_key_included': True})
    return {'one_symbol_encoder_inverse_cases': checks, 'small_field_fixtures': rows}


def singleton_constraints(source, cipher, real=False, section=None, global_start=0, cut=None, words=None):
    words = tokenize_words(source) if words is None else words
    features = feature_rows(cipher)
    rows, records = [], []
    for word in words:
        local = word['rune_offset'] - global_start
        if len(word['values']) != 1 or local < 2 or (cut is not None and local >= cut):
            continue
        if real and (word['page'], word['page_rune_offset']) in EXEMPT:
            continue
        feature = features[local-2]
        records.append({'section': section, 'global_rune_offset': word['rune_offset'],
                        'local_rune_offset': local, 'lp2_page' if real else 'source_page': word['page'],
                        'page_rune_offset': word['page_rune_offset'], 'feature_row': feature.tolist()})
        rows.append(feature)
    return np.array(rows, dtype=np.int64).reshape((-1,5)), records


def control_sources():
    manifest = json.loads((ROOT/'increment_calibration_sources.json').read_text())
    known = {g['name']: g['values'] for g in manifest['groups']}
    welcome = replace_values('%'.join(pages[1:3]), known['welcome'])
    koan = replace_values('%'.join(pages[12:14]), known['second_koan'])
    assert 'welcome' not in GROUPS and 'second_koan' not in GROUPS
    return [('welcome_then_koan_twice', '%'.join([welcome, koan]*2)),
            ('koan_then_welcome_twice', '%'.join([koan, welcome]*2))]


def run_controls(plan):
    rows = []
    initial = (plan['controls']['initial_context']['U'], plan['controls']['initial_context']['V'])
    for name, source in control_sources():
        plain = vals(source)
        words = tokenize_words(source)
        assert len(plain) == 1668
        limit = min(768, int(.6*len(plain)))
        cut = max(w['rune_offset']+len(w['values']) for w in words
                  if w['rune_offset']+len(w['values']) <= limit)
        prefix_lengths = [len(w['values']) for w in words
                          if w['rune_offset']+len(w['values']) <= cut]
        for key in plan['controls']['planted_coefficients']:
            cipher = encode(plain, key, initial=initial)
            assert np.array_equal(decode(cipher, key, initial=initial), plain)
            rendered = replace_values(source, cipher)
            matrix, records = singleton_constraints(rendered, cipher, cut=cut)
            solved = solve_constraints(matrix, {24,10})
            candidates = solved['all_constraint_compatible_keys']
            assert candidates
            decoded = np.array([decode(cipher, k, initial=initial) for k in candidates])
            scores = FULL_MODEL.score(decoded[:, :cut], prefix_lengths)
            order = sorted(range(len(candidates)), key=lambda i: (-float(scores[i]), candidates[i]))
            selected = order[:3]
            planted = candidates.index(key)
            recovery = np.array_equal(decoded[planted], plain)
            gate = planted in selected and recovery
            row = {'source': name, 'runes': len(plain), 'prefix_runes': cut,
                   'prefix_singletons': len(records), 'planted_coefficients': key,
                   'ciphertext_values': cipher.tolist(), 'initial_context': list(initial),
                   'constraint_records': records, 'solver': solved,
                   'compatible_prefix_scores': scores.tolist(),
                   'planted_prefix_rank': order.index(planted)+1,
                   'selected_coefficient_vectors': [candidates[i] for i in selected],
                   'known_key_roundtrip_exact': True, 'retained_planted_full_plaintext_exact': recovery,
                   'gate_passed': gate}
            rows.append(row)
            print(json.dumps({'control': name, 'key': key, 'rank': row['planted_prefix_rank'],
                              'compatible_keys': len(candidates), 'gate': gate}), flush=True)
    assert len(rows) == 6
    return {'rows': rows, 'all_six_gates_passed': all(r['gate_passed'] for r in rows),
            'training_excludes_both_control_passages': True,
            'source_overlap_limit': 'Six encryptions reuse two passages in two composite orders, not six independent language samples.'}


def real_sections():
    source = '%'.join(lp[:56])
    words = tokenize_words(source)
    out, start = [], 0
    for section, piece in enumerate(source.split('$')):
        cipher = vals(piece)
        if len(cipher) > 100:
            target_words = [w for w in words if w['section'] == section]
            matrix, records = singleton_constraints(piece, cipher, True, section, start, words=target_words)
            out.append({'section': section, 'cipher': cipher, 'source': piece,
                        'global_start': start, 'matrix': matrix, 'records': records})
        start += len(cipher)
    assert [t['section'] for t in out] == [0,1,2,4,5,6,7,8]
    assert sum(len(t['cipher']) for t in out) == 12947
    assert sum(len(t['records']) for t in out) == 81
    return out


def phrase_constraints():
    stream = vals('%'.join(lp[:56]))
    anchors = []
    for start in (6555,12950):
        segment = stream[start-2:start+6]
        anchors.append({'global_rune_offset': start, 'previous_two_ciphertext_values': segment[:2].tolist(),
                        'ciphertext_values': segment[2:].tolist(),
                        'feature_rows': feature_rows(segment).tolist()})
    assert anchors[0]['ciphertext_values'] == anchors[1]['ciphertext_values'] == [23,11,1,17,18,10]
    difference = (np.array(anchors[0]['feature_rows']) - np.array(anchors[1]['feature_rows'])) % B
    assert difference[:2].tolist() == [[0,15,12,17,0],[0,0,15,26,0]]
    assert np.all(difference[2:] == 0)
    triples = []
    for b,d,e in itertools.product(range(B), repeat=3):
        permitted = (15*b + 12*d + 17*e) % B == 0 and (15*d + 26*e) % B == 0
        assert permitted == (b == 25*e % B and d == 6*e % B)
        if permitted:
            triples.append([b,d,e])
    assert len(triples) == B
    witness = [3,14,8,11,13]
    decoded = [(np.array(a['feature_rows']) @ witness % B).tolist() for a in anchors]
    assert decoded[0] == decoded[1]
    return {'role': 'Conditional equal-plaintext phrase constraint, separate from the primary singleton test.',
            'anchors': anchors, 'plaintext_difference_feature_rows': difference.tolist(),
            'equation_rank': len(independent_rows(difference, B)),
            'reduced_relations': ['b = 25*e (mod 29)', 'd = 6*e (mod 29)'],
            'all_24389_predecessor_coefficient_triples_checked': True,
            'allowed_b_d_e_triples': triples,
            'full_parameter_settings_if_all_six_plaintext_runes_match': 28*29**2,
            'different_context_equal_output_counterexample': {'coefficients': witness,
                                                             'decoded_rune_values_at_both_anchors': decoded[0],
                                                             'not_a_proposed_plaintext': True}}


def screen_real(phrase):
    targets = real_sections()
    fit = [t for t in targets if t['section'] in (0,1,2,4)]
    later = [t for t in targets if t['section'] in (5,6,7,8)]
    matrix = np.vstack([t['matrix'] for t in fit])
    records = [r for t in fit for r in t['records']]
    rows = {}
    for name, allowed in [('AI', {24,10}), ('AIO', {24,10,3})]:
        solved = solve_constraints(matrix, allowed)
        certificate = solved['contradiction_constraint_indices']
        if certificate is not None:
            assert not solve_constraints(matrix[certificate], allowed)['compatible_key_count']
        coefficients = solved['all_constraint_compatible_keys']
        evaluations = []
        for key in coefficients:
            outputs = [decode(t['cipher'], key) for t in later]
            violations = []
            for t, decoded in zip(later, outputs):
                for record in t['records']:
                    value = int(decoded[record['local_rune_offset']-2])
                    if value not in allowed:
                        violations.append({**record, 'decoded_value': value})
            evaluations.append({'coefficients': key, 'later_singleton_violations': violations,
                                'later_sections_decoded_values': [v.tolist() for v in outputs]})
        conditional_basis = [key for key in solved['basis_compatible_bijective_keys']
                             if key[1] == 25*key[3] % B and key[2] == 6*key[3] % B]
        rows[name] = {'solver': solved,
                      'basis_constraint_records': [records[i] for i in solved['basis_constraint_indices']],
                      'contradiction_constraint_records': [records[i] for i in certificate] if certificate else None,
                      'basis_compatible_keys_also_matching_phrase_plaintext': conditional_basis,
                      'later_evaluations_of_frozen_training_survivors': evaluations}
    return {'scope': 'One shared coefficient vector; the two initial ciphertext runes per section are context only.',
            'scored_runes_with_two_predecessors': sum(len(t['cipher'])-2 for t in targets),
            'fitting_singleton_records': records,
            'fitting_singletons': len(records), 'later_singletons': sum(len(t['records']) for t in later),
            'branches': rows,
            'limits': 'No independent section coefficients are fitted. All real text has been examined before.'}


def main():
    plan = json.loads((ROOT/'product_feedback_plan.json').read_text())
    assert sha(ROOT/'liber-primus__transcription--master.txt') == 'b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    checks = exhaustive_checks()
    phrase = phrase_constraints()
    controls = run_controls(plan)
    sources = ['product_feedback_plan.json', 'product_feedback_audit.py',
               'liber-primus__transcription--master.txt', 'increment_calibration_sources.json',
               'lp_core.py', 'word_core.py', 'lexical_words.py']
    control_payload = {'session': 80, 'exhaustive_checks': checks, 'controls': controls,
                       'source_hashes': {name: sha(ROOT/name) for name in sources}}
    control_path = ROOT/'product_feedback_controls.json'
    control_path.write_text(json.dumps(control_payload, indent=2) + '\n')
    control_hash = sha(control_path)
    if not controls['all_six_gates_passed']:
        raise RuntimeError('Control gate failed; real screen is not permitted.')
    real = screen_real(phrase)
    assert sha(control_path) == control_hash
    result = {'session': 80, 'full_shared_parameter_settings': 28*29**4,
              'control_file_sha256_before_real_run': control_hash, 'real_run_permitted': True,
              'conditional_phrase_constraints': phrase, 'real': real,
              'source_hashes': {**{name: sha(ROOT/name) for name in sources},
                                'product_feedback_controls.json': control_hash},
              'limits': plan['limits'], 'new_plaintext_established': False}
    (ROOT/'product_feedback_results.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps({'full_shared_parameter_settings': result['full_shared_parameter_settings'],
                      'conditional_same_phrase_parameter_settings': phrase['full_parameter_settings_if_all_six_plaintext_runes_match'],
                      'all_six_control_gates_pass': controls['all_six_gates_passed'],
                      'fitting_singletons': real['fitting_singletons'], 'later_singletons': real['later_singletons'],
                      'real_branches': {name: {'basis_rank': row['solver']['basis_rank'],
                                               'basis_assignments': row['solver']['assignment_count'],
                                               'bijective_basis_keys': len(row['solver']['basis_compatible_bijective_keys']),
                                               'fitting_compatible_keys': row['solver']['compatible_key_count'],
                                               'contradiction_words': len(row['contradiction_constraint_records'] or [])}
                                        for name,row in real['branches'].items()}}, indent=2), flush=True)


if __name__ == '__main__':
    main()
