#!/usr/bin/env python3
"""
Independent exact-arithmetic check of the canonical regular icosahedron definitions
in Mikhail Levit's Lean 4 formalization (lean/Icosahedron/Defs.lean, commit f2539dbc).
Verifies in exact Z[phi] arithmetic (phi^2 = phi + 1):
  1. All 12 vertices in vtxCode are distinct.
  2. Exactly 30 pairs have squared Euclidean distance 4 (edge length 2).
  3. Every vertex has degree 5 in the edge graph.
  4. The 20 triples in faceIdx coincide exactly with the 20 triangles of the edge graph.
"""

vtx_code = [
    [(0, 0), (1, 0), (0, 1)],
    [(1, 0), (0, 1), (0, 0)],
    [(0, 1), (0, 0), (1, 0)],
    [(0, 0), (1, 0), (0, -1)],
    [(1, 0), (0, -1), (0, 0)],
    [(0, 1), (0, 0), (-1, 0)],
    [(0, 0), (-1, 0), (0, 1)],
    [(-1, 0), (0, 1), (0, 0)],
    [(0, -1), (0, 0), (1, 0)],
    [(0, 0), (-1, 0), (0, -1)],
    [(-1, 0), (0, -1), (0, 0)],
    [(0, -1), (0, 0), (-1, 0)],
]

face_idx = [
    (0, 1, 2), (0, 1, 7), (0, 2, 6), (0, 6, 8), (0, 7, 8),
    (1, 2, 5), (1, 3, 5), (1, 3, 7), (2, 4, 5), (2, 4, 6),
    (3, 5, 9), (3, 7, 11), (3, 9, 11), (4, 5, 9), (4, 6, 10),
    (4, 9, 10), (6, 8, 10), (7, 8, 11), (8, 10, 11), (9, 10, 11),
]


def sq_dist_zphi(u, v):
    """Exact squared Euclidean distance in Z[phi], represented as (a, b) for a + b*phi."""
    a, b = 0, 0
    for (a1, b1), (a2, b2) in zip(u, v):
        da, db = a1 - a2, b1 - b2
        # (da + db*phi)^2 = da^2 + 2*da*db*phi + db^2*(1 + phi)
        a += da * da + db * db
        b += 2 * da * db + db * db
    return (a, b)


def main():
    assert len(vtx_code) == 12
    assert len({tuple(v) for v in vtx_code}) == 12, "Vertices not distinct"

    edges = set()
    dists = {}
    for i in range(12):
        for j in range(i + 1, 12):
            d2 = sq_dist_zphi(vtx_code[i], vtx_code[j])
            dists[d2] = dists.get(d2, 0) + 1
            if d2 == (4, 0):
                edges.add((i, j))

    assert len(edges) == 30, f"Expected 30 edges, got {len(edges)}"
    degrees = [sum(1 for e in edges if i in e) for i in range(12)]
    assert degrees == [5] * 12, f"Unexpected vertex degrees: {degrees}"

    triangles = {
        (i, j, k)
        for i in range(12)
        for j in range(i + 1, 12)
        for k in range(j + 1, 12)
        if (i, j) in edges and (i, k) in edges and (j, k) in edges
    }
    assert len(triangles) == 20, f"Expected 20 triangles, got {len(triangles)}"
    assert triangles == set(face_idx), "faceIdx does not match triangles of edge graph"

    print("PASS: vtxCode defines 12 distinct vertices of a regular icosahedron (edge length 2).")
    print("Pairwise squared distance multiplicities in Z[phi]:", sorted(dists.items()))
    print("PASS: 30 edges, all 12 vertex degrees = 5, 20 triangles match faceIdx exactly.")


if __name__ == "__main__":
    main()
