"""Session 81: full-domain quadratic two-predecessor polynomial screen.

Python + NumPy, retained local sources. Earlier evidence is read, never rewritten.
Unknown-key control gates and their saved hashes precede real coefficient tests.
"""
import itertools
import json
from collections import Counter

import numpy as np

import product_feedback_audit as previous
from lp_core import ROOT, vals
from word_core import FULL_MODEL, replace_values
from lexical_words import tokenize_words

B = 29
DIM = 7
sha = previous.sha


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,u*u % field,v*v % field,
                            np.ones(len(current), dtype=np.int64))) % field


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


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


def solve(matrix, allowed, field=B):
    matrix = np.asarray(matrix,dtype=np.int64)
    basis = previous.independent_rows(matrix,field)
    assert len(basis) == DIM, f'Rank {len(basis)} is insufficient for the seven-row method.'
    inverse = previous.inverse_matrix(matrix[basis],field)
    assignments = np.array(list(itertools.product(sorted(allowed),repeat=DIM)),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 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(alive.sum())})
        if not np.any(alive) and certificate is None:
            certificate = sorted(set(basis+added))
    assert np.array_equal(alive,compatible)
    return {'basis_rank':len(basis),'basis_constraint_indices':basis,
            'basis_feature_rows':matrix[basis].tolist(),
            'basis_inverse_modulo_field':inverse.tolist(),'assignment_count':len(assignments),
            'a_zero_assignments_excluded':int((~bijective).sum()),
            'basis_compatible_bijective_keys':valid.tolist(),
            'decoded_values_at_all_constraints':predicted.tolist(),
            'compatible_key_count':int(compatible.sum()),
            'all_constraint_compatible_keys':valid[compatible].tolist(),
            'filter_steps':steps,'contradiction_constraint_indices':certificate}


def classification_checks():
    c = np.arange(B,dtype=np.int64)
    quadratic_images = Counter()
    for h in range(1,B):
        for a in range(B):
            size = len(set(map(int,(h*c*c+a*c) % B)))
            quadratic_images[size] += 1
            assert size == 15
    u,v = np.meshgrid(c,c,indexing='ij')
    zero_counts = Counter()
    valid = []
    for a,l,m in itertools.product(range(B),repeat=3):
        zeros = int(np.count_nonzero((a+l*u+m*v) % B == 0))
        zero_counts[zeros] += 1
        assert (zeros == 0) == (a != 0 and l == 0 and m == 0)
        if zeros == 0:
            valid.append([a,l,m])
    assert len(valid) == 28
    symbol_cases = 0
    for a in range(1,B):
        for bias in range(B):
            emitted = (pow(a,-1,B)*(c-bias)) % B
            assert len(set(map(int,emitted))) == B
            assert np.array_equal((a*emitted+bias) % B,c)
            symbol_cases += B
    return {'current_quadratic_rows_checked':28*29,
            'current_quadratic_image_size_counts':dict(sorted(quadratic_images.items())),
            'affine_current_multiplier_rules_checked':29**3,
            'contexts_per_multiplier_rule':29**2,
            'zero_context_count_distribution':dict(sorted(zero_counts.items())),
            'multipliers_nonzero_in_every_context':valid,
            'seven_coefficient_classification_verified':True,
            'one_symbol_encoder_inverse_cases':symbol_cases,
            'domain_limit':'Classification assumes all 29 symbols at all 29^2 histories.'}


def small_field_checks():
    rng = np.random.default_rng(330181)
    out = []
    for field,allowed in [(3,{0,1}),(5,{1,4}),(5,{0,2,4})]:
        brute_keys = np.array([(a,)+other for a in range(1,field)
                               for other in itertools.product(range(field),repeat=6)],dtype=np.int64)
        for case in range(3):
            key = [int(rng.integers(1,field))]+rng.integers(0,field,6).tolist()
            for attempt in range(64):
                cipher = rng.integers(0,field,160)
                plain = []
                u,v = 1,2
                a,b,d,e,f,g,k = key
                for current in cipher:
                    plain.append((a*int(current)+b*u+d*v+e*u*v+f*u*u+g*v*v+k) % field)
                    u,v = int(current),u
                positions = [i for i in range(2,len(cipher)) if plain[i] in allowed]
                matrix = feature_rows(cipher,field)[np.array(positions)-2]
                if len(previous.independent_rows(matrix,field)) == DIM:
                    break
            else:
                raise AssertionError('No full-rank small-field fixture.')
            got = {tuple(k) for k in solve(matrix,allowed,field)['all_constraint_compatible_keys']}
            # Complete parameter enumeration with an independent direct scalar formula,
            # vectorized over keys, and no reuse of the feature-row implementation.
            alive = np.ones(len(brute_keys),dtype=bool)
            for i in positions:
                current,u,v = map(int,(cipher[i],cipher[i-1],cipher[i-2]))
                decoded = (brute_keys[:,0]*current+brute_keys[:,1]*u+brute_keys[:,2]*v
                           +brute_keys[:,3]*u*v+brute_keys[:,4]*u*u
                           +brute_keys[:,5]*v*v+brute_keys[:,6]) % field
                alive &= np.isin(decoded,sorted(allowed))
            brute = {tuple(k) for k in brute_keys[alive]}
            assert got == brute and tuple(key) in got
            assert np.array_equal(decode(cipher,key,field,(1,2)),plain)
            assert np.array_equal(encode(plain,key,field,(1,2)),cipher)
            out.append({'field':field,'allowed':sorted(allowed),'case':case,
                        'constraint_rows':len(positions),'basis_rank':DIM,
                        'brute_force_parameter_settings':len(brute_keys),
                        'rank_solver_matches_brute_force':True,'compatible_keys':len(got),
                        'planted_key_included':True,'full_roundtrip_exact':True})
    assert len(out) == 9
    return out


def singleton_rows(source,cipher,cut=None):
    _,records = previous.singleton_constraints(source,cipher,cut=cut)
    features = feature_rows(cipher)
    rows = []
    for record in records:
        row = features[record['local_rune_offset']-2]
        record['feature_row'] = row.tolist()
        rows.append(row)
    return np.array(rows,dtype=np.int64).reshape((-1,DIM)),records


def run_controls(plan):
    initial = (plan['controls']['initial_context']['U'],plan['controls']['initial_context']['V'])
    rows = []
    for name,source in previous.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)
        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)
            source_cipher = replace_values(source,cipher)
            matrix,records = singleton_rows(source_cipher,cipher,cut)
            solved = solve(matrix,{24,10})
            keys = solved['all_constraint_compatible_keys']
            assert keys
            decoded = np.array([decode(cipher,k,initial=initial) for k in keys])
            scores = FULL_MODEL.score(decoded[:,:cut],lengths)
            order = sorted(range(len(keys)),key=lambda i:(-float(scores[i]),keys[i]))
            planted = keys.index(key)
            chosen = order[:3]
            full_recovery = np.array_equal(decoded[planted],plain)
            gate = planted in chosen and full_recovery
            rows.append({'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':[keys[i] for i in chosen],
                         'known_key_roundtrip_exact':True,
                         'retained_planted_full_plaintext_exact':full_recovery,'gate_passed':gate})
            print(json.dumps({'control':name,'key':key,'prefix_rank':order.index(planted)+1,
                              'compatible_keys':len(keys),'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':'Same two known passages in two repeated composite orders; six encryptions are not six independent language samples.'}


def phrase_constraints():
    old = previous.phrase_constraints()
    anchors = []
    for a in old['anchors']:
        segment = a['previous_two_ciphertext_values']+a['ciphertext_values']
        anchors.append({**a,'feature_rows':feature_rows(segment).tolist()})
    differences = (np.array(anchors[0]['feature_rows'])-np.array(anchors[1]['feature_rows'])) % B
    assert differences[:2].tolist() == [[0,15,12,17,7,3,0],[0,0,15,26,0,7,0]]
    assert np.all(differences[2:] == 0)
    pivot = differences[:2,1:3]
    inverse = previous.inverse_matrix(pivot,B)
    free = np.array(list(itertools.product(range(B),repeat=3)),dtype=np.int64)
    fixed = ((-free @ differences[:2,3:6].T) @ inverse.T) % B
    assert np.array_equal(fixed[:,0],(25*free[:,0]+15*free[:,1]+11*free[:,2]) % B)
    assert np.array_equal(fixed[:,1],(6*free[:,0]+15*free[:,2]) % B)
    assert np.all((fixed @ pivot.T+free @ differences[:2,3:6].T) % B == 0)
    witness = [3,1,10,11,2,4,13]
    outputs = [(np.array(a['feature_rows']) @ witness % B).tolist() for a in anchors]
    assert outputs[0] == outputs[1]
    return {'role':'Conditional full phrase plaintext equality; not imposed on primary singleton screen.',
            'anchors':anchors,'plaintext_difference_feature_rows':differences.tolist(),
            'equation_rank':len(previous.independent_rows(differences,B)),
            'b_d_pivot_inverse':inverse.tolist(),'free_e_f_g_triples_checked':len(free),
            'reduced_relations':['b = 25*e + 15*f + 11*g (mod 29)','d = 6*e + 15*g (mod 29)'],
            'full_parameter_settings_if_all_six_plaintext_runes_match':28*29**4,
            'different_context_equal_output_counterexample':{'coefficients':witness,
                                                             'decoded_rune_values_at_both_anchors':outputs[0],
                                                             'not_a_proposed_plaintext':True}}


def phrase_match(key):
    a,b,d,e,f,g,k = key
    return b == (25*e+15*f+11*g) % B and d == (6*e+15*g) % B


def real_screen():
    targets = previous.real_sections()
    for target in targets:
        features = feature_rows(target['cipher'])
        target['matrix'] = np.array([features[r['local_rune_offset']-2] for r in target['records']],dtype=np.int64)
        for record,row in zip(target['records'],target['matrix']):
            record['feature_row'] = row.tolist()
    fitting = [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 fitting])
    records = [r for t in fitting for r in t['records']]
    assert len(records) == 41 and sum(len(t['records']) for t in later) == 40
    branches = {}
    for name,allowed in [('AI',{24,10}),('AIO',{24,10,3})]:
        solved = solve(matrix,allowed)
        certificate = solved['contradiction_constraint_indices']
        if certificate is not None:
            assert solve(matrix[certificate],allowed)['compatible_key_count'] == 0
        conditional = [k for k in solved['basis_compatible_bijective_keys'] if phrase_match(k)]
        conditional_final = [k for k in solved['all_constraint_compatible_keys'] if phrase_match(k)]
        evaluations = []
        for key in solved['all_constraint_compatible_keys']:
            decoded = [decode(t['cipher'],key) for t in later]
            violations = []
            for t,p in zip(later,decoded):
                for r in t['records']:
                    value = int(p[r['local_rune_offset']-2])
                    if value not in allowed:
                        violations.append({**r,'decoded_value':value})
            evaluations.append({'coefficients':key,'later_singleton_violations':violations,
                                'later_sections_decoded_values':[p.tolist() for p in decoded]})
        branches[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,
                          'all_fitting_words_and_equal_phrase_compatible_keys':conditional_final,
                          'later_evaluations_of_frozen_training_survivors':evaluations}
    return {'scored_runes_with_two_predecessors':sum(len(t['cipher'])-2 for t in targets),
            'fitting_singletons':41,'later_singletons':40,'fitting_singleton_records':records,
            'branches':branches,'scope':'One shared coefficient vector; no section-specific refitting.',
            'limits':'All real text has been inspected previously; ordinary singleton meanings are conditional.'}


def main():
    plan = json.loads((ROOT/'quadratic_feedback_plan.json').read_text())
    assert plan['parameters']['full_shared_settings'] == 28*29**6
    assert sha(ROOT/'liber-primus__transcription--master.txt') == 'b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    checks = {'classification':classification_checks(),'small_field_fixtures':small_field_checks()}
    phrase = phrase_constraints()
    controls = run_controls(plan)
    sources = ['quadratic_feedback_plan.json','quadratic_feedback_audit.py','product_feedback_audit.py',
               'product_feedback_plan.json','liber-primus__transcription--master.txt',
               'increment_calibration_sources.json','lp_core.py','word_core.py','lexical_words.py']
    control_payload = {'session':81,'checks':checks,'controls':controls,
                       'source_hashes':{name:sha(ROOT/name) for name in sources}}
    control_path = ROOT/'quadratic_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 coefficient screen is not permitted.')
    real = real_screen()
    assert sha(control_path) == control_hash
    result = {'session':81,'full_shared_parameter_settings':28*29**6,
              '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},
                               'quadratic_feedback_controls.json':control_hash},
              'limits':plan['limits'],'new_plaintext_established':False}
    (ROOT/'quadratic_feedback_results.json').write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps({'full_shared_parameter_settings':result['full_shared_parameter_settings'],
                      'all_six_controls_pass':controls['all_six_gates_passed'],
                      '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 []),
                                             'equal_phrase_basis_keys':len(row['basis_compatible_keys_also_matching_phrase_plaintext'])}
                                       for name,row in real['branches'].items()}},indent=2),flush=True)


if __name__ == '__main__':
    main()
