"""Inspect iso-class 5 at n=8 to see what's structurally special."""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import networkx as nx
from collections import Counter
from triangulation_gen import enumerate_all_triangulations


isos = enumerate_all_triangulations(8)
T5 = isos[5]
print(f"iso-class 5 at n=8:")
print(f"  vertices: {sorted(T5.nodes())}")
print(f"  edges:    {sorted(T5.edges())}")
print(f"  degree sequence: {sorted([T5.degree(v) for v in T5.nodes()], reverse=True)}")
print(f"  min degree: {min(T5.degree(v) for v in T5.nodes())}")

ip, emb = nx.check_planarity(T5)
print(f"  planar: {ip}")

# What face cycles exist?
faces = []
seen = set()
for v in emb.nodes():
    for w in emb[v]:
        if (v, w) not in seen:
            f = emb.traverse_face(v, w)
            for i in range(len(f)):
                seen.add((f[i], f[(i+1) % len(f)]))
            faces.append(f)
print(f"  face lengths: {Counter(len(f) for f in faces)}")

# Check 4-colorability and best matching
def four_color(G):
    """Greedy 4-coloring."""
    colors = {}
    for v in nx.nodes(G):
        used = {colors[u] for u in G.neighbors(v) if u in colors}
        for c in range(4):
            if c not in used:
                colors[v] = c; break
    return colors

# Check whether iso 5 can be 4-colored
try:
    col = four_color(T5)
    sizes = Counter(col.values())
    print(f"  greedy 4-coloring sizes: {sizes}")
except Exception as e:
    print(f"  4-coloring failed: {e}")

# Comparison: print all 14 iso-classes' degree sequences
print(f"\nAll iso-classes at n=8 (degree sequences, sorted):")
for i, T in enumerate(isos):
    ds = tuple(sorted([T.degree(v) for v in T.nodes()], reverse=True))
    marker = " <-- missing" if i in [5] else ""
    print(f"  {i:2d}: {ds}{marker}")

# Now check if any algorithm output has degree sequence (6,6,6,5,4,3,3,3)
print(f"\nChecking algorithm outputs at n=8 for target degree sequence...")
from level_cycles import level_sources, compute_levels
from simple_level_resolution_coverage import simple_level_resolutions, is_triangulation
target_ds = tuple(sorted([T5.degree(v) for v in T5.nodes()], reverse=True))
found = 0
total = 0
for src_idx, G in enumerate(isos):
    ip, emb = nx.check_planarity(G)
    if not ip:
        continue
    for kind, label, source_set in level_sources(G, emb):
        for Gp in simple_level_resolutions(G, source_set):
            total += 1
            if not is_triangulation(Gp, 8):
                continue
            ds = tuple(sorted([Gp.degree(v) for v in Gp.nodes()], reverse=True))
            if ds == target_ds:
                found += 1
                if found <= 3:
                    print(f"  found! src={src_idx} source={label}")
                    print(f"  Gp edges: {sorted(Gp.edges())}")
print(f"total outputs: {total}, with target degree sequence: {found}")
