"""Two-tire nesting picture for fiber_decomposition.tex.

We draw two concentric annuli (the outer tire and inner tire) sharing
a common cycle gamma in the middle.  Each annulus is triangulated, and
each triangular face has a dual vertex.  The shared cycle gamma carries
dual vertices that are annular for both tires; for one vertex v on gamma
we highlight the single G'-edge that crosses the shared cycle -- the
'spoke' edge that is an outer spoke of the inner tire and an inner spoke
of the outer tire simultaneously."""
import math
import os
import matplotlib.pyplot as plt
import matplotlib.patches as patches


def main():
    here = os.path.dirname(os.path.abspath(__file__))
    out = os.path.join(here, 'fig_nesting_compatibility.png')

    fig, ax = plt.subplots(figsize=(9.0, 7.5))

    # Three radii: outer boundary of outer tire, shared cycle gamma, inner boundary
    R_OUT = 3.0
    R_GAMMA = 2.0
    R_IN = 1.0

    n = 8  # number of vertices on each cycle (just for the picture)

    def ring(R):
        return [(R * math.cos(2 * math.pi * i / n + math.pi / 2),
                 R * math.sin(2 * math.pi * i / n + math.pi / 2))
                for i in range(n)]

    out_pts = ring(R_OUT)
    gamma_pts = ring(R_GAMMA)
    in_pts = ring(R_IN)

    # Light shaded annular regions
    outer_annulus = patches.Wedge((0, 0), R_OUT, 0, 360, width=R_OUT - R_GAMMA,
                                  facecolor='#e6f0ff', edgecolor='none', zorder=0)
    inner_annulus = patches.Wedge((0, 0), R_GAMMA, 0, 360, width=R_GAMMA - R_IN,
                                  facecolor='#fff2e0', edgecolor='none', zorder=0)
    ax.add_patch(outer_annulus)
    ax.add_patch(inner_annulus)

    # Cycles
    for pts, color in [(out_pts, '#333'), (gamma_pts, '#1f3f70'), (in_pts, '#333')]:
        for i in range(n):
            x1, y1 = pts[i]; x2, y2 = pts[(i + 1) % n]
            ax.plot([x1, x2], [y1, y2], color=color, linewidth=2.0, zorder=1)

    # Triangulate each annulus (simple zig-zag)
    for ring_a, ring_b in [(out_pts, gamma_pts), (gamma_pts, in_pts)]:
        for i in range(n):
            x1, y1 = ring_a[i]; x2, y2 = ring_b[i]
            ax.plot([x1, x2], [y1, y2], color='#999', linewidth=0.8, zorder=1)
            x3, y3 = ring_b[(i + 1) % n]
            ax.plot([x1, x2], [y1, y2], color='#999', linewidth=0.8, zorder=1)
            ax.plot([ring_a[i][0], ring_b[(i + 1) % n][0]],
                    [ring_a[i][1], ring_b[(i + 1) % n][1]],
                    color='#999', linewidth=0.8, zorder=1)

    # Cycle vertices on gamma
    for (x, y) in gamma_pts:
        ax.plot(x, y, 'o', color='#1f3f70', markersize=7, zorder=2)

    # Pick a focal vertex v on gamma and draw the local G'-picture:
    # the two annular faces of the outer tire incident to v give the
    # cycle edges of T'^outer_ann at v, the two annular faces of the
    # inner tire incident to v give the cycle edges of T'^inner_ann at v,
    # and the single 'crossing' G'-edge at v ... well, in the spoke-only
    # case the dual vertex at v has degree 3 in G' and one of those edges
    # crosses gamma.
    #
    # For the picture we mark the dual vertex at v with a small star and
    # draw its three G'-edges in distinct colors.
    v_idx = 0
    vx, vy = gamma_pts[v_idx]
    # We draw a dual vertex slightly offset (since v on gamma is a *vertex*
    # of G, not a dual; really we want to mark an annular face dual on each
    # side of gamma).  Skip the dual-vertex picture and instead just
    # highlight the shared cycle gamma and one focal vertex v with arrows
    # pointing to its outer- and inner-tire roles.

    ax.plot(vx, vy, 'o', color='#d62728', markersize=14, zorder=3)
    ax.annotate("$v \\in V(\\gamma)$", (vx, vy), xytext=(vx + 0.8, vy + 0.3),
                fontsize=11, color='#d62728',
                arrowprops=dict(arrowstyle='->', color='#d62728', lw=1.2))

    # The 'shared spoke' for v: in the spoke-only Remark 1.16.1 picture,
    # T^outer_ann's cycle near v carries one G'-edge crossing inward
    # (to a face inside gamma == an inner spoke of T^outer_{f'}), and
    # T^inner_ann's cycle near v carries one G'-edge crossing outward
    # (to a face outside gamma == an outer spoke of T^inner_{f'}).
    # In the spoke-only case these are the SAME G'-edge.
    #
    # Draw it as a heavy orange line crossing gamma at v.
    r_outer_face = (R_GAMMA + R_OUT) / 2  # mid-radius of outer annulus
    r_inner_face = (R_GAMMA + R_IN) / 2   # mid-radius of inner annulus
    theta = math.pi / 2  # vertex 0 is at the top
    px_out = r_outer_face * math.cos(theta)
    py_out = r_outer_face * math.sin(theta)
    px_in = r_inner_face * math.cos(theta)
    py_in = r_inner_face * math.sin(theta)
    ax.plot([px_out, px_in], [py_out, py_in], color='#e08000', linewidth=4.0,
            zorder=2)
    ax.plot(px_out, py_out, 's', color='#e08000', markersize=14, zorder=3)
    ax.plot(px_in, py_in, 's', color='#e08000', markersize=14, zorder=3)
    ax.annotate("outer-tire\nannular face $f$",
                (px_out, py_out), xytext=(2.4, 2.6), fontsize=9,
                color='#a05000',
                arrowprops=dict(arrowstyle='->', color='#a05000', lw=1.0))
    ax.annotate("inner-tire\nannular face $f'$",
                (px_in, py_in), xytext=(1.5, 0.6), fontsize=9,
                color='#a05000',
                arrowprops=dict(arrowstyle='->', color='#a05000', lw=1.0))
    ax.annotate("shared $G'$-edge at $v$\n(spoke from both sides)",
                ((px_out + px_in) / 2, (py_out + py_in) / 2),
                xytext=(-3.6, 1.8), fontsize=10, color='#e08000',
                arrowprops=dict(arrowstyle='->', color='#e08000', lw=1.2))

    # Label the cycles
    ax.text(0, R_OUT + 0.25, r"$B_{\mathrm{out}}$ of outer tire",
            ha='center', fontsize=9, color='#333')
    ax.text(0, -R_IN - 0.35, r"$B_{\mathrm{in}}$ of inner tire",
            ha='center', fontsize=9, color='#333')
    ax.text(-R_GAMMA - 0.45, 0, r"$\gamma$", ha='right', va='center',
            fontsize=14, color='#1f3f70', fontweight='bold')

    # Region labels
    ax.text(0, (R_OUT + R_GAMMA) / 2 + 0.1, "outer tire",
            ha='center', fontsize=10, color='#1f3f70',
            bbox=dict(boxstyle='round,pad=0.3', facecolor='white',
                      edgecolor='none', alpha=0.7))
    ax.text(0, -(R_GAMMA + R_IN) / 2 - 0.1, "inner tire",
            ha='center', fontsize=10, color='#a05000',
            bbox=dict(boxstyle='round,pad=0.3', facecolor='white',
                      edgecolor='none', alpha=0.7))

    ax.set_xlim(-4.2, 4.2)
    ax.set_ylim(-4.2, 4.2)
    ax.set_aspect('equal')
    ax.axis('off')
    ax.set_title("Nested tires sharing cycle $\\gamma$:\n"
                 "the spoke from $v \\in V(\\gamma)$ is shared between "
                 "$T'^{\\mathrm{outer}}_{f'}$ and $T'^{\\mathrm{inner}}_{f'}$",
                 fontsize=11)

    plt.savefig(out, dpi=160, bbox_inches='tight')
    plt.close()
    print(f"wrote {out}")


if __name__ == '__main__':
    main()
