"""Impurity measures and the best split search used by decision trees."""
import math
from collections import Counter


def gini(labels):
    n = len(labels)
    return 1 - sum((c / n) ** 2 for c in Counter(labels).values()) if n else 0.0


def entropy(labels):
    n = len(labels)
    return -sum((c / n) * math.log2(c / n) for c in Counter(labels).values()) if n else 0.0


def information_gain(parent, left, right, impurity=entropy):
    n = len(parent)
    return impurity(parent) - (len(left) / n) * impurity(left) - (len(right) / n) * impurity(right)


def best_split(X, y, impurity=gini):
    """Try every feature and threshold (midpoints between sorted unique values).

    Returns (feature, threshold, weighted_impurity) for the split x[feature] <= threshold.
    """
    best = (None, None, impurity(y))
    n = len(y)
    for f in range(len(X[0])):
        values = sorted({row[f] for row in X})
        for lo, hi in zip(values, values[1:]):
            t = (lo + hi) / 2
            left = [lab for row, lab in zip(X, y) if row[f] <= t]
            right = [lab for row, lab in zip(X, y) if row[f] > t]
            score = len(left) / n * impurity(left) + len(right) / n * impurity(right)
            if score < best[2]:
                best = (f, t, score)
    return best
