"""Plot the missing iso (n=7 iso[2]) with a proper 4-coloring."""
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, target_idx = 7, 2
    isos = enumerate_all_triangulations(n)
    T = isos[target_idx]

    # 4-coloring
    coloring = {0: 'A', 1: 'B', 2: 'C', 3: 'D',
                4: 'D', 5: 'C', 6: 'B'}
    color_to_hex = {'A': '#ef4444', 'B': '#3b82f6',
                     'C': '#22c55e', 'D': '#f59e0b'}

    # Verify
    for u, v in T.edges():
        assert coloring[u] != coloring[v], f"Edge ({u},{v}) is monochromatic!"
    print("4-coloring verified proper.")

    # Layout: planar with source face on outside
    pos = nx.planar_layout(T)
    centroid = np.mean(list(pos.values()), axis=0)
    for v in pos:
        pos[v] = (pos[v] - centroid) * 1.5

    fig, ax = plt.subplots(1, 1, figsize=(8, 8))
    nx.draw_networkx_edges(T, pos, ax=ax, edge_color='#333', width=2.0)
    for v in T.nodes():
        ax.scatter(pos[v][0], pos[v][1],
                   c=color_to_hex[coloring[v]], s=900,
                   edgecolors='black', linewidths=2.0, zorder=3)
        ax.text(pos[v][0], pos[v][1], f"{v}\n({coloring[v]})",
                fontsize=12, ha='center', va='center',
                fontweight='bold', zorder=4)

    # Add a legend
    from matplotlib.patches import Patch
    legend_elements = [
        Patch(facecolor=color_to_hex['A'], edgecolor='black',
              label='A (1 vertex)'),
        Patch(facecolor=color_to_hex['B'], edgecolor='black',
              label='B (2 vertices)'),
        Patch(facecolor=color_to_hex['C'], edgecolor='black',
              label='C (2 vertices)'),
        Patch(facecolor=color_to_hex['D'], edgecolor='black',
              label='D (2 vertices)'),
    ]
    ax.legend(handles=legend_elements, loc='upper right', fontsize=11)

    ax.set_title(
        f"Proper 4-coloring of $n = {n}$ iso[{target_idx}]\n"
        f"Color cardinalities: $(|A|, |B|, |C|, |D|) = (1, 2, 2, 2)$.",
        fontsize=13
    )
    ax.set_aspect('equal')
    ax.axis('off')

    out = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                        '..', f'missing_iso_n{n}_idx{target_idx}_4color.png')
    plt.savefig(out, dpi=130, bbox_inches='tight')
    print(f"saved: {out}")


if __name__ == "__main__":
    main()
