"""Session 84: exact bounded exception costs under frozen circular shifts.

Counts, never selected keys. Cached bases are recomputed for each retained subset.
The unrotated and planted gates precede every rotated real coefficient screen.
"""
import itertools
import json
from collections import Counter
from functools import lru_cache

import numpy as np

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


@lru_cache(maxsize=None)
def assignments(allowed, rank):
    return np.array(list(itertools.product(allowed, repeat=rank)), dtype=np.int64).reshape((-1, rank)) if rank else np.empty((1, 0), dtype=np.int64)


class CapacityOracle:
    """Cache complete affine-basis counts and violations, not one fitted basis."""
    def __init__(self, matrix, field=29):
        self.matrix = np.asarray(matrix, dtype=np.int64).reshape((-1, 7)) % field
        self.field = field
        self.rows = len(self.matrix)
        self.full_mask = (1 << self.rows)-1
        self.subsets = {}
        self.maps = {}
        self.predictions = {}

    def count(self, omitted, allowed):
        allowed = tuple(sorted(allowed))
        kept_mask = self.full_mask ^ sum(1 << i for i in omitted)
        if kept_mask not in self.subsets:
            kept = [i for i in range(self.rows) if kept_mask & (1 << i)]
            local_basis = p.independent_rows(self.matrix[kept], self.field)
            basis = tuple(kept[i] for i in local_basis)
            self.subsets[kept_mask] = basis
        basis = self.subsets[kept_mask]
        if basis not in self.maps:
            _, _, free, mapping, nullspace = base.affine_basis(self.matrix[list(basis)], self.field)
            self.maps[basis] = (free, mapping, nullspace)
        key = (basis, allowed)
        if key not in self.predictions:
            free, mapping, nullspace = self.maps[basis]
            particular = assignments(allowed, len(basis)) @ mapping.T % self.field
            if np.any(nullspace[:, 0]):
                weights = np.full(len(particular), (self.field-1)*self.field**(len(free)-1), dtype=np.int64)
            else:
                weights = (particular[:, 0] != 0).astype(np.int64)*self.field**len(free)
            predicted = particular @ self.matrix.T % self.field
            bad = ~np.isin(predicted, allowed)
            powers = np.array([1 << i for i in range(self.rows)], dtype=np.uint64)
            bits = bad.astype(np.uint64) @ powers
            self.predictions[key] = (bits, weights)
        bits, weights = self.predictions[key]
        return int(weights[(bits & np.uint64(kept_mask)) == 0].sum())

    def search(self, allowed, budget=2, all_levels=False):
        levels = []
        minimum, minimum_keys, minimum_masks = None, 0, 0
        for level in range(min(budget, self.rows)+1):
            counts = [self.count(mask, allowed) for mask in itertools.combinations(range(self.rows), level)]
            feasible = sum(c != 0 for c in counts)
            levels.append({'omitted_word_count': level,
                           'compatible_counts_in_lexicographic_mask_order': counts,
                           'deletion_sets_tested': len(counts), 'feasible_deletion_sets': feasible})
            if feasible and minimum is None:
                minimum, minimum_keys, minimum_masks = level, sum(counts), feasible
            if minimum is not None and not all_levels:
                break
        return {'minimum_exceptions': minimum, 'minimum_is_exact': minimum is not None,
                'capped_cost': minimum if minimum is not None else budget+1,
                'unique_minimum_compatible_keys': minimum_keys,
                'minimum_feasible_masks': minimum_masks,
                'levels': levels, 'deletion_sets_tested': sum(x['deletion_sets_tested'] for x in levels)}


def cyclic_codes(cipher, field=29):
    cipher = np.asarray(cipher, dtype=np.int64)
    return cipher + field*np.roll(cipher, 1) + field*field*np.roll(cipher, 2)


def structural_checks():
    rng = np.random.default_rng(3301841)
    cases = 0
    for field, length in [(3, 12), (29, 37)]:
        cipher = rng.integers(0, field, length)
        inventory = np.bincount(cipher, minlength=field)
        contexts = np.bincount(cyclic_codes(cipher, field), minlength=field**3)
        for shift in range(1, length):
            moved = np.roll(cipher, shift)
            assert np.array_equal(np.roll(moved, -shift), cipher)
            assert np.array_equal(np.bincount(moved, minlength=field), inventory)
            assert np.array_equal(np.bincount(cyclic_codes(moved, field), minlength=field**3), contexts)
            direct = np.array([[int(moved[i]), int(moved[i-1]), int(moved[i-2]),
                                int(moved[i-1])*int(moved[i-2]) % field,
                                int(moved[i-1])**2 % field, int(moved[i-2])**2 % field, 1]
                               for i in range(2, length)])
            assert np.array_equal(q.feature_rows(moved, field), direct)
            original_codes = cyclic_codes(cipher, field)
            omissions = [(-shift) % length, (1-shift) % length]
            retained_codes = np.delete(original_codes, omissions)
            assert Counter(map(int, retained_codes)) == Counter(map(int, cyclic_codes(moved, field)[2:]))
            cases += 1
    return {'toy_rotations_checked': cases, 'inventory_context_inverse_and_edge_checks_pass': True}


def toy_checks():
    rng = np.random.default_rng(3301842)
    out = []
    for field, allowed in [(3, {0, 1}), (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)
        for attempt in range(64):
            candidate = rng.integers(0, field, (20, 7))
            rows = p.independent_rows(candidate, field)
            if len(rows) == 7:
                break
        else:
            raise AssertionError('No full-rank toy matrix.')
        independent = candidate[rows]
        for rank in range(8):
            matrix = independent[:rank].copy()
            if rank:
                matrix = np.vstack((matrix, matrix[0], np.sum(matrix, axis=0) % field))
            matrix = np.vstack((matrix, np.zeros((1, 7), dtype=np.int64)))
            oracle = CapacityOracle(matrix, field)
            found = oracle.search(allowed, 2, all_levels=True)
            # Independent full enumeration, with no basis, inverse, cache,
            # nullspace representation or affine-count formula.
            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))
            minimum = int(violations.sum(axis=1).min())
            tested = 0
            for level in found['levels']:
                for mask, count in zip(itertools.combinations(range(len(matrix)), level['omitted_word_count']),
                                       level['compatible_counts_in_lexicographic_mask_order']):
                    kept = [i for i in range(len(matrix)) if i not in mask]
                    direct_count = int(np.count_nonzero(~np.any(violations[:, kept], axis=1)))
                    assert count == direct_count
                    tested += 1
            assert found['minimum_exceptions'] == (minimum if minimum <= 2 else None)
            if minimum <= 2:
                assert found['unique_minimum_compatible_keys'] == int(np.count_nonzero(violations.sum(axis=1) == minimum))
            out.append({'field': field, 'rank': rank, 'enumerated_bijective_vectors': len(keys),
                        'subset_counts_checked': tested, 'exact_counts_and_minimum_match': True})
    assert len(out) == 16
    return out


def regression_checks(prior):
    checks = 0
    costs = {name: 0 for name in ('AI', 'AIO')}
    for section in prior['real']['sections']:
        oracle = CapacityOracle(section['feature_rows'])
        for name, branch in section['branches'].items():
            allowed = {10, 24} if name == 'AI' else {3, 10, 24}
            found = oracle.search(allowed)
            old_counts = [n['compatible_key_count'] for n in branch['inspected_deletion_sets']]
            new_counts = [v for level in found['levels'] for v in level['compatible_counts_in_lexicographic_mask_order']]
            assert old_counts == new_counts
            assert found['minimum_exceptions'] == branch['minimum_exceptions']
            assert found['unique_minimum_compatible_keys'] == branch['unique_minimum_exception_compatible_keys']
            costs[name] += found['capped_cost']
            checks += len(new_counts)
    assert checks == 744 and costs == {'AI': 12, 'AIO': 7}
    return {'all_saved_unrotated_subset_counts_match': checks, 'observed_capped_cost': costs}


def message_controls():
    prefix = json.loads((ROOT/'quadratic_feedback_controls.json').read_text())
    old_controls = json.loads((ROOT/'quadratic_exception_controls.json').read_text())['controls']['rows']
    source = dict(p.control_sources())
    checked, rows = 0, []
    for control in old_controls:
        original = next(c for c in prefix['controls']['rows']
                        if c['source'] == control['source'] and c['planted_coefficients'] == control['planted_coefficients'])
        cipher = np.array(original['ciphertext_values'], dtype=np.int64)
        plain = vals(source[control['source']])
        matrix = np.array([r['feature_row'] for r in original['constraint_records']], dtype=np.int64)
        extra = q.feature_rows(cipher)[np.array(control['false_claim_rune_offsets'])-2]
        oracle = CapacityOracle(np.vstack((matrix, extra)))
        found = oracle.search({10, 24}, control['budget'], all_levels=True)
        got = [v for level in found['levels'] for v in level['compatible_counts_in_lexicographic_mask_order']]
        expected = [n['compatible_key_count'] for n in control['all_subset_counts']]
        assert got == expected and found['minimum_exceptions'] == control['minimum_found']
        planted = control['planted_coefficients']
        direct_retained = matrix @ np.array(planted) % 29
        assert np.all(np.isin(direct_retained, [10, 24]))
        assert oracle.count(control['correct_false_claim_mask'], {10, 24}) == control['correct_mask_compatible_keys']
        assert np.array_equal(q.decode(cipher, planted, initial=original['initial_context']), plain)
        checked += len(got)
        rows.append({'source': control['source'], 'planted_coefficients': planted,
                     'false_claims': control['false_claim_count'], 'minimum': found['minimum_exceptions'],
                     'subset_counts_match': len(got), 'planted_available_and_full_recovery_exact': True})
    assert len(rows) == 12 and checked == 630
    return {'rows': rows, 'all_twelve_gates_pass': True, 'subset_counts_match': checked,
            'limit': 'Reuse twelve false-claim fixtures of six encryptions, not new independent language samples.'}


def rotation_screen(plan, schedule, targets, prior):
    records = {s['section']: s['constraint_records'] for s in prior['real']['sections']}
    rows = []
    cohort_costs = {name: [0]*plan['rotations_per_section'] for name in plan['branches']}
    total_subsets = 0
    for target, shifts in zip(targets, schedule['sections']):
        assert target['section'] == shifts['section']
        cipher = target['cipher']
        n = len(cipher)
        positions = np.array([r['local_rune_offset'] for r in records[target['section']]])
        inventory = np.bincount(cipher, minlength=29)
        circular = np.bincount(cyclic_codes(cipher), minlength=29**3)
        baseline_linear_repeats = int(np.count_nonzero(cipher[1:] == cipher[:-1]))
        moved_rows = []
        for cohort, shift in enumerate(shifts['shifts']):
            moved = np.roll(cipher, shift)
            assert np.array_equal(np.bincount(moved, minlength=29), inventory)
            assert np.array_equal(np.bincount(cyclic_codes(moved), minlength=29**3), circular)
            matrix = q.feature_rows(moved)[positions-2]
            oracle = CapacityOracle(matrix)
            branches = {}
            for name, allowed in plan['branches'].items():
                found = oracle.search(set(allowed), plan['exception_budget_per_section'])
                cohort_costs[name][cohort] += found['capped_cost']
                total_subsets += found['deletion_sets_tested']
                branches[name] = found
            linear_repeats = int(np.count_nonzero(moved[1:] == moved[:-1]))
            assert abs(linear_repeats-baseline_linear_repeats) <= 1
            moved_rows.append({'cohort': cohort, 'right_shift': shift,
                               'omitted_original_circular_context_positions': [(-shift) % n, (1-shift) % n],
                               'linear_neighbor_repeats': linear_repeats,
                               'feature_rows_at_fixed_singletons': matrix.tolist(), 'branches': branches})
        rows.append({'section': target['section'], 'runes': n, 'singleton_count': len(positions),
                     'singleton_coordinates': [{k: v for k, v in r.items() if k != 'feature_row'} for r in records[target['section']]],
                     'baseline_linear_neighbor_repeats': baseline_linear_repeats,
                     'all_rotations_preserve_inventory_and_circular_contexts': True,
                     'rotations': moved_rows})
        print(json.dumps({'section': target['section'], 'rotations_completed': len(moved_rows),
                          'cost_distributions': {name: dict(sorted(Counter(r['branches'][name]['capped_cost'] for r in moved_rows).items())) for name in plan['branches']}}), flush=True)
    summary = {}
    for name, values in cohort_costs.items():
        observed = prior['real']['aggregate'][name]['total_exception_lower_bound']
        lower = sum(v < observed for v in values)
        equal = values.count(observed)
        greater = sum(v > observed for v in values)
        summary[name] = {'observed_capped_cost': observed, 'rotation_cohort_costs': values,
                         'cohort_cost_distribution': dict(sorted(Counter(values).items())),
                         'minimum_control_cost': min(values), 'maximum_control_cost': max(values),
                         'mean_control_cost': float(np.mean(values)),
                         'controls_lower_than_observed': lower, 'controls_equal_to_observed': equal,
                         'controls_greater_than_observed': greater,
                         'equal_or_lower_empirical_fraction': (lower+equal)/len(values),
                         'formal_p_value_reported': False}
    return {'sections': rows, 'summary': summary, 'total_subset_counts': total_subsets,
            'total_section_rotations': sum(len(s['rotations']) for s in rows),
            'no_real_key_selection_or_source_changes': True}


def main():
    plan = json.loads((ROOT/'quadratic_alignment_plan.json').read_text())
    assert plan['rotations_per_section'] == 99 and plan['exception_budget_per_section'] == 2
    assert p.sha(ROOT/'liber-primus__transcription--master.txt') == 'b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    prior = json.loads((ROOT/'quadratic_exception_results.json').read_text())
    targets = p.real_sections()
    rng = np.random.default_rng(plan['seed'])
    schedule = {'session': 84, 'seed': plan['seed'], 'right_rotation': True,
                'sections': [{'section': t['section'], 'runes': len(t['cipher']),
                              'shifts': rng.choice(np.arange(1, len(t['cipher'])), plan['rotations_per_section'], replace=False).tolist()}
                             for t in targets]}
    schedule_path = ROOT/'quadratic_alignment_shifts.json'
    schedule_path.write_text(json.dumps(schedule, indent=2)+'\n')
    sources = ['quadratic_alignment_plan.json', 'quadratic_alignment_audit.py', schedule_path.name,
               'quadratic_exception_results.json', 'quadratic_exception_controls.json', 'quadratic_exception_audit.py',
               'section_quadratic_audit.py', '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}
    gates = {'structure': structural_checks(), 'toy_enumeration': toy_checks(),
             'unrotated_regression': regression_checks(prior), 'known_message_controls': message_controls()}
    control_path = ROOT/'quadratic_alignment_controls.json'
    control_path.write_text(json.dumps({'session': 84, 'gates': gates, 'source_hashes': hashes}, indent=2)+'\n')
    control_hash = p.sha(control_path)
    if not gates['known_message_controls']['all_twelve_gates_pass']:
        raise RuntimeError('Control gate failed; no rotated real solving allowed.')
    real = rotation_screen(plan, schedule, targets, prior)
    assert p.sha(control_path) == control_hash
    assert all(p.sha(ROOT/name) == value for name, value in hashes.items())
    result = {'session': 84, 'control_sha256_before_rotation_screen': control_hash,
              'rotation_screen_permitted': True, 'real': real,
              'source_hashes': {**hashes, control_path.name: control_hash},
              'limits': plan['limits'], 'new_plaintext_established': False}
    (ROOT/'quadratic_alignment_results.json').write_text(json.dumps(result, indent=2)+'\n')
    print(json.dumps({'section_rotations': real['total_section_rotations'], 'subset_counts': real['total_subset_counts'],
                      'summary': {name: {k: v for k, v in values.items() if k != 'rotation_cohort_costs'} for name, values in real['summary'].items()}}, indent=2), flush=True)


if __name__ == '__main__':
    main()
