"""Finite 1-D W1 and WGAN-GP slope sanity check; no GAN is trained."""
import json


def mean(values):
    return sum(values) / len(values)


def w1_sorted_pairing(p, q):
    """Exact 1-D W1 for equal-weight empirical measures of equal size."""
    if len(p) != len(q) or not p:
        raise ValueError("need equally sized, non-empty empirical measures")
    return mean([abs(x - y) for x, y in zip(sorted(p), sorted(q))])


def w1_cdf_quadrature(p, q):
    """Integrate |F_P-F_Q| exactly over intervals between support points."""
    breaks = sorted(set(p + q))
    area, intervals = 0.0, []
    for left, right in zip(breaks, breaks[1:]):
        mid = (left + right) / 2.0
        f_p = sum(x <= mid for x in p) / len(p)
        f_q = sum(x <= mid for x in q) / len(q)
        part = (right - left) * abs(f_p - f_q)
        intervals.append({"left": left, "right": right, "F_P": f_p, "F_Q": f_q, "area": part})
        area += part
    return area, intervals


def critic_gap(w, p, q):
    return mean([w * x for x in p]) - mean([w * x for x in q])


def gp_objective(w, p, q, penalty_weight):
    penalty = penalty_weight * (abs(w) - 1.0) ** 2
    return critic_gap(w, p, q) - penalty, penalty


def central_difference(fn, x, h=1e-6):
    return (fn(x + h) - fn(x - h)) / (2.0 * h)


def main():
    p, q = [-1.0, 1.0], [2.0, 4.0]  # Equal-weight Q is P translated by +3.
    w1_pairing = w1_sorted_pairing(p, q)
    w1_cdf, cdf_intervals = w1_cdf_quadrature(p, q)

    # Search the full valid linear 1-Lipschitz range on a 0.001 grid.
    bounded_w = [i / 1000.0 for i in range(-1000, 1001)]
    best_w = max(bounded_w, key=lambda w: critic_gap(w, p, q))
    invalid_w, invalid_gap = -5.0, critic_gap(-5.0, p, q)

    # Maximize J(w)=-3w-lambda*(|w|-1)^2. For w<0, dJ/dw=-3-2lambda(w+1).
    lam = 10.0
    w_star = -1.0 - 3.0 / (2.0 * lam)
    gp_value, penalty = gp_objective(w_star, p, q, lam)
    d_manual = -3.0 - 2.0 * lam * (w_star + 1.0)
    d_fd = central_difference(lambda w: gp_objective(w, p, q, lam)[0], w_star)

    # Negative control: identical finite distributions have zero W1.
    p0, q0 = [-1.0, 1.0], [-1.0, 1.0]
    w1_zero_pairing = w1_sorted_pairing(p0, q0)
    w1_zero_cdf, zero_intervals = w1_cdf_quadrature(p0, q0)

    checks = {
        "sorted_pairing_matches_CDF_quadrature": abs(w1_pairing - w1_cdf) < 1e-12,
        "translation_W1_equals_3": abs(w1_pairing - 3.0) < 1e-12,
        "bounded_grid_optimum_attains_W1": best_w == -1.0 and abs(critic_gap(best_w, p, q) - w1_pairing) < 1e-12,
        "unbounded_score_not_W1": invalid_gap == 15.0 and invalid_gap > w1_pairing and abs(invalid_w) > 1.0,
        "GP_stationary_derivative_formula_zero": abs(d_manual) < 1e-12,
        "GP_stationary_derivative_FD_zero": abs(d_fd) < 1e-8,
        "finite_GP_solution_slope_exceeds_1": abs(w_star) > 1.0,
        "identical_distribution_negative_control_zero": w1_zero_pairing == 0.0 and w1_zero_cdf == 0.0,
    }
    assert all(checks.values()), checks

    result = {
        "scope": "Exact finite 1-D distributions, linear critic arithmetic, and WGAN-GP penalty illustration only; no neural network, GAN training, image generation, mode-collapse diagnosis, convergence, quality, or benchmark.",
        "measure_convention": "P and Q each place equal probability on their two listed points; transportation cost is absolute distance on R.",
        "translation_example": {
            "P": p, "Q": q, "translation": 3.0,
            "W1_sorted_optimal_pairing": w1_pairing,
            "W1_integral_abs_CDF_difference": w1_cdf,
            "CDF_interval_contributions": cdf_intervals,
            "linear_critic": "f_w(x)=w*x",
            "critic_gap": "E_P[f_w]-E_Q[f_w]=-3w",
            "valid_1Lipschitz_condition": "|w| <= 1",
            "bounded_grid_max": {"w": best_w, "gap": critic_gap(best_w, p, q), "grid_step": 0.001},
            "invalid_unbounded_example": {"w": invalid_w, "gap": invalid_gap, "why_invalid": "|w|>1 violates the Kantorovich-Rubinstein 1-Lipschitz constraint; this score is not W1."},
        },
        "finite_WGAN_GP_linear_toy": {
            "maximized_objective": "J(w)=-3w-lambda*(|w|-1)^2",
            "lambda": lam,
            "negative_branch": "J(w)=-3w-lambda*(w+1)^2",
            "stationary_formula": "w=-1-3/(2*lambda)",
            "w_stationary": w_star,
            "critic_gap": critic_gap(w_star, p, q),
            "gradient_penalty": penalty,
            "maximized_objective_value": gp_value,
            "sign_reversed_minimized_critic_loss": -gp_value,
            "dJ_dw_manual": d_manual,
            "dJ_dw_central_difference": d_fd,
            "slope_magnitude": abs(w_star),
            "interpretation": "For finite lambda, this sampled-point soft penalty trades critic gap against slope penalty. This linear example has slope 1.15 everywhere; its penalized optimum is not 1-Lipschitz and is not a global Lipschitz certificate.",
        },
        "negative_control": {"P": p0, "Q": q0, "W1_sorted_pairing": w1_zero_pairing, "W1_integral_abs_CDF_difference": w1_zero_cdf, "CDF_interval_contributions": zero_intervals},
        "checks": checks,
    }
    print(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False))


if __name__ == "__main__":
    main()
