"""Show a valid parity partition of iso[49] at n=9, with the induced
4-coloring."""
import sys
import os
sys.path.insert(0, '/Users/didericis/Code/math-research/papers/'
                'level_resolutions_of_maximal_planar_graphs/experiments')
import networkx as nx
import matplotlib.pyplot as plt
from triangulation_gen import enumerate_all_triangulations

OUT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

tris = enumerate_all_triangulations(9)
G = tris[49]

V_E = (0, 1, 3, 6)
V_O = (2, 4, 5, 7, 8)

# 2-color each induced subgraph
def bipart_coloring(subg):
    # BFS-based 2-coloring; returns dict v -> 0/1
    cmap = {}
    for start in subg.nodes():
        if start in cmap: continue
        cmap[start] = 0
        frontier = [start]
        while frontier:
            new = []
            for u in frontier:
                for w in subg.neighbors(u):
                    if w not in cmap:
                        cmap[w] = 1 - cmap[u]
                        new.append(w)
            frontier = new
    return cmap

cE = bipart_coloring(G.subgraph(V_E))
cO = bipart_coloring(G.subgraph(V_O))
# 4-color: even gets red/blue, odd gets yellow/green
COLOR_RED, COLOR_BLUE = '#dc2626', '#3b82f6'
COLOR_YELLOW, COLOR_GREEN = '#eab308', '#16a34a'
four_color = {}
for v in V_E:
    four_color[v] = COLOR_RED if cE[v] == 0 else COLOR_BLUE
for v in V_O:
    four_color[v] = COLOR_YELLOW if cO[v] == 0 else COLOR_GREEN

# Verify proper 4-coloring
for u, v in G.edges():
    assert four_color[u] != four_color[v], \
        f'edge ({u},{v}) violates 4-coloring: {four_color[u]} vs {four_color[v]}'
print('4-coloring is proper.')

_, emb = nx.check_planarity(G)
pos = nx.combinatorial_embedding_to_pos(emb)

fig, ax = plt.subplots(figsize=(9, 8))
nx.draw_networkx_edges(G, pos, ax=ax, edge_color='#333', width=1.5)
node_colors = [four_color[v] for v in G.nodes()]
nx.draw_networkx_nodes(G, pos, ax=ax, node_color=node_colors,
                       node_size=700, edgecolors='black', linewidths=1.3)
nx.draw_networkx_labels(G, pos, ax=ax, font_color='white',
                        font_size=12, font_weight='bold')
ax.set_aspect('equal'); ax.axis('off')

# Legend
import matplotlib.patches as mpatches
legend_handles = [
    mpatches.Patch(color=COLOR_RED, label=r'even-parity vertex, bipartition class 0'),
    mpatches.Patch(color=COLOR_BLUE, label=r'even-parity vertex, bipartition class 1'),
    mpatches.Patch(color=COLOR_YELLOW, label=r'odd-parity vertex, bipartition class 0'),
    mpatches.Patch(color=COLOR_GREEN, label=r'odd-parity vertex, bipartition class 1'),
]
ax.legend(handles=legend_handles, loc='lower center',
          bbox_to_anchor=(0.5, -0.08), ncol=2, fontsize=9, frameon=False)

ax.set_title(f'iso[49] with a valid parity partition\n'
             f'$V_E = \\{{0, 1, 3, 6\\}}$, '
             f'$V_O = \\{{2, 4, 5, 7, 8\\}}$\n'
             f'(both induced subgraphs bipartite; 4-coloring derived)',
             fontsize=11)
fig.tight_layout()
out = os.path.join(OUT_DIR, 'fig_n9_valid_partition.png')
fig.savefig(out, dpi=180, bbox_inches='tight')
plt.close(fig)
print(f'wrote {out}')

# Also report the induced subgraphs
GE = G.subgraph(V_E)
GO = G.subgraph(V_O)
print(f'G[V_E] = {sorted(GE.edges())}  bipartite={nx.is_bipartite(GE)}')
print(f'G[V_O] = {sorted(GO.edges())}  bipartite={nx.is_bipartite(GO)}')
