"""Generate the example figure for Definition 1.5 (tire graph) of the
paper.  Produces fig_tire_example.png at the paper's top level.

Picks a specific small tire (m=6 outer cycle, k=4 inner cycle with one
chord) so that all four named parts B_out, O, B_in, E_ann are visible
and the annular triangles are individually legible.
"""
import math
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

import matplotlib.pyplot as plt
import matplotlib.patches as patches

from tire_graph import random_tire, planar_positions


def draw_tire_def(tire, filename):
    m, k = tire['m'], tire['k']
    outer, inner = tire['outer'], tire['inner']
    edges = tire['edges']

    R_out, R_in = 1.0, 0.45
    pos = planar_positions(tire, R_out=R_out, R_in=R_in)

    fig, ax = plt.subplots(figsize=(6.5, 6.5))

    # guide circles for reference
    for r in (R_out + 0.04, R_in - 0.04):
        ax.add_patch(patches.Circle((0, 0), r, fill=False,
                                    edgecolor='lightgray',
                                    linewidth=0.5, linestyle='--'))

    outer_set = set(outer)
    inner_set = set(inner)
    C = {
        'outer_cycle': '#1f77b4',
        'inner_cycle': '#d62728',
        'inner_chord': '#ff7f0e',
        'spoke':       '#7f7f7f',
    }

    # classify and draw edges
    for (u, v) in edges:
        if u in outer_set and v in outer_set:
            color, lw, label = C['outer_cycle'], 2.6, 'B_out'
        elif u in inner_set and v in inner_set:
            ia, ib = u - m, v - m
            d = abs(ia - ib)
            d = min(d, k - d)
            if d == 1:
                color, lw, label = C['inner_cycle'], 2.6, 'B_in'
            else:
                color, lw, label = C['inner_chord'], 1.8, 'O chord'
        else:
            color, lw, label = C['spoke'], 1.1, 'E_ann'
        x1, y1 = pos[u]; x2, y2 = pos[v]
        ax.plot([x1, x2], [y1, y2], color=color, linewidth=lw, zorder=1)

    # vertices
    for v in outer:
        x, y = pos[v]
        ax.plot(x, y, 'o', color=C['outer_cycle'], markersize=14, zorder=2)
        ax.annotate(str(v), (x, y), color='white', ha='center',
                    va='center', fontsize=9, fontweight='bold', zorder=3)
    for v in inner:
        x, y = pos[v]
        ax.plot(x, y, 'o', color=C['inner_cycle'], markersize=13, zorder=2)
        ax.annotate(str(v), (x, y), color='white', ha='center',
                    va='center', fontsize=8, fontweight='bold', zorder=3)

    # legend
    legend_items = [
        plt.Line2D([], [], color=C['outer_cycle'], linewidth=2.6,
                   label=r'$B_{\mathrm{out}}$ (outer boundary, $m=6$)'),
        plt.Line2D([], [], color=C['inner_cycle'], linewidth=2.6,
                   label=r'$B_{\mathrm{in}}$ (inner boundary, $k=4$)'),
        plt.Line2D([], [], color=C['inner_chord'], linewidth=1.8,
                   label=r'chord of $O$'),
        plt.Line2D([], [], color=C['spoke'], linewidth=1.1,
                   label=r'$E_{\mathrm{ann}}$ (annular edges)'),
    ]
    ax.legend(handles=legend_items, loc='upper left',
              bbox_to_anchor=(1.0, 1.0), fontsize=10, frameon=False)

    ax.set_xlim(-1.20, 1.20)
    ax.set_ylim(-1.20, 1.20)
    ax.set_aspect('equal')
    ax.axis('off')

    plt.savefig(filename, dpi=160, bbox_inches='tight')
    plt.close()


def main():
    # m=6 outer, k=4 inner, 1 chord — try a few seeds to pick a clean one
    paper_dir = os.path.abspath(os.path.join(HERE, '..'))
    candidates = [(6, 4, 1, s) for s in (3, 5, 8, 13, 21)]
    # Use seed=3 as the chosen example (good lattice-path balance)
    for (m, k, nc, seed) in candidates[:1]:
        tire = random_tire(m, k, n_chords=nc, seed=seed)
        fn = os.path.join(paper_dir, 'fig_tire_example.png')
        draw_tire_def(tire, fn)
        print(f"  wrote {fn}")
        print(f"    m={m}, k={k}, chords={tire['inner_chords']}, "
              f"path={tire['lattice_path']}")


if __name__ == '__main__':
    main()
