"""Exact two-feature attribution games; no SHAP library or model fitting.

Marginal replacement and observational conditioning define different games.
Neither operation is a causal intervention in this example.
"""

from fractions import Fraction as F
from itertools import permutations
import json


BACKGROUND = ((0, 0), (1, 1))
TARGET = (1, 1)


def value(model, coalition, mode, background):
    if mode == "conditional":
        matching = [row for row in background
                    if all(row[j] == TARGET[j] for j in coalition)]
        if not matching:
            raise ValueError("No observed support for this conditioning event")
        return sum((F(model(*row)) for row in matching), F(0)) / len(matching)
    if mode != "marginal":
        raise ValueError("Unknown game")
    predictions = []
    for row in background:
        combined = tuple(TARGET[j] if j in coalition else row[j] for j in (0, 1))
        predictions.append(F(model(*combined)))
    return sum(predictions, F(0)) / len(predictions)


def explain(name, model, mode, background):
    coalitions = (frozenset(), frozenset({0}), frozenset({1}), frozenset({0, 1}))
    game = {s: value(model, s, mode, background) for s in coalitions}
    contributions = [F(0), F(0)]
    orders = []
    for order in permutations((0, 1)):
        known = frozenset()
        increments = []
        for j in order:
            expanded = known | {j}
            increment = game[expanded] - game[known]
            contributions[j] += increment / 2
            increments.append(str(increment))
            known = expanded
        orders.append({"order": list(order), "increments_in_order": increments})
    base = game[frozenset()]
    prediction = F(model(*TARGET))
    assert base + sum(contributions, F(0)) == prediction
    return {
        "model": name, "game": mode, "background_rows_equal_mass": list(background),
        "target": TARGET,
        "coalition_values": {"empty" if not s else "+".join(str(j) for j in sorted(s)): str(v)
                             for s, v in game.items()},
        "orders": orders, "base": str(base), "phi": [str(v) for v in contributions],
        "prediction": str(prediction), "base_plus_phi_exact": str(base + sum(contributions)),
    }


def main():
    interaction = lambda x, z: x + 2*z + 3*x*z
    reads_x_only = lambda x, z: x
    cases = [
        explain("x+2z+3xz", interaction, "marginal", ((0, 0),)),
        explain("x+2z+3xz", interaction, "marginal", BACKGROUND),
        explain("x+2z+3xz", interaction, "conditional", BACKGROUND),
        explain("x (z unused by model)", reads_x_only, "marginal", BACKGROUND),
        explain("x (z unused by model)", reads_x_only, "conditional", BACKGROUND),
    ]
    print(json.dumps({
        "scope": "Exact enumeration of hand-specified two-feature games; no fitted explainer, uncertainty estimate, or causal effect",
        "feature_indices": {"0": "x", "1": "z"},
        "conditional_scope": "Only explicit finite background support; conditioning events used here have positive mass",
        "cases": cases,
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
