"""Plot G (with face source {0, 1, 6} producing T iso[2] at n=7 via Def 2.4)
alongside T itself, to show the relationship."""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from triangulation_gen import enumerate_all_triangulations


def main():
    n = 7
    target_idx = 2
    isos = enumerate_all_triangulations(n)
    T = isos[target_idx]

    # Constructed G: source face {0, 1, 6}, stacked from vertex 0
    G_edges = [
        (0, 1), (1, 6), (0, 6),   # source face
        (0, 2), (1, 2), (2, 6),   # 2 inside (0, 1, 6)
        (0, 3), (1, 3), (2, 3),   # 3 inside (0, 1, 2)
        (0, 4), (2, 4), (3, 4),   # 4 inside (0, 2, 3)
        (0, 5), (3, 5), (4, 5),   # 5 inside (0, 3, 4)
    ]
    G = nx.Graph(); G.add_edges_from(G_edges)
    print(f"G edges: {sorted(G.edges())}")
    print(f"G has {G.number_of_edges()} edges (need {3*n - 6})")
    ip_g, emb_g = nx.check_planarity(G)
    print(f"G planar: {ip_g}")

    # BFS levels from {0, 1, 6}
    from level_cycles import compute_levels
    source = {0, 1, 6}
    G_levels = compute_levels(G, source)
    print(f"G BFS levels: {sorted(G_levels.items())}")

    # Apply G's levels to T
    even = [v for v in T.nodes() if G_levels[v] % 2 == 0]
    odd = [v for v in T.nodes() if G_levels[v] % 2 == 1]
    print(f"T even subgraph on {sorted(even)}: edges "
          f"{sorted(T.subgraph(even).edges())}, "
          f"bipartite: {nx.is_bipartite(T.subgraph(even))}")
    print(f"T odd subgraph on {sorted(odd)}: edges "
          f"{sorted(T.subgraph(odd).edges())}, "
          f"bipartite: {nx.is_bipartite(T.subgraph(odd))}")

    # Edges in G but not T, and vice versa
    Ge = set(frozenset(e) for e in G.edges())
    Te = set(frozenset(e) for e in T.edges())
    only_G = Ge - Te
    only_T = Te - Ge
    print(f"Edges only in G: {sorted(only_G)}")
    print(f"Edges only in T: {sorted(only_T)}")

    # Use the face-area-balanced planar layout from balanced_layout.py.
    from balanced_layout import balanced_planar_layout
    outer_face = (0, 1, 6)
    pos = balanced_planar_layout(G, outer_face, n_explore=4000, n_refine=2000)

    fig, axes = plt.subplots(1, 2, figsize=(15, 7))

    level_color = {0: '#3b82f6', 1: '#f59e0b'}

    def draw(ax, graph, title, highlight_edges=None, missing_edges=None):
        # Edges of this graph
        for u, v in graph.edges():
            if highlight_edges and frozenset([u, v]) in highlight_edges:
                ax.plot([pos[u][0], pos[v][0]], [pos[u][1], pos[v][1]],
                        color='#22c55e', linewidth=3.5, zorder=2,
                        linestyle='-')
            else:
                ax.plot([pos[u][0], pos[v][0]], [pos[u][1], pos[v][1]],
                        color='#444', linewidth=1.5, zorder=2)
        # Show missing edges as faint dashed
        if missing_edges:
            for (u, v) in missing_edges:
                ax.plot([pos[u][0], pos[v][0]], [pos[u][1], pos[v][1]],
                        color='#ef4444', linewidth=1.5, zorder=1.5,
                        linestyle=':', alpha=0.5)
        # Vertices colored by G-level
        for v in graph.nodes():
            ax.scatter(pos[v][0], pos[v][1],
                       c=level_color[G_levels[v]], s=900,
                       edgecolors='black', linewidths=2.0, zorder=3)
            ax.text(pos[v][0], pos[v][1],
                    f"{v}\n$L_{{{G_levels[v]}}}$",
                    fontsize=12, ha='center', va='center',
                    fontweight='bold', zorder=4)
        ax.set_title(title, fontsize=12)
        ax.set_aspect('equal'); ax.axis('off')

    draw(axes[0], G,
         f"$G$: triangulation with face source $S = \\{{0, 1, 6\\}}$\n"
         f"Green = edges that are in $G$ but not in $T$",
         highlight_edges=only_G,
         missing_edges=only_T)
    draw(axes[1], T,
         f"$T$: the target (iso[2] at $n = 7$). G-levels applied.\n"
         f"Even subgraph bipartite: True; odd subgraph bipartite: True\n"
         f"(Red dotted = edges in $T$ but not $G$.)",
         missing_edges=only_G)

    plt.suptitle(
        "$T$ as a level resolution of $G$ (Def 2.4) — partition cardinality "
        "$(|L_0|, |L_1|) = (3, 4)$.\n"
        "Both parity subgraphs of $T$ under $G$'s levels are bipartite. "
        "The algorithm of \\S5 does not produce $T$ from $(G, S)$, however.",
        fontsize=12, y=1.02
    )
    plt.tight_layout()
    out = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                        '..', f'G_for_T_n{n}_idx{target_idx}.png')
    plt.savefig(out, dpi=130, bbox_inches='tight')
    print(f"saved: {out}")


if __name__ == "__main__":
    main()
