#!/usr/bin/env python3
"""Run the blog's finite RL examples and sampling-budget arithmetic.

Standard library only. Exact enumeration checks a finite model; it does not
measure LLM training performance or establish a sampler's input assumptions.
"""

from fractions import Fraction
from itertools import product
from math import sqrt


def expected_update(p, q, weight_shift, shift_on_all_wrong=False):
    """Average the two-response update over all four IID Bernoulli pairs."""
    expectation = Fraction(0)
    total_probability = Fraction(0)
    for r1, r2 in product((0, 1), repeat=2):
        probability = (q if r1 else 1 - q) * (q if r2 else 1 - q)
        a1, a2 = Fraction(r1 - r2), Fraction(r2 - r1)
        if not shift_on_all_wrong or (r1 == 0 and r2 == 0):
            a1 += weight_shift
            a2 += weight_shift
        # The Bernoulli-logit score at outcome r is r - p.
        update = (a1 * (r1 - p) + a2 * (r2 - p)) / 2
        expectation += probability * update
        total_probability += probability
    if total_probability != 1:
        raise AssertionError("Pair probabilities do not sum to one")
    return expectation


def check_equal(actual, predicted):
    if actual != predicted:
        raise AssertionError(f"Enumerated {actual}; predicted {predicted}")


def main():
    p = Fraction(1, 4)
    weight_shift = Fraction(1, 2)
    print("RL: exact group enumeration; p = 1/4, lambda = 1/2")
    print(f"{'Intervention':<22} {'q':>5} {'Base':>8} {'Shifted':>8} {'Delta':>8} {'Prediction':>11}")
    for intervention, all_wrong_only in (("Every response", False), ("All-wrong pairs only", True)):
        for q in (p, Fraction(3, 4)):
            baseline = expected_update(p, q, Fraction(0))
            shifted = expected_update(p, q, weight_shift, all_wrong_only)
            difference = shifted - baseline
            prediction = (
                weight_shift * (1 - q) ** 2 * (-p)
                if all_wrong_only
                else weight_shift * (q - p)
            )
            check_equal(difference, prediction)
            print(f"{intervention:<22} {str(q):>5} {str(baseline):>8} {str(shifted):>8} {str(difference):>8} {str(prediction):>11}")

    # Inputs to the public theorem, assumed to hold at every outer step:
    # common initialization, total outer time 1, c = 1, averaged squared
    # conditional bias <= .02^2, averaged trace variance <= 4, and N = 256
    # conditionally independent inner samples. All moment/integrability and
    # Gaussian-chain premises remain inputs; this checks only the arithmetic.
    total_time = Fraction(1)
    coefficient = Fraction(1)
    squared_bias_bound = Fraction(2, 100) ** 2
    trace_variance_bound = Fraction(4)
    inner_samples = 256
    approximation_budget = Fraction(5, 100)
    reference_tv_bound = Fraction(1, 100)
    squared_approximation_bound = (
        total_time * coefficient**2
        * (squared_bias_bound + trace_variance_bound / inner_samples) / 8
    )
    if squared_approximation_bound > approximation_budget**2:
        raise AssertionError("The approximation budget is exceeded")
    total_tv_budget = reference_tv_bound + approximation_budget
    check_equal(total_tv_budget, Fraction(6, 100))
    print("\nSampling: arithmetic with the theorem's assumptions supplied")
    print(f"Squared approximation bound: {squared_approximation_bound} <= {approximation_budget**2}")
    print(f"Approximation TV bound: {sqrt(float(squared_approximation_bound)):.6f} <= {float(approximation_budget):.2f}")
    print(f"Target TV budget: {float(reference_tv_bound):.2f} + {float(approximation_budget):.2f} = {float(total_tv_budget):.2f}")
    print("\nPASS: finite RL enumeration and sampling-budget arithmetic")


if __name__ == "__main__":
    main()
