import networkx as nx
from graph_algorithms import kruskal_mst, prim_mst

def edges_to_nx_graph(n, edges):
    G = nx.Graph()
    G.add_nodes_from(range(n))
    for u, v, w in edges:
        G.add_edge(u, v, weight=w)
    return G

def total_weight_from_nx_mst(nx_mst):
    return sum(d["weight"] for _,_,d in nx_mst.edges(data=True))

def test_kruskal_prim_match_networkx():
    edges = [
        (0,1,1.5),
        (0,2,1.0),
        (1,3,2.0),
        (2,3,1.0),
        (1,2,0.5)
    ]
    n = 4
    mst_k, w_k = kruskal_mst(n, edges)
    mst_p, w_p = prim_mst(n, edges)

    G = edges_to_nx_graph(n, edges)
    nx_mst = nx.minimum_spanning_tree(G)
    w_nx = total_weight_from_nx_mst(nx_mst)

    assert abs(w_k - w_nx) < 1e-8
    assert abs(w_p - w_nx) < 1e-8