"""Verify that every level subgraph L_k is outerplanar across n=6..10."""
import sys; sys.path.insert(0, '/home/claude/build')
import networkx as nx
from collections import defaultdict
from triangulation_gen import enumerate_all_triangulations
from level_cycles import compute_levels, level_sources


def is_outerplanar(G):
    """Outerplanar iff no K_4 minor and no K_{2,3} minor.
    Equivalently: planar AND can add a new vertex connected to all existing
    vertices while remaining planar."""
    if G.number_of_nodes() <= 3:
        return True
    H = G.copy()
    apex = max(H.nodes()) + 1
    for v in G.nodes():
        H.add_edge(apex, v)
    return nx.check_planarity(H)[0]


# Check on a sample of triangulations
results = defaultdict(int)  # (n, outerplanar) -> count
non_outerplanar_examples = []

for n in [6, 7, 8, 9, 10]:
    reps = enumerate_all_triangulations(n)
    for gi, G in enumerate(reps):
        ip, emb = nx.check_planarity(G)
        if not ip: continue
        for kind, label, source_set in level_sources(G, emb):
            levels = compute_levels(G, source_set)
            level_groups = defaultdict(list)
            for v, lv in levels.items():
                level_groups[lv].append(v)
            for k, verts in level_groups.items():
                Lk = G.subgraph(verts)
                op = is_outerplanar(Lk)
                results[(n, op)] += 1
                if not op and len(non_outerplanar_examples) < 5:
                    non_outerplanar_examples.append({
                        'n': n, 'G_idx': gi,
                        'source': (kind, label),
                        'level': k,
                        'L_k_edges': list(Lk.edges()),
                        'L_k_nodes': verts,
                    })
                    print(f"  Non-outerplanar L_{k} at n={n}, T{gi}, "
                          f"source={kind} {label}: {verts}, edges={list(Lk.edges())}")

print(f"\nSummary:")
for n in [6, 7, 8, 9, 10]:
    op = results[(n, True)]
    nop = results[(n, False)]
    print(f"  n={n}: {op} outerplanar, {nop} non-outerplanar level subgraphs")
