"""Session 86: solved mechanisms and exact known-key selective-F alignment.

All earlier evidence is read only. Full plaintext is hashed, not republished.
The word screen is a necessary condition, not an unknown-key language decoder.
"""
import hashlib
import itertools
import json
from collections import Counter

import numpy as np

import product_feedback_audit as previous
from lp_core import ROOT, R, pages, lp, SEQS
from lexical_words import tokenize_words


def hash_values(values):
    return hashlib.sha256(bytes(map(int, values))).hexdigest()


def trial_primes(count):
    out, candidate = [], 2
    while len(out) < count:
        prime = True
        for p in out:
            if p*p > candidate:
                break
            if candidate % p == 0:
                prime = False
                break
        if prime:
            out.append(candidate)
        candidate += 1
    return out


def known_recipes(plan):
    reference = json.loads((ROOT/'increment_calibration_sources.json').read_text())
    groups = {g['name']: g['values'] for g in reference['groups']}
    records, streams = [], {}
    for recipe in plan['recipes']:
        source = '%'.join(pages[i] for i in recipe['parsed_pages'])
        cipher = [R.index(ch) for ch in source if ch in R]
        plaintext, encoded, phases = [], [], []
        skip = set(recipe.get('skip_offsets', []))
        prime = trial_primes(len(cipher))
        cursor = 0
        for i, current in enumerate(cipher):
            method = recipe['method']
            if method == 'direct':
                value, inverse = current, current
            elif method == 'reflection':
                value = (recipe['constant']-current) % 29
                inverse = (recipe['constant']-value) % 29
            elif method in ('repeating_key', 'prime_minus_one'):
                phases.append(cursor % len(recipe['key']) if method == 'repeating_key' else cursor)
                if i in skip:
                    assert current == 0
                    value, inverse = 0, 0
                else:
                    key = recipe['key'][cursor % len(recipe['key'])] if method == 'repeating_key' else prime[cursor]-1
                    value = (current-key) % 29
                    inverse = (value+key) % 29
                    cursor += 1
            else:
                raise ValueError(method)
            plaintext.append(value)
            encoded.append(inverse)
        assert plaintext == groups[recipe['name']]
        assert encoded == cipher
        streams[recipe['name']] = {'source': source, 'cipher': cipher, 'plaintext': plaintext}
        records.append({**recipe, 'runes': len(cipher), 'parsed_text_pages': len(recipe['parsed_pages']),
                        'ciphertext_values_sha256': hash_values(cipher),
                        'literal_plaintext_values_sha256': hash_values(plaintext),
                        'literal_reference_match': True, 'exact_scalar_inverse_reencryption': True,
                        'ciphertext_F_count': cipher.count(0),
                        'documented_unenciphered_F_count': len(skip),
                        'consumed_key_elements': cursor if recipe['method'] in ('repeating_key','prime_minus_one') else None,
                        'key_phase_at_each_rune': phases if phases else None,
                        'initial_state': 0 if recipe['method'] == 'repeating_key' else None,
                        'boundary_policy': 'Continuous across listed pages; punctuation consumes nothing.'})
    assert sum(r['runes'] for r in records) == 2977
    assert sum(r['parsed_text_pages'] for r in records) == 17
    return records, streams


def exact_paths(cipher, key, start, allowed_by_position, field=29, checkpoints=True, repeating=True):
    """All F subsets, merged by periodic phase or absolute finite-stream index."""
    states = {start: 1}
    events = []
    for offset, current in enumerate(map(int, cipher)):
        incoming = states
        states = Counter()
        allowed = allowed_by_position.get(offset)
        for phase, multiplicity in incoming.items():
            assert 0 <= phase < len(key), 'Insufficient finite stream; never silently prune.'
            value = (current-key[phase]) % field
            if allowed is None or value in allowed:
                states[(phase+1) % len(key) if repeating else phase+1] += multiplicity
            if current == 0 and (allowed is None or 0 in allowed):
                states[phase] += multiplicity
        if checkpoints and allowed is not None:
            events.append({'rune_offset': offset, 'allowed_values': sorted(allowed),
                           'incoming_phase_counts_decimal': {str(k):str(v) for k,v in sorted(incoming.items())},
                           'outgoing_phase_counts_decimal': {str(k):str(v) for k,v in sorted(states.items())}})
        if not states:
            return {'initial_state': start, 'first_failure_rune_offset': offset,
                    'compatible_path_count_decimal': '0', 'end_state_counts_decimal': {},
                    'distinct_end_states': 0, 'counter_is_periodic': repeating, 'checkpoints': events}
    return {'initial_state': start, 'first_failure_rune_offset': None,
            'compatible_path_count_decimal': str(sum(states.values())),
            'end_state_counts_decimal': {str(k):str(v) for k,v in sorted(states.items())},
            'distinct_end_states': len(states), 'counter_is_periodic': repeating, 'checkpoints': events}


def brute_paths(cipher, key, start, allowed_by_position, field, repeating=True):
    positions = [i for i, c in enumerate(cipher) if c == 0]
    counts = Counter()
    for decisions in itertools.product((False, True), repeat=len(positions)):
        skipped = {i for i, flag in zip(positions, decisions) if flag}
        cursor = start
        valid = True
        for i, current in enumerate(map(int, cipher)):
            if i in skipped:
                decoded = 0
            else:
                decoded = (current-key[cursor % len(key) if repeating else cursor]) % field
                cursor += 1
            if i in allowed_by_position and decoded not in allowed_by_position[i]:
                valid = False
                break
        if valid:
            counts[cursor % len(key) if repeating else cursor] += 1
    return {str(k):str(v) for k,v in sorted(counts.items())}, 2**len(positions)


def toy_controls():
    rng = np.random.default_rng(330185)
    rows = []
    for field, allowed in [(3, {0,1}), (5, {1,4})]:
      for repeating in (True, False):
        for case in range(8):
            size = 10+case % 3
            cipher = rng.integers(0, field, size).tolist()
            for i in range(0, size, 3):
                cipher[i] = 0
            if case == 0:
                cipher = [1 if c == 0 else c for c in cipher]
            if case == 1:
                cipher[3:6] = [0,0,0]
            if case == 2:
                cipher[0] = cipher[-1] = 0
            if case == 3:
                cipher[1] = 0
            key = rng.integers(0, field, 2+case % 3 if repeating else size+3).tolist()
            constraints = {i: allowed for i in range(1, size, 3)}
            if case == 6:
                constraints[5] = set()
            phase_rows = []
            for phase in range(len(key) if repeating else 3):
                got = exact_paths(cipher, key, phase, constraints, field, repeating=repeating)
                expected, subsets = brute_paths(cipher, key, phase, constraints, field, repeating=repeating)
                assert got['end_state_counts_decimal'] == expected
                assert int(got['compatible_path_count_decimal']) == sum(map(int,expected.values()))
                # The first reported contradiction is verified on that prefix.
                if got['first_failure_rune_offset'] is not None:
                    stop = got['first_failure_rune_offset']
                    prefix_counts, _ = brute_paths(cipher[:stop+1], key, phase,
                                                   {i:v for i,v in constraints.items() if i <= stop}, field, repeating=repeating)
                    assert not prefix_counts
                phase_rows.append({'phase': phase, 'brute_subsets': subsets,
                                   'compatible_paths_decimal': got['compatible_path_count_decimal'],
                                   'exact_end_state_count_match': True})
            rows.append({'field':field, 'case':case, 'counter_is_periodic':repeating, 'runes':size, 'key':key, 'cipher':cipher,
                         'constraint_offsets':list(constraints), 'phases':phase_rows})
    assert len(rows) == 32
    return rows


def known_skip_controls(plan, streams):
    controls = []
    for recipe in plan['recipes']:
        if recipe['method'] not in ('repeating_key','prime_minus_one'):
            continue
        stream = streams[recipe['name']]
        repeating = recipe['method'] == 'repeating_key'
        key = recipe['key'] if repeating else [(p-1)%29 for p in trial_primes(len(stream['cipher'])+1)]
        full_constraints = {i:{p} for i,p in enumerate(stream['plaintext'])}
        full = exact_paths(stream['cipher'], key, 0, full_constraints, checkpoints=False, repeating=repeating)
        assert int(full['compatible_path_count_decimal']) > 0
        # Independently check that the documented skip mask is a live path,
        # although the automaton did not receive this mask as a fitting input.
        cursor = 0
        skip = set(recipe['skip_offsets'])
        for i, current in enumerate(stream['cipher']):
            value = 0 if i in skip else (current-key[cursor % len(key) if repeating else cursor]) % 29
            if i not in skip:
                cursor += 1
            assert value == stream['plaintext'][i]
        words = tokenize_words(stream['source'])
        singleton_positions = [w['rune_offset'] for w in words if len(w['values']) == 1]
        assert all(stream['plaintext'][i] in (10,24) for i in singleton_positions)
        membership = exact_paths(stream['cipher'], key, 0,
                                 {i:{10,24} for i in singleton_positions}, repeating=repeating)
        assert int(membership['compatible_path_count_decimal']) > 0
        controls.append({'name':recipe['name'], 'runes':len(stream['cipher']),
                         'documented_skip_mask_is_valid':True, 'full_known_plaintext_path':full,
                         'singleton_count':len(singleton_positions), 'ordinary_AI_screen':membership,
                         'known_skip_mask_not_given_to_automaton':True,
                         'limit':'Full-reference matching verifies path availability and arithmetic; it does not claim unknown plaintext recovery from the singleton screen.'})
    assert len(controls) == 3
    return controls


def real_screen(plan):
    keys = [r for r in plan['recipes'] if r['method'] == 'repeating_key']
    targets = previous.real_sections()
    prime_key = [(p-1)%29 for p in trial_primes(max(len(t['cipher']) for t in targets)+33)]
    assert prime_key == list(map(int, SEQS['prime_minus_one'][:len(prime_key)]))
    schedules = keys + [{'name':'prime_minus_one','key':prime_key}]
    all_words = tokenize_words('%'.join(lp[:56]))
    red = {(6,75),(54,0)}
    singleton_total = 0
    rows = []
    for target in targets:
        words = {w['rune_offset']-target['global_start']:
                 {'section':target['section'],'global_rune_offset':w['rune_offset'],
                  'local_rune_offset':w['rune_offset']-target['global_start'],
                  'lp2_page':w['page'],'page_rune_offset':w['page_rune_offset']}
                 for w in all_words if w['section']==target['section'] and len(w['values'])==1}
        singleton_total += len(words)
        for recipe in schedules:
            key = recipe['key']
            repeating = recipe['name'] != 'prime_minus_one'
            starts = range(len(key)) if repeating else range(33)
            branches = {}
            variants = [('AI_all_singletons',{10,24},False),('AIO_all_singletons',{3,10,24},False),
                        ('AI_prior_red_exemptions',{10,24},True),('AIO_prior_red_exemptions',{3,10,24},True)]
            for name, allowed, omit_red in variants:
                active = {i:r for i,r in words.items() if not(omit_red and (r['lp2_page'],r['page_rune_offset']) in red)}
                phases = [exact_paths(target['cipher'], key, phase, {i:allowed for i in active}, repeating=repeating)
                          for phase in starts]
                valid = [p['initial_state'] for p in phases if int(p['compatible_path_count_decimal'])]
                impossible = []
                for offset, record in active.items() if repeating else []:
                    current = int(target['cipher'][offset])
                    possible = {(current-int(k)) % 29 for k in key}
                    if current == 0:
                        possible.add(0)
                    if not possible.intersection(allowed):
                        impossible.append({**{k:v for k,v in record.items() if k != 'feature_row'},
                                           'ciphertext_value': current,
                                           'possible_plaintext_values_under_any_phase':sorted(possible)})
                if impossible:
                    assert not valid
                branches[name] = {'initial_state_results':phases, 'compatible_initial_states':valid,
                                  'active_singletons':len(active),
                                  'phase_independent_impossible_word_count':len(impossible) if repeating else None,
                                  'all_phase_independent_word_witnesses':impossible}
            if not repeating:
                weak = branches['AIO_prior_red_exemptions']
                if not weak['compatible_initial_states']:
                    cutoff = max(p['first_failure_rune_offset'] for p in weak['initial_state_results'])
                    certificate = {i:{3,10,24} for i,r in words.items()
                                   if i <= cutoff and (r['lp2_page'],r['page_rune_offset']) not in red}
                    assert all(exact_paths(target['cipher'],key,start,certificate,repeating=False,
                                           checkpoints=False)['compatible_path_count_decimal']=='0' for start in range(33))
                    weak['prefix_word_certificate'] = [words[i] for i in certificate]
                    weak['all_33_offsets_fail_on_certificate_alone'] = True
            for prefix in ('AI','AIO'):
                strict = branches[prefix+'_all_singletons']['compatible_initial_states']
                loose = branches[prefix+'_prior_red_exemptions']['compatible_initial_states']
                assert set(strict).issubset(loose)
            rows.append({'section':target['section'], 'runes':len(target['cipher']),
                         'global_start':target['global_start'],'singleton_records':list(words.values()),
                         'singleton_count':len(words), 'literal_key_name':recipe['name'],
                         'key':key if repeating else None, 'counter_is_periodic':repeating,
                         'branches':branches})
        print(json.dumps({'section':target['section'], 'compatible_phases':{
            r['literal_key_name']:{name:b['compatible_initial_states'] for name,b in r['branches'].items()}
            for r in rows[-3:]} }),flush=True)
    assert singleton_total == 83
    return {'rows':rows, 'known_literal_keys_tested':2, 'prime_offsets':list(range(33)),
            'prime_stream_length':len(prime_key),'prime_stream_values_sha256':hash_values(prime_key),
            'section_key_cases':len(rows), 'all_singletons':83,'prior_red_exemption_singletons':81,
            'initial_state_branch_cases':sum((len(r['key']) if r['counter_is_periodic'] else 33)*len(r['branches']) for r in rows),
            'new_real_plaintext_selected':False}


def main():
    plan = json.loads((ROOT/'solved_mechanism_plan.json').read_text())
    assert previous.sha(ROOT/'liber-primus__transcription--master.txt') == 'b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    coverage_files = sorted({name for row in plan['coverage_audit'] for name in row['files']})
    sources = list(dict.fromkeys(['solved_mechanism_plan.json','solved_mechanism_audit.py',
               'liber-primus__transcription--master.txt','increment_calibration_sources.json',
               'increment_calibration_plan.json','lp_core.py','product_feedback_audit.py','lexical_words.py',
               'selective_F_feasibility_plan.json','mechanism_coverage_results.json','SESSION_85.md']+coverage_files))
    hashes = {name:previous.sha(ROOT/name) for name in sources}
    records, streams = known_recipes(plan)
    toy = toy_controls()
    known = known_skip_controls(plan, streams)
    control_payload = {'session':86, 'solved_mechanism_ledger':records, 'toy_controls':toy,
                       'known_advancing_key_controls':known, 'all_gates_passed':True,
                       'coverage_audit':plan['coverage_audit'], 'source_review':plan['source_review'],
                       'source_hashes':hashes}
    control_path = ROOT/'solved_mechanism_controls.json'
    control_path.write_text(json.dumps(control_payload,indent=2)+'\n')
    control_hash = previous.sha(control_path)
    real = real_screen(plan)
    assert previous.sha(control_path) == control_hash
    assert all(previous.sha(ROOT/name) == digest for name,digest in hashes.items())
    result = {'session':86, 'control_sha256_before_real_screen':control_hash,
              'real_run_permitted':True, 'real':real,
              'source_hashes':{**hashes,control_path.name:control_hash}, 'limits':plan['limits'],
              'new_plaintext_established':False}
    (ROOT/'solved_mechanism_results.json').write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps({'solved_groups_reproduced':len(records), 'solved_text_pages':17,
                      'literal_runes':sum(r['runes'] for r in records), 'toy_fixtures':len(toy),
                      'toy_phase_checks':sum(len(r['phases']) for r in toy),
                      'initial_state_branch_cases':real['initial_state_branch_cases'],
                      'compatible_section_key_cases':{name:sum(bool(r['branches'][name]['compatible_initial_states']) for r in real['rows']) for name in ('AI_all_singletons','AIO_all_singletons','AI_prior_red_exemptions','AIO_prior_red_exemptions')}},indent=2),flush=True)


if __name__ == '__main__':
    main()
