"""Week 13: Weighted graphs. Dijkstra, Bellman-Ford, topological sort, union-find, Kruskal, Prim."""
from __future__ import annotations

import heapq
from collections import defaultdict, deque
from typing import Dict, Hashable, List, Optional, Tuple

Edge = Tuple[Hashable, Hashable, float]


def dijkstra(edges: List[Edge], source: Hashable, directed: bool = True) -> Dict[Hashable, float]:
    """Shortest distances from source with non-negative weights. O((V + E) log V)."""
    adj = defaultdict(list)
    for u, v, w in edges:
        if w < 0:
            raise ValueError("Dijkstra needs non-negative weights; use bellman_ford")
        adj[u].append((v, w))
        if not directed:
            adj[v].append((u, w))
    dist: Dict[Hashable, float] = {}
    heap = [(0, source)]
    while heap:
        d, u = heapq.heappop(heap)
        if u in dist:
            continue  # stale entry
        dist[u] = d
        for v, w in adj[u]:
            if v not in dist:
                heapq.heappush(heap, (d + w, v))
    return dist


def bellman_ford(nodes: List[Hashable], edges: List[Edge], source: Hashable) -> Optional[Dict[Hashable, float]]:
    """Handles negative weights. Returns None if a negative cycle is reachable. O(V * E)."""
    dist = {n: float("inf") for n in nodes}
    dist[source] = 0
    for _ in range(len(nodes) - 1):
        changed = False
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            return None
    return dist


def topological_sort(nodes: List[Hashable], edges: List[Tuple[Hashable, Hashable]]) -> Optional[List[Hashable]]:
    """Kahn's algorithm. Returns None when the graph has a cycle."""
    adj = defaultdict(list)
    indegree = {n: 0 for n in nodes}
    for u, v in edges:
        adj[u].append(v)
        indegree[v] += 1
    queue = deque(n for n in nodes if indegree[n] == 0)
    order = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in adj[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                queue.append(v)
    return order if len(order) == len(nodes) else None


class UnionFind:
    """Disjoint set union with path compression and union by size: near O(1) per operation."""

    def __init__(self, items=()):
        self.parent: Dict[Hashable, Hashable] = {}
        self.size: Dict[Hashable, int] = {}
        self.components = 0
        for x in items:
            self.add(x)

    def add(self, x: Hashable) -> None:
        if x not in self.parent:
            self.parent[x] = x
            self.size[x] = 1
            self.components += 1

    def find(self, x: Hashable) -> Hashable:
        self.add(x)
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:  # path compression
            self.parent[x], x = root, self.parent[x]
        return root

    def union(self, a: Hashable, b: Hashable) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        self.components -= 1
        return True

    def connected(self, a: Hashable, b: Hashable) -> bool:
        return self.find(a) == self.find(b)


def kruskal(nodes: List[Hashable], edges: List[Edge]) -> Tuple[float, List[Edge]]:
    """Minimum spanning tree (or forest): sort edges, add each one that joins two components."""
    uf = UnionFind(nodes)
    total, chosen = 0, []
    for u, v, w in sorted(edges, key=lambda e: e[2]):
        if uf.union(u, v):
            total += w
            chosen.append((u, v, w))
    return total, chosen


def prim(nodes: List[Hashable], edges: List[Edge]) -> float:
    """MST weight with a heap, starting from nodes[0]. Assumes a connected graph."""
    if not nodes:
        return 0
    adj = defaultdict(list)
    for u, v, w in edges:
        adj[u].append((w, v))
        adj[v].append((w, u))
    seen = {nodes[0]}
    heap = list(adj[nodes[0]])
    heapq.heapify(heap)
    total = 0
    while heap and len(seen) < len(nodes):
        w, v = heapq.heappop(heap)
        if v in seen:
            continue
        seen.add(v)
        total += w
        for item in adj[v]:
            if item[1] not in seen:
                heapq.heappush(heap, item)
    if len(seen) != len(nodes):
        raise ValueError("graph is not connected")
    return total
