"""Kruskal's minimum spanning tree.

Idea
----
Sort all edges by weight and add them one by one, skipping any edge whose two
ends are already connected (it would form a cycle). A union-find structure
answers "already connected?" in near-constant time. The greedy choice is safe
because of the cut property: the lightest edge crossing any cut belongs to
some minimum spanning tree.

Complexity
----------
Time:  O(E log E) for sorting; union-find work is almost linear
Space: O(V)
"""

from collections.abc import Hashable, Iterable, Sequence
from typing import TypeVar

from algorithms.data_structures.union_find import UnionFind

N = TypeVar("N", bound=Hashable)


def kruskal(
    nodes: Iterable[N], edges: Sequence[tuple[N, N, float]]
) -> tuple[float, list[tuple[N, N, float]]]:
    """Return ``(total_weight, chosen_edges)`` of a minimum spanning forest."""
    uf = UnionFind(nodes)
    chosen: list[tuple[N, N, float]] = []
    total = 0.0
    for u, v, w in sorted(edges, key=lambda e: e[2]):
        if uf.union(u, v):
            chosen.append((u, v, w))
            total += w
    return total, chosen
