"""A deterministic scalar GAN update example; not a neural-network training run."""
import json
import math
import platform

import torch
import torch.nn as nn
import torch.nn.functional as F

DTYPE = torch.float64
DEVICE = torch.device("cpu")


class ScalarGenerator(nn.Module):
    def __init__(self):
        super().__init__()
        self.a = nn.Parameter(torch.tensor(0.4, dtype=DTYPE, device=DEVICE))
        self.c = nn.Parameter(torch.tensor(-0.1, dtype=DTYPE, device=DEVICE))

    def forward(self, z):
        return self.a * z + self.c


class ScalarDiscriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.w = nn.Parameter(torch.tensor(1.2, dtype=DTYPE, device=DEVICE))
        self.b = nn.Parameter(torch.tensor(-0.3, dtype=DTYPE, device=DEVICE))

    def forward(self, x):
        # Return logits. BCEWithLogitsLoss applies a numerically stable sigmoid+BCE.
        return self.w * x + self.b


def f(x):
    return float(x.detach().cpu()) if isinstance(x, torch.Tensor) else float(x)


def sigmoid_scalar(x):
    # Stable scalar sigmoid without autograd.
    if x >= 0:
        e = math.exp(-x)
        return 1.0 / (1.0 + e)
    e = math.exp(x)
    return e / (1.0 + e)


def softplus_scalar(x):
    # Stable log(1 + exp(x)); used for independent loss/finite-difference checks.
    return max(x, 0.0) + math.log1p(math.exp(-abs(x)))


def bce_logit_scalar(logit, target):
    return softplus_scalar(logit) - target * logit


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


def d_loss_scalar(w, b, z_values, real_values, a_value, c_value):
    fake_values = [a_value * z + c_value for z in z_values]
    real_loss = mean([bce_logit_scalar(w * x + b, 1.0) for x in real_values])
    fake_loss = mean([bce_logit_scalar(w * x + b, 0.0) for x in fake_values])
    # The two batch means are summed; this is not one mean over a 2B concatenation.
    return real_loss + fake_loss


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


z = torch.tensor([-1.0, 1.0], dtype=DTYPE, device=DEVICE)
real = torch.tensor([0.8, 1.2], dtype=DTYPE, device=DEVICE)
G = ScalarGenerator()
D = ScalarDiscriminator()

# --- Discriminator step: hold G fixed and detach fake samples. ---
a0, c0 = f(G.a), f(G.c)
w0, b0 = f(D.w), f(D.b)
fake0 = G(z)
real_logits0 = D(real)
fake_logits0 = D(fake0.detach())
d_real_loss = F.binary_cross_entropy_with_logits(
    real_logits0, torch.ones_like(real_logits0), reduction="mean"
)
d_fake_loss = F.binary_cross_entropy_with_logits(
    fake_logits0, torch.zeros_like(fake_logits0), reduction="mean"
)
d_loss = d_real_loss + d_fake_loss
D.zero_grad(set_to_none=True)
d_loss.backward()
d_grads_torch = {"w": f(D.w.grad), "b": f(D.b.grad)}

# Independent scalar chain-rule derivatives, using only Python math.
real_x = [0.8, 1.2]
z_values = [-1.0, 1.0]
fake_x0 = [a0 * zi + c0 for zi in z_values]
d_dw_manual = mean([
    (sigmoid_scalar(w0 * x + b0) - 1.0) * x for x in real_x
]) + mean([
    sigmoid_scalar(w0 * x + b0) * x for x in fake_x0
])
d_db_manual = mean([
    sigmoid_scalar(w0 * x + b0) - 1.0 for x in real_x
]) + mean([
    sigmoid_scalar(w0 * x + b0) for x in fake_x0
])
d_w_fd = central_difference(lambda w: d_loss_scalar(w, b0, z_values, real_x, a0, c0), w0)
d_b_fd = central_difference(lambda b: d_loss_scalar(w0, b, z_values, real_x, a0, c0), b0)

D_LR = 0.05
d_optimizer = torch.optim.SGD(D.parameters(), lr=D_LR)
d_before = {"w": f(D.w), "b": f(D.b)}
d_optimizer.step()
d_after = {"w": f(D.w), "b": f(D.b)}
d_update_expected = {
    "w": d_before["w"] - D_LR * d_grads_torch["w"],
    "b": d_before["b"] - D_LR * d_grads_torch["b"],
}
g_grads_none_after_d = G.a.grad is None and G.c.grad is None
g_params_after_d = {"a": f(G.a), "c": f(G.c)}
assert g_grads_none_after_d and g_params_after_d == {"a": a0, "c": c0}  # fake detached; G unchanged

# --- Non-saturating generator step: freeze D parameters, but keep its input path. ---
D.zero_grad(set_to_none=True)
for parameter in D.parameters():
    parameter.requires_grad_(False)

G.zero_grad(set_to_none=True)
fake_for_g = G(z)
g_logits = D(fake_for_g)
g_loss = F.binary_cross_entropy_with_logits(
    g_logits, torch.ones_like(g_logits), reduction="mean"
)
g_loss.backward()
g_grads_torch = {"a": f(G.a.grad), "c": f(G.c.grad)}

w1, b1 = f(D.w), f(D.b)
# Independent scalar derivatives with D held fixed at its post-D-step values.
def g_loss_scalar(a, c):
    return mean([
        bce_logit_scalar(w1 * (a * zi + c) + b1, 1.0) for zi in z_values
    ])

sigmoid_errors = [sigmoid_scalar(w1 * (a0 * zi + c0) + b1) - 1.0 for zi in z_values]
g_da_manual = mean([error * w1 * zi for error, zi in zip(sigmoid_errors, z_values)])
g_dc_manual = mean([error * w1 for error in sigmoid_errors])
g_a_fd = central_difference(lambda a: g_loss_scalar(a, c0), a0)
g_c_fd = central_difference(lambda c: g_loss_scalar(a0, c), c0)

G_LR = 0.1
g_optimizer = torch.optim.SGD(G.parameters(), lr=G_LR)
g_before = {"a": f(G.a), "c": f(G.c)}
g_optimizer.step()
g_after = {"a": f(G.a), "c": f(G.c)}
g_update_expected = {
    "a": g_before["a"] - G_LR * g_grads_torch["a"],
    "c": g_before["c"] - G_LR * g_grads_torch["c"],
}
assert D.w.grad is None and D.b.grad is None  # D is frozen, but D(fake) was not no_grad.

# Compare original minimax G objective to the non-saturating objective in logit space.
# Stable forms: log(1 - sigmoid(s)) = -softplus(s); -log(sigmoid(s)) = softplus(-s).
logit_comparison = []
for s in (-8.0, 0.0, 8.0):
    p = sigmoid_scalar(s)
    logit_comparison.append({
        "fake_logit": s,
        "D_probability": p,
        "original_minimax_G_loss_log1_minus_D": -softplus_scalar(s),
        "original_minimax_dloss_dlogit": -p,
        "non_saturating_G_loss_minus_log_D": softplus_scalar(-s),
        "non_saturating_dloss_dlogit": p - 1.0,
    })

checks = {
    "D_manual_chainrule_matches_autograd": all(abs(d_grads_torch[k] - v) < 1e-12 for k, v in {"w": d_dw_manual, "b": d_db_manual}.items()),
    "D_central_difference_matches_manual": abs(d_w_fd - d_dw_manual) < 1e-7 and abs(d_b_fd - d_db_manual) < 1e-7,
    "D_scalar_SGD_updates_match": all(abs(d_after[k] - d_update_expected[k]) < 1e-14 for k in d_after),
    "G_manual_chainrule_matches_autograd": abs(g_grads_torch["a"] - g_da_manual) < 1e-12 and abs(g_grads_torch["c"] - g_dc_manual) < 1e-12,
    "G_central_difference_matches_manual": abs(g_a_fd - g_da_manual) < 1e-7 and abs(g_c_fd - g_dc_manual) < 1e-7,
    "G_scalar_SGD_updates_match": all(abs(g_after[k] - g_update_expected[k]) < 1e-14 for k in g_after),
    "G_gradients_absent_and_params_unchanged_during_D_step": g_grads_none_after_d and g_params_after_d == {"a": a0, "c": c0},
    "D_grad_none_and_unchanged_by_G_step": D.w.grad is None and D.b.grad is None and d_after == {"w": f(D.w), "b": f(D.b)},
}
assert all(checks.values()), checks

result = {
    "scope": "Fixed scalar GAN gradient/update mechanics only; no data training, neural-network image generation, convergence, quality, or benchmark claims.",
    "environment": {"python": platform.python_version(), "torch": torch.__version__, "device": "cpu", "dtype": "float64", "randomness": "none"},
    "inputs": {"z": z.tolist(), "real": real.tolist(), "G_initial": {"a": a0, "c": c0}, "D_initial": {"w": w0, "b": b0}},
    "discriminator_step": {
        "loss_definition": "mean BCEWithLogits(real, 1) + mean BCEWithLogits(fake.detach(), 0)",
        "separate_real_mean": f(d_real_loss), "separate_fake_mean": f(d_fake_loss), "summed_loss": f(d_loss),
        "before": d_before, "grad_autograd": d_grads_torch,
        "grad_manual_chainrule": {"w": d_dw_manual, "b": d_db_manual},
        "grad_central_difference": {"w": d_w_fd, "b": d_b_fd},
        "learning_rate": D_LR, "expected_after": d_update_expected, "actual_after": d_after,
        "G_grads_after_D_step": {"a": None, "c": None},
        "G_parameters_after_D_step": g_params_after_d,
    },
    "generator_step": {
        "loss_definition": "mean BCEWithLogits(D(G(z)), 1), the non-saturating objective; D parameters frozen but forward path differentiable",
        "loss": f(g_loss), "D_fixed_at": {"w": w1, "b": b1},
        "before": g_before, "grad_autograd": g_grads_torch,
        "grad_manual_chainrule": {"a": g_da_manual, "c": g_dc_manual},
        "grad_central_difference": {"a": g_a_fd, "c": g_c_fd},
        "learning_rate": G_LR, "expected_after": g_update_expected, "actual_after": g_after,
        "D_grads_after_G_step": {"w": None, "b": None},
        "D_parameters_after_G_step": {"w": f(D.w), "b": f(D.b)},
    },
    "logit_gradient_comparison": logit_comparison,
    "checks": checks,
}
print(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False))
