"""Small deterministic examples for global, local, and causal questions.

This script does not fit a model or estimate an effect from real data.
"""

import json


def f(x, z):
    return x + 2 * z + 3 * x * z


def mse(actual, predicted):
    return sum((a - p) ** 2 for a, p in zip(actual, predicted)) / len(actual)


def main():
    # Observed support contains only (x, z) = (0, 0) and (1, 1), equally often.
    observed = [(0, 0), (0, 0), (1, 1), (1, 1)]
    pdp = {}
    ice = {}
    for x in (0, 1):
        by_z = {z: f(x, z) for z in (0, 1)}
        pdp[str(x)] = sum(by_z.values()) / 2
    for z in (0, 1):
        ice[str(z)] = {str(x): f(x, z) for x in (0, 1)}

    # Exact duplicate predictors: the fitted toy rule relies on x1 only.
    x1 = [0, 0, 1, 1]
    x2 = [0, 0, 1, 1]
    y = [0, 0, 1, 1]
    baseline_pred = list(x1)
    x1_shuffled = [1, 1, 0, 0]
    x2_shuffled = [1, 0, 0, 1]
    perm_x1_pred = list(x1_shuffled)
    perm_x2_pred = list(x1)  # The fixed model ignores x2.

    # Paired deterministic SCMs. Both have observational U -> X and X == Y.
    # The intervention replaces X's structural equation and holds U fixed.
    u_values = (0, 1)
    observational = [(u, u) for u in u_values]
    scm_a_do = {str(x): sum(u for u in u_values) / 2 for x in (0, 1)}
    scm_b_do = {str(x): float(x) for x in (0, 1)}

    result = {
        "scope": "hand-specified deterministic arithmetic; no fitting, real data, or effect estimation",
        "global_vs_individual": {
            "model": "f(x,z)=x+2z+3xz",
            "observed_support_rows": [
                {"x": x, "z": z, "weight": 0.25, "f": f(x, z)}
                for x, z in observed
            ],
            "support_note": "Observed support has x=z only. PDP values at x!=z require model evaluation off observed support.",
            "pdp_equal_weight_z": pdp,
            "pdp_slope_from_x0_to_x1": pdp["1"] - pdp["0"],
            "ice_by_fixed_z": ice,
            "ice_slopes_from_x0_to_x1": {
                z: curve["1"] - curve["0"] for z, curve in ice.items()
            },
        },
        "single_fixed_permutation_example": {
            "rows": [
                {"x1": x1[i], "x2": x2[i], "y": y[i]}
                for i in range(len(y))
            ],
            "fixed_model": "prediction=x1",
            "metric": "mean squared error on these four rows",
            "baseline_mse": mse(y, baseline_pred),
            "one_fixed_x1_permutation": x1_shuffled,
            "x1_permuted_mse": mse(y, perm_x1_pred),
            "x1_permutation_score_drop": mse(y, perm_x1_pred) - mse(y, baseline_pred),
            "one_fixed_x2_permutation": x2_shuffled,
            "x2_permuted_mse": mse(y, perm_x2_pred),
            "x2_permutation_score_drop": mse(y, perm_x2_pred) - mse(y, baseline_pred),
            "scope_note": "One fixed shuffle for one fixed model and metric; not an uncertainty estimate, a universal feature value, or a causal effect. x2 duplicates x1 in these rows, but this fitted rule reads x1 only.",
        },
        "observationally_indistinguishable_scms": {
            "exogenous_support": [{"u": u, "probability": 0.5} for u in u_values],
            "scm_a": "X=U; Y=U (no structural dependence of Y on X)",
            "scm_b": "X=U; Y=X",
            "shared_observational_joint_xy": [
                {"x": x, "y": y_value, "probability": 0.5}
                for x, y_value in observational
            ],
            "mean_y_under_do_x": {
                "scm_a": scm_a_do,
                "scm_b": scm_b_do,
            },
            "do_effect_mean_y_x1_minus_x0": {
                "scm_a": scm_a_do["1"] - scm_a_do["0"],
                "scm_b": scm_b_do["1"] - scm_b_do["0"],
            },
            "scope_note": "These are two explicitly assumed structures with the same observational distribution and different intervention effects; they show non-identification from that distribution alone, not an effect learned from data.",
        },
    }
    assert result["global_vs_individual"]["pdp_slope_from_x0_to_x1"] == 2.5
    assert result["global_vs_individual"]["ice_slopes_from_x0_to_x1"] == {"0": 1, "1": 4}
    assert result["single_fixed_permutation_example"]["baseline_mse"] == 0
    assert result["single_fixed_permutation_example"]["x1_permuted_mse"] == 1
    assert result["single_fixed_permutation_example"]["x2_permuted_mse"] == 0
    assert result["observationally_indistinguishable_scms"]["do_effect_mean_y_x1_minus_x0"] == {
        "scm_a": 0.0,
        "scm_b": 1.0,
    }
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
