"""Session 75: independent additive key-increment compatibility.

Run with Python, NumPy and SciPy beside the retained LP utilities.
This is an empirical convex-mixture diagnostic, not a decryption or p-value.
No network calls. No master or earlier result files are changed.
"""
import hashlib
import json
import platform
from pathlib import Path

import scipy
from scipy.optimize import linprog

from lp_core import ROOT, R, LET, lp, vals, np
from word_core import GROUPS
from lexical_words import tokenize_words

B = 29
TOL = 1e-9
FIT = [0, 1, 2, 4]
LATER = [5, 6, 7, 8]


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


def differences(v):
    return np.bincount((np.diff(v) % B), minlength=B)


def prob(counts):
    return counts / counts.sum()


def convolution_matrix(p):
    # Column k is the ciphertext-difference distribution for key difference k.
    return np.column_stack([np.roll(p, k) for k in range(len(p))])


def tv(a, b):
    return float(np.abs(a - b).sum() / 2)


def best_fit(p, target):
    """Minimize .5*sum(e), subject to -e <= A*q-target <= e.

    q is any nonnegative key-increment distribution of total mass one.
    The selected optimal q need not be unique; retain the solver's one output.
    """
    size = len(p)
    A = convolution_matrix(p)
    objective = np.r_[np.zeros(size), np.full(size, .5)]
    bounds = [(0, None)] * (2 * size)
    solution = linprog(
        objective,
        A_ub=np.vstack([np.c_[A, -np.eye(size)], np.c_[-A, -np.eye(size)]]),
        b_ub=np.r_[target, -target],
        A_eq=np.r_[np.ones(size), np.zeros(size)][None, :],
        b_eq=[1.0], bounds=bounds, method='highs',
        options={'dual_feasibility_tolerance': TOL,
                 'primal_feasibility_tolerance': TOL},
    )
    assert solution.success, solution.message
    q = solution.x[:size]
    expected = A @ q
    assert q.min() >= -TOL and abs(q.sum() - 1) < TOL
    residual = tv(expected, target)
    assert abs(residual - solution.fun) < TOL
    # HiGHS dual variables also supply an independently recorded lower bound.
    dual_bound = float(np.r_[target, -target] @ solution.ineqlin.marginals
                       + solution.eqlin.marginals[0])
    assert abs(dual_bound - residual) < TOL
    return {
        'minimum_total_variation': residual,
        'exact_empirical_match_within_tolerance': residual < TOL,
        'key_increment_probabilities': q.tolist(),
        'expected_cipher_increment_probabilities': expected.tolist(),
        'expected_repeat_probability': float(expected[0]),
        'signed_residual_expected_minus_observed': (expected - target).tolist(),
        'dual_lower_bound': dual_bound,
        'dual_inequality_weights': solution.ineqlin.marginals.tolist(),
        'dual_equality_weight': float(solution.eqlin.marginals[0]),
        'dual_feasibility_max_violation': float(max(0, np.max(
            np.vstack([np.c_[A, -np.eye(size)], np.c_[-A, -np.eye(size)]]).T
            @ solution.ineqlin.marginals
            + np.r_[np.ones(size), np.zeros(size)] * solution.eqlin.marginals[0]
            - objective))),
    }


def record_counts(counts):
    return {'transitions': int(counts.sum()), 'repeat_count': int(counts[0]),
            'increment_counts': counts.tolist(),
            'increment_probabilities': prob(counts).tolist()}


def controls(reference_vectors, pooled_counts):
    p = prob(pooled_counts)
    # Check orientation and modular convention for all 841 delta pairs.
    checked = 0
    for d_plain in range(B):
        unit = np.eye(B)[d_plain]
        A = convolution_matrix(unit)
        for d_key in range(B):
            assert np.argmax(A[:, d_key]) == (d_plain + d_key) % B
            checked += 1
    assert np.allclose(convolution_matrix(p) @ np.full(B, 1/B), 1/B,
                       atol=1e-14)

    slopes = []
    for slope in range(B):
        total = np.zeros(B, dtype=np.int64)
        for v in reference_vectors:
            key = (np.arange(len(v)) * slope + 7) % B
            ciphertext = (v + key) % B
            assert np.array_equal((ciphertext - key) % B, v)
            total += differences(ciphertext)
        assert np.array_equal(total, np.roll(pooled_counts, slope))
        fitted = best_fit(p, prob(total))
        assert fitted['minimum_total_variation'] < TOL
        slopes.append({'slope': slope, 'known_key_decryption_exact': True,
                       'histogram_fit_distance': fitted['minimum_total_variation']})

    # Exact independent delta pairs, with integer weights, not a natural book.
    weights = np.zeros(B, dtype=np.int64)
    weights[[0, 4, 17]] = [2, 3, 5]
    product = np.array([
        sum(int(pooled_counts[d]) * int(weights[(c-d) % B]) for d in range(B))
        for c in range(B)], dtype=np.int64)
    expected = convolution_matrix(p) @ prob(weights)
    assert np.allclose(prob(product), expected, atol=1e-14)
    product_fit = best_fit(p, prob(product))
    assert product_fit['minimum_total_variation'] < TOL

    # Deliberately dependent key: C_i=i mod29, K_i=C_i-P_i.
    # This legal additive encoder has zero repeats and recovers the known prose,
    # but its key depends on that prose and fails the independence premise.
    dependent_counts = np.zeros(B, dtype=np.int64)
    for v in reference_vectors:
        ciphertext = np.arange(len(v)) % B
        key = (ciphertext - v) % B
        assert np.array_equal((ciphertext - key) % B, v)
        dependent_counts += differences(ciphertext)
    assert dependent_counts[0] == 0
    dependent_fit = best_fit(p, prob(dependent_counts))
    assert dependent_fit['minimum_total_variation'] > .5
    return {
        'modular_delta_pair_checks': checked,
        'uniform_increment_mixture_exact': True,
        'constant_slope_known_text_controls': slopes,
        'independent_weighted_product': {
            'key_increment_weights': weights.tolist(),
            'transition_count': int(product.sum()),
            'predicted_distribution_exact': True,
            'minimum_total_variation': product_fit['minimum_total_variation'],
            'scope': 'Exact independent delta-pair fixture; not new natural prose.'},
        'plaintext_dependent_key_counterexample': {
            **record_counts(dependent_counts),
            'known_key_decryption_exact': True,
            'independent_profile_minimum_total_variation':
                dependent_fit['minimum_total_variation'],
            'meaning': 'The diagnostic is conditional on independence, not a ban on all additive ciphers.'},
    }


def phrase_check(source):
    all_values = vals(source)
    expected = np.array([23, 11, 1, 17, 18, 10])
    anchors = [6555, 12950]
    words = tokenize_words(source)
    records = []
    for anchor in anchors:
        assert np.array_equal(all_values[anchor:anchor+6], expected)
        start = next(i for i, w in enumerate(words) if w['rune_offset'] == anchor)
        pair = words[start:start+2]
        assert [len(w['values']) for w in pair] == [3, 3]
        assert pair[0]['section'] == pair[1]['section']
        records.append({'global_rune_offset': anchor, 'lp2_page': pair[0]['page'],
                        'section': pair[0]['section'],
                        'page_rune_offset': pair[0]['page_rune_offset'],
                        'preceding_cipher_rune': int(all_values[anchor-1]),
                        'internal_cipher_increments': (np.diff(expected) % B).tolist()})
    # Algebra controls use explicitly synthetic plaintext, not a phrase guess.
    synthetic_p = np.array([1, 7, 3, 24, 6, 10])
    first_key = (expected - synthetic_p) % B
    second_p = (synthetic_p + 1) % B
    second_key = (expected - second_p) % B
    assert np.array_equal((synthetic_p + first_key) % B, expected)
    assert np.array_equal((second_p + second_key) % B, expected)
    assert not np.array_equal(first_key, second_key)
    return {'cipher_runes': expected.tolist(), 'labels': [LET[i] for i in expected],
            'anchors': records,
            'synthetic_equal_cipher_different_plaintext_control_passed': True,
            'identity': 'C_A=C_B implies K_A-K_B=P_B-P_A (mod29), component by component. If P_A=P_B, the six corresponding key values must match.',
            'limit': 'One-step increment marginals leave temporal dependence and six-value joint recurrence unspecified. No recurrence probability or independent validation is inferred here.'}


def main():
    plan = json.loads((ROOT/'key_increment_plan.json').read_text())
    assert plan['split']['fit_sections'] == FIT
    assert plan['split']['continuation_sections'] == LATER
    vectors = {name: vals(text) for name, text in GROUPS.items()}
    counts = {name: differences(v) for name, v in vectors.items()}
    pooled = sum(counts.values())
    assert int(pooled.sum()) == 1958
    counts = {'pooled': pooled, **counts}
    source = '%'.join(lp[:56])
    sections = {i: vals(s) for i, s in enumerate(source.split('$'))
                if len(vals(s)) > 100}
    assert list(sections) == FIT + LATER
    section_counts = {i: differences(v) for i, v in sections.items()}
    training = sum(section_counts[i] for i in FIT)
    later = sum(section_counts[i] for i in LATER)
    total = training + later
    assert (int(total.sum()), int(total[0])) == (12939, 86)
    references = []
    for name, reference in counts.items():
        p = prob(reference)
        first = best_fit(p, prob(training))
        frozen_expected = np.array(first['expected_cipher_increment_probabilities'])
        whole = best_fit(p, prob(total))
        references.append({
            'name': name, **record_counts(reference),
            'minimum_expected_repeat_probability': float(p.min()),
            'minimizing_key_increments': [k for k in range(B)
                if abs(p[(-k) % B] - p.min()) < 1e-14],
            'minimum_expected_repeat_count_at_real_exposure': float(p.min() * total.sum()),
            'uniform_key_increment_expected_repeat_count': float(total.sum() / B),
            'all_sections_best_fit': whole,
            'earlier_sections_fit': first,
            'frozen_prediction_later_sections_tv': tv(frozen_expected, prob(later)),
            'uniform_prediction_later_sections_tv': tv(np.full(B, 1/B), prob(later)),
            'observed_earlier_to_later_tv': tv(prob(training), prob(later)),
        })
    section_fits = []
    for i, v in sections.items():
        ct = section_counts[i]
        section_fits.append({'section': i, 'runes': len(v), **record_counts(ct),
                             'pooled_reference_best_fit': best_fit(prob(pooled), prob(ct))})

    independent_section_weighted_tv = sum(
        r['transitions'] * r['pooled_reference_best_fit']['minimum_total_variation']
        for r in section_fits) / int(total.sum())
    result = {
        'session': 75, 'alphabet': R, 'rune_labels': LET,
        'increment_bins': list(range(B)),
        'environment': {'python': platform.python_version(), 'numpy': np.__version__,
                        'scipy': scipy.__version__},
        'source_hashes': {name: sha(ROOT/name) for name in [
            'liber-primus__transcription--master.txt', 'lp_core.py', 'word_core.py',
            'lexical_words.py', 'key_increment_plan.json', 'key_increment_audit.py']},
        'formula': 'r(d)=sum_j p(d-j)q(j), with modular indices and independent plaintext/key increments.',
        'expected_repeat_floor_formula': 'min_q r(0)=min_j p(j). Each q is a probability distribution.',
        'metric': 'Minimum .5*L1 distance between the empirical cipher difference distribution and an expected convolution. This is not a p-value.',
        'real_corpus': {'earlier': record_counts(training), 'later': record_counts(later),
                        'all': record_counts(total), 'runes': sum(map(len, sections.values())),
                        'section_boundary_policy': 'Exclude all cross-section edges and the nine-rune numeric segment.'},
        'references': references,
        'independent_section_sensitivity': {
            'sections': section_fits,
            'exposure_weighted_minimum_tv': float(independent_section_weighted_tv),
            'meaning': 'Expected local profile distances with separate arbitrary q in each section. Not a global pooled-distance bound.'},
        'controls': controls(list(vectors.values()), pooled),
        'repeated_phrase': phrase_check(source),
        'limits': plan['limits'] + [plan['interpretation'],
            'Earlier and later sections have been examined before. This is a retrospective conditional diagnostic, not fresh held-out evidence.',
            'The five solved reference samples are short and related. Sensitivity across them is not a confidence interval or a sampling correction.',
            'The reference profiles and observed distributions are empirical. Independence need not hold exactly for their finite realized transitions even under an independently generated key.',
            'The one selected training optimum is frozen; continuation results do not claim to cover every tied optimum.',
            'No glyph reading, boundary change, unknown-key recovery or plaintext decoding is performed.'],
    }
    target = ROOT/'key_increment_results.json'
    target.write_text(json.dumps(result, indent=2, ensure_ascii=False)+'\n')
    print(json.dumps({
        'real_transitions': int(total.sum()), 'real_repeats': int(total[0]),
        'reference_summary': [{
            'name': r['name'], 'repeat_floor': r['minimum_expected_repeat_probability'],
            'all_best_tv': r['all_sections_best_fit']['minimum_total_variation'],
            'fit_tv': r['earlier_sections_fit']['minimum_total_variation'],
            'later_tv': r['frozen_prediction_later_sections_tv'],
        } for r in references],
        'separate_section_weighted_tv': independent_section_weighted_tv,
        'controls_passed': True, 'result_sha256': sha(target),
    }, indent=2))


if __name__ == '__main__':
    main()
