#!/usr/bin/env python3
"""Fixed scalar Gaussian VAE mechanics; deterministic, standard library only."""
import json
import math
import platform


X = 1.0
MU = 0.3
SIGMA = 0.7
W = 1.2
B = -0.1
OBS_SIGMA = 0.5
EPSILONS = (-1.0, 0.0, 1.0)


def terms(mu, logvar, epsilon):
    sigma = math.exp(0.5 * logvar)
    z = mu + sigma * epsilon
    decoder_mean = W * z + B
    variance = OBS_SIGMA**2
    nll = 0.5 * math.log(2.0 * math.pi * variance)
    nll += 0.5 * (X - decoder_mean) ** 2 / variance
    kl = 0.5 * (mu**2 + sigma**2 - 1.0 - logvar)

    d_nll_dz = (decoder_mean - X) * W / variance
    dmu = d_nll_dz + mu
    dlogvar = d_nll_dz * 0.5 * sigma * epsilon + 0.5 * (sigma**2 - 1.0)
    return {
        "sigma": sigma,
        "z": z,
        "decoder_mean": decoder_mean,
        "gaussian_nll": nll,
        "kl": kl,
        "negative_elbo_sample": nll + kl,
        "pathwise_gradient_mu": dmu,
        "pathwise_gradient_logvar": dlogvar,
    }


def central_difference(function, value, step=1e-6):
    return (function(value + step) - function(value - step)) / (2.0 * step)


def density(z, mu, sigma):
    return math.exp(-0.5 * ((z - mu) / sigma) ** 2) / (sigma * math.sqrt(2.0 * math.pi))


def gaussian_nll_at_z(z):
    mean = W * z + B
    return 0.5 * math.log(2.0 * math.pi * OBS_SIGMA**2) + 0.5 * (X - mean) ** 2 / OBS_SIGMA**2


def main():
    logvar = math.log(SIGMA**2)
    rows = []
    fd_errors = []
    for epsilon in EPSILONS:
        result = terms(MU, logvar, epsilon)
        result["epsilon_fixed_not_sampled"] = epsilon
        fd_mu = central_difference(lambda m: terms(m, logvar, epsilon)["negative_elbo_sample"], MU)
        fd_lv = central_difference(lambda lv: terms(MU, lv, epsilon)["negative_elbo_sample"], logvar)
        result["central_difference_gradient_mu"] = fd_mu
        result["central_difference_gradient_logvar"] = fd_lv
        fd_errors.append(max(abs(fd_mu - result["pathwise_gradient_mu"]), abs(fd_lv - result["pathwise_gradient_logvar"])))
        rows.append(result)

    expected_nll = 0.5 * math.log(2.0 * math.pi * OBS_SIGMA**2)
    expected_nll += 0.5 * ((X - (W * MU + B)) ** 2 + W**2 * SIGMA**2) / OBS_SIGMA**2
    kl = 0.5 * (MU**2 + SIGMA**2 - 1.0 - logvar)
    expected_negative_elbo = expected_nll + kl

    # Independent density-weighted trapezoid quadrature over z in [-8, 8].
    lo, hi, step = -8.0, 8.0, 0.001
    n = round((hi - lo) / step)
    weighted_sum = 0.0
    mass_sum = 0.0
    for i in range(n + 1):
        z = lo + i * step
        trapezoid_weight = 0.5 if i in (0, n) else 1.0
        p = density(z, MU, SIGMA)
        weighted_sum += trapezoid_weight * p * gaussian_nll_at_z(z)
        mass_sum += trapezoid_weight * p
    numerical_mass = mass_sum * step
    numerical_expected_nll = weighted_sum * step / numerical_mass

    output = {
        "scope": "deterministic_scalar_reparameterization_example_not_a_trained_VAE",
        "runtime": {"python": platform.python_version(), "dependencies": "Python standard library only"},
        "fixed_parameters": {
            "x": X, "q_mu": MU, "q_sigma": SIGMA, "q_logvar": logvar,
            "decoder_w": W, "decoder_b": B, "likelihood_sigma": OBS_SIGMA,
            "epsilons_are_hand_chosen_not_gaussian_draws": list(EPSILONS),
        },
        "fixed_epsilon_samples": rows,
        "gradient_check": {
            "method": "central finite differences with fixed epsilon and step 1e-6",
            "max_abs_error_over_mu_and_logvar": max(fd_errors),
        },
        "expected_objective": {
            "expected_gaussian_nll_closed_form": expected_nll,
            "kl_q_to_unit_normal": kl,
            "negative_elbo_closed_form": expected_negative_elbo,
            "quadrature": {
                "method": "trapezoid integral of q(z|x) density times scalar Gaussian NLL",
                "interval": [lo, hi], "step": step,
                "integrated_probability_mass": numerical_mass,
                "expected_gaussian_nll": numerical_expected_nll,
                "absolute_difference_from_closed_form": abs(numerical_expected_nll - expected_nll),
            },
        },
        "limitations": [
            "No neural network, learned encoder/decoder, dataset, training, Monte Carlo quality estimate, or latent traversal.",
            "The three fixed epsilon values illustrate the path, not draws from a Gaussian or an estimate of sample quality.",
            "The expected NLL is checked analytically and by numerical integration for this scalar Gaussian setup only.",
        ],
    }
    print(json.dumps(output, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()
