"""Three-step scalar DDPM arithmetic; no RNG, model, optimizer or image generation."""
import json
import math
import platform


def close(a, b):
    if not math.isclose(a, b, rel_tol=1e-12, abs_tol=1e-12):
        raise AssertionError((a, b))


def main():
    x0 = 1.25
    betas = [0.1, 0.2, 0.3]  # Deliberately large toy schedule, not Ho's trained schedule.
    chosen_eps = [-0.5, 1.0, -1.5]  # Hand-picked constants, NOT Gaussian draws.
    alphas = [1.0 - beta for beta in betas]
    bars = [1.0]
    states = [x0]
    rows = []
    for i, (alpha, beta, eps) in enumerate(zip(alphas, betas, chosen_eps)):
        bars.append(bars[-1] * alpha)
        states.append(math.sqrt(alpha) * states[-1] + math.sqrt(beta) * eps)
        coefficients = [math.sqrt(betas[j] * math.prod(alphas[j + 1:i + 1]))
                        for j in range(i + 1)]
        coeff_sq_sum = sum(c * c for c in coefficients)
        noise_sum = sum(c * e for c, e in zip(coefficients, chosen_eps))
        effective_eps = noise_sum / math.sqrt(1.0 - bars[-1])
        closed = math.sqrt(bars[-1]) * x0 + math.sqrt(1.0 - bars[-1]) * effective_eps
        restored = (states[-1] - math.sqrt(1.0 - bars[-1]) * effective_eps) / math.sqrt(bars[-1])
        close(coeff_sq_sum, 1.0 - bars[-1])
        close(states[-1], closed)
        close(restored, x0)
        delta = 0.1
        perturbed = (states[-1] - math.sqrt(1.0 - bars[-1]) * (effective_eps + delta)) / math.sqrt(bars[-1])
        predicted_error = -math.sqrt((1.0 - bars[-1]) / bars[-1]) * delta
        close(perturbed - x0, predicted_error)
        posterior_var = beta * (1.0 - bars[-2]) / (1.0 - bars[-1])
        x0_coeff = math.sqrt(bars[-2]) * beta / (1.0 - bars[-1])
        xt_coeff = math.sqrt(alpha) * (1.0 - bars[-2]) / (1.0 - bars[-1])
        posterior_mean = x0_coeff * x0 + xt_coeff * states[-1]
        oracle_reverse_mean = (states[-1] - beta * effective_eps / math.sqrt(1.0 - bars[-1])) / math.sqrt(alpha)
        close(posterior_mean, oracle_reverse_mean)
        # Fresh HAND-CHOSEN reverse z, unrelated to the forward epsilon history.
        proposed_z = 0.5
        used_z = proposed_z if i + 1 > 1 else 0.0  # Algorithm 2's last-step rule.
        rows.append({
            't': i + 1, 'alpha': alpha, 'alpha_bar': bars[-1],
            'chosen_step_epsilon': eps, 'sequential_xt': states[-1],
            'forward_noise_coefficients': coefficients,
            'sum_coefficient_squares': coeff_sq_sum, 'forward_marginal_variance': 1.0 - bars[-1],
            'oracle_effective_epsilon': effective_eps, 'closed_form_xt': closed,
            'oracle_reconstructed_x0': restored,
            'epsilon_plus_0_1_reconstruction': perturbed, 'reconstruction_error': predicted_error,
            'posterior_x0_coefficient': x0_coeff, 'posterior_xt_coefficient': xt_coeff,
            'posterior_mean_given_x0': posterior_mean, 'oracle_epsilon_reverse_mean': oracle_reverse_mean,
            'beta_variance': beta, 'posterior_beta_tilde_variance': posterior_var,
            'proposed_hand_chosen_z': proposed_z, 'used_z_after_last_step_rule': used_z,
            'illustrative_step_beta_variance': oracle_reverse_mean + math.sqrt(beta) * used_z,
            'illustrative_step_beta_tilde_variance': oracle_reverse_mean + math.sqrt(posterior_var) * used_z,
        })
    # Independent scalar Gaussian conditioning for t=2 given x0:
    # Cov(x1,x2|x0)=sqrt(alpha2)*Var(x1|x0).
    t = 2
    mean_prev = math.sqrt(bars[t - 1]) * x0
    mean_current = math.sqrt(bars[t]) * x0
    var_prev = 1.0 - bars[t - 1]
    var_current = 1.0 - bars[t]
    cov = math.sqrt(alphas[t - 1]) * var_prev
    conditional_mean = mean_prev + cov / var_current * (states[t] - mean_current)
    conditional_var = var_prev - cov * cov / var_current
    close(conditional_mean, rows[t - 1]['posterior_mean_given_x0'])
    close(conditional_var, rows[t - 1]['posterior_beta_tilde_variance'])
    result = {
        'environment': {'python': platform.python_version(), 'dependencies': 'standard library only', 'numeric_type': 'Python float'},
        'scope': 'Fixed scalar arithmetic. No random sampling, neural network, fitting, image generation or quality evaluation.',
        'x0': x0, 'toy_betas': betas, 'hand_chosen_forward_epsilons': chosen_eps,
        'rows': rows,
        'independent_t2_gaussian_conditioning': {'mean': conditional_mean, 'variance': conditional_var},
        'fixed_epsilon_prediction_squared_error_for_delta_0_1': 0.1 ** 2,
        'limitations': [
            'Effective epsilon is an ORACLE computed from known x0 and the chosen forward history; it is not a learned predictor.',
            'The coefficient-square variance identity has a probabilistic interpretation only with independent standard Gaussian step noises.',
            'Each reverse-step illustration conditions on its stored forward xt; the rows are not a recursively sampled generative trajectory.',
            'The analytic posterior conditions on x0; it is not the generally unavailable true reverse conditional given only xt.',
            'beta and beta_tilde are alternative fixed reverse variance choices for t>1, not the forward marginal variance.',
            'At t=1 sampling adds no z noise. This does not prove a learned model has recovered the original training image.',
            'The final noise squared error is one fixed arithmetic example, not a Monte Carlo estimate or trained objective value.'
        ]
    }
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))


if __name__ == '__main__':
    main()
