"""k-means (with k-means++ initialization) and k-nearest neighbors."""
import math
import random
from collections import Counter


def sq_dist(a, b):
    return sum((x - y) ** 2 for x, y in zip(a, b))


def kmeans(points, k, iters=100, seed=0):
    """Returns (centroids, labels). Lloyd's algorithm: assign to nearest centroid, move centroids to means."""
    rng = random.Random(seed)
    # k-means++: spread initial centroids out, picking far points with higher probability.
    centroids = [list(rng.choice(points))]
    while len(centroids) < k:
        d2 = [min(sq_dist(p, c) for c in centroids) for p in points]
        r, acc = rng.random() * sum(d2), 0.0
        for p, w in zip(points, d2):
            acc += w
            if acc >= r:
                centroids.append(list(p))
                break
    labels = [0] * len(points)
    for _ in range(iters):
        new_labels = [min(range(k), key=lambda c: sq_dist(p, centroids[c])) for p in points]
        for c in range(k):
            members = [p for p, lab in zip(points, new_labels) if lab == c]
            if members:  # keep an empty cluster's centroid where it was
                centroids[c] = [sum(col) / len(members) for col in zip(*members)]
        if new_labels == labels:
            break
        labels = new_labels
    return centroids, labels


def inertia(points, centroids, labels):
    return sum(sq_dist(p, centroids[lab]) for p, lab in zip(points, labels))


def knn_predict(train_X, train_y, x, k=3):
    """Majority vote among the k closest training points (ties broken by the nearest neighbor's label)."""
    nearest = sorted(range(len(train_X)), key=lambda i: sq_dist(train_X[i], x))[:k]
    votes = Counter(train_y[i] for i in nearest)
    top = max(votes.values())
    for i in nearest:
        if votes[train_y[i]] == top:
            return train_y[i]


def euclidean(a, b):
    return math.sqrt(sq_dist(a, b))
