"""Draw the icosahedron as the canonical "internally 6-connected"
planar triangulation. Highlight a 5-vertex cut that isolates
exactly one vertex (the only kind of small cut permitted by
Birkhoff's condition).

Internally 6-connected (Birkhoff 1913): a planar triangulation in
which every vertex cut of size ≤ 5 either fails to separate, OR is
a 5-cut whose two sides have one side equal to a single vertex.

Equivalently: no separating 3- or 4-cycle (these are forbidden);
no separating 5-cycle that isolates more than one vertex on either
side.

The icosahedron satisfies this: every vertex has degree 5, and the
5 neighbors of any vertex form a 5-cycle whose removal isolates
that vertex (1 on one side, 6 on the other).
"""
import os, sys
import matplotlib.pyplot as plt
from sage.all import graphs

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


def main():
    G = graphs.IcosahedralGraph()
    G.is_planar(set_embedding=True)
    pos = G.layout(layout='planar')

    # Pick a "center" vertex (one with small distance from center of layout)
    center_v = 0  # arbitrary
    neighbors = list(G.neighbors(center_v))
    print(f'Vertex {center_v} has {len(neighbors)} neighbors: {neighbors}')

    # Verify they form a 5-cycle in the induced subgraph
    nbr_graph = G.subgraph(neighbors)
    print(f'Induced subgraph on neighbors: {nbr_graph.size()} edges, '
          f'is_cycle={nbr_graph.is_cycle()}')

    # Removing 5 neighbors: what's left
    G_minus = G.copy()
    G_minus.delete_vertices(neighbors)
    comps = G_minus.connected_components()
    print(f'After removing the 5 neighbors: {len(comps)} components, '
          f'sizes={sorted(len(c) for c in comps)}')
    # Expect: one component of size 1 (just center_v), another of size 6.

    fig, axes = plt.subplots(1, 2, figsize=(13, 6))

    # LEFT: the icosahedron with the cut highlighted
    ax = axes[0]
    for u, v in G.edges(labels=False):
        x1, y1 = pos[u]; x2, y2 = pos[v]
        if u == center_v or v == center_v:
            color = '#CCCCCC'; lw = 1.0
        elif u in neighbors and v in neighbors:
            # Edge of the 5-cycle separator
            color = '#1166CC'; lw = 4.0
        else:
            color = '#888888'; lw = 1.2
        ax.plot([x1, x2], [y1, y2], color=color, linewidth=lw, zorder=2)
    for v in G.vertices():
        x, y = pos[v]
        if v == center_v:
            ax.plot(x, y, 'o', color='#DD2222', markersize=14, zorder=4,
                    markeredgecolor='black', markeredgewidth=1.5)
            ax.annotate(f'{v}\n(isolated)', (x, y),
                        textcoords='offset points', xytext=(0, 14),
                        ha='center', fontsize=9, color='#AA0000')
        elif v in neighbors:
            ax.plot(x, y, 'o', color='#1166CC', markersize=11, zorder=3,
                    markeredgecolor='black', markeredgewidth=1.2)
            ax.annotate(str(v), (x, y),
                        textcoords='offset points', xytext=(8, 8),
                        fontsize=8, color='#0044AA')
        else:
            ax.plot(x, y, 'o', color='#444444', markersize=8, zorder=2)
            ax.annotate(str(v), (x, y),
                        textcoords='offset points', xytext=(8, 8),
                        fontsize=8, color='gray')
    ax.set_aspect('equal'); ax.axis('off')
    ax.set_title(f'Icosahedron: 5-vertex cut (blue) isolating one vertex (red).\n'
                 f'This is the ONLY kind of small cut permitted '
                 f'by Birkhoff\'s condition.', fontsize=10)

    # RIGHT: schematic showing 4 cases (3 forbidden, 1 allowed)
    ax = axes[1]
    ax.set_xlim(0, 4); ax.set_ylim(0, 4)
    ax.set_aspect('equal'); ax.axis('off')
    cases = [
        ('3-vertex cut\n(separating triangle)', 'FORBIDDEN', 'red', 3.6, 3),
        ('4-vertex cut\n(separating quadrilateral)', 'FORBIDDEN', 'red', 3.6, 2),
        ('5-cut isolating ≥ 2 vertices', 'FORBIDDEN', 'red', 3.6, 1),
        ('5-cut isolating exactly 1 vertex', 'ALLOWED', 'green', 3.6, 0),
    ]
    ax.text(2.0, 3.7, 'Birkhoff (1913): internally 6-connected',
            fontsize=11, weight='bold', ha='center')
    for i, (label, status, color, y_label, y_pos) in enumerate(cases):
        y = 3.0 - i * 0.7
        ax.text(0.1, y, label, fontsize=9, va='center')
        ax.text(2.8, y, status, fontsize=10, weight='bold', color=color,
                va='center')
    ax.text(2.0, -0.4,
            'A minimum 4CT counterexample, if one exists,\n'
            'must satisfy all of the above.',
            fontsize=9, ha='center', style='italic')

    plt.tight_layout()
    out = os.path.join(os.path.dirname(HERE), 'notes',
                       'icosahedron_internally_6_connected.pdf')
    fig.savefig(out, bbox_inches='tight', dpi=120)
    print(f'\nWrote {out}')


if __name__ == '__main__':
    main()
