"""One supplementary finite-sample control for Session 75.

Specified after the main histogram diagnostic, before generating this fixture.
No real-text score is used to choose its seed, distribution or generated keys.
The independent iid increments have fixed integer weights 2:3:5 at 0,4,17.
This is a control demonstrating sampling discrepancy, not a calibrated test.
"""
import json
import numpy as np
from key_increment_audit import B, ROOT, GROUPS, vals, differences, prob, best_fit, sha

SEED = 3301075


def main():
    weights = np.zeros(B)
    weights[[0, 4, 17]] = [2, 3, 5]
    q = prob(weights)
    rng = np.random.default_rng(SEED)
    reference_counts = np.zeros(B, dtype=np.int64)
    cipher_counts = np.zeros(B, dtype=np.int64)
    groups = []
    for name, source in GROUPS.items():
        plaintext = vals(source)
        increments = rng.choice(B, size=len(plaintext)-1, p=q)
        key = np.r_[7, 7+np.cumsum(increments)] % B
        ciphertext = (plaintext + key) % B
        assert np.array_equal((ciphertext-key) % B, plaintext)
        reference_counts += differences(plaintext)
        cipher_counts += differences(ciphertext)
        groups.append({'name': name, 'ciphertext_values': ciphertext.tolist(),
                       'key_values': key.tolist(), 'known_key_decryption_exact': True})
    fitted = best_fit(prob(reference_counts), prob(cipher_counts))
    result = {
        'session': 75, 'role': 'Supplementary finite-realization control, specified after the main diagnostic.',
        'seed': SEED, 'generation': 'Key increments drawn iid, independently of the five retained plaintext streams. Fixed weights 2:3:5 at increments 0,4,17. Initial key value 7 in each source group.',
        'transitions': int(cipher_counts.sum()),
        'key_increment_probabilities': q.tolist(),
        'plaintext_increment_counts': reference_counts.tolist(),
        'ciphertext_increment_counts': cipher_counts.tolist(),
        'minimum_tv_against_true_plaintext_profile': fitted['minimum_total_variation'],
        'fit': fitted, 'groups': groups,
        'source_hashes': {n: sha(ROOT/n) for n in [
            'key_increment_sampling_control.py', 'key_increment_audit.py',
            'key_increment_plan.json', 'key_increment_results.json',
            'liber-primus__transcription--master.txt', 'lp_core.py', 'word_core.py']},
        'limit': 'One constructed sample, not a noise threshold, null distribution or significance calibration. Correct known-key recovery does not mean unknown-key recovery.',
    }
    path = ROOT/'key_increment_sampling_results.json'
    path.write_text(json.dumps(result, indent=2)+'\n')
    print(json.dumps({'seed': SEED, 'transitions': result['transitions'],
                      'known_key_decryption_exact': True,
                      'minimum_tv': fitted['minimum_total_variation'],
                      'result_sha256': sha(path)}, indent=2))


if __name__ == '__main__':
    main()
