"""Generate Lecture 02 figures into ../figures. Run: python figures.py"""
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

OUT = Path(__file__).resolve().parent.parent / "figures"
BLUE, ORANGE = "#2a78d6", "#eb6834"
INK, MUTED, SURFACE = "#0b0b0b", "#52514e", "#fcfcfb"


def draw_commit(ax, x, y, label, color):
    ax.add_patch(plt.Circle((x, y), 0.28, color=color, zorder=3))
    ax.text(x, y - 0.6, label, ha="center", va="top", fontsize=11, color=INK)


def draw_edge(ax, start, end):
    ax.annotate("", xy=start, xytext=end, zorder=1,
                arrowprops=dict(arrowstyle="->", color=MUTED, lw=1.6,
                                shrinkA=12, shrinkB=12))


def draw_pointer(ax, x, y, text, color):
    ax.text(x, y, text, ha="center", va="center", fontsize=11, color="white",
            bbox=dict(boxstyle="round,pad=0.35", fc=color, ec="none"))


def plot_commit_graph():
    main = {"A": (0, 0), "B": (2.4, 0), "D": (7.2, 0), "M": (9.6, 0)}
    feature = {"C": (4.8, 1.8)}
    fig, ax = plt.subplots(figsize=(9, 3.8), facecolor=SURFACE)
    ax.set_facecolor(SURFACE)
    for child, parent in [("B", "A"), ("D", "B"), ("M", "D")]:
        draw_edge(ax, main[parent], main[child])
    draw_edge(ax, main["B"], feature["C"])
    draw_edge(ax, feature["C"], main["M"])
    labels = {"A": "A\nAdd env files", "B": "B\nAdd README", "D": "D\nName the group",
              "M": "M\nMerge", "C": "C\nDescribe the repo"}
    for name, pos in main.items():
        draw_commit(ax, *pos, labels[name], BLUE)
    ax.add_patch(plt.Circle(feature["C"], 0.28, color=ORANGE, zorder=3))
    ax.text(4.8, 2.35, "C  Describe the repo", ha="center", va="center", fontsize=11, color=INK)
    draw_pointer(ax, 9.6, 0.85, "main, HEAD", BLUE)
    draw_pointer(ax, 4.8, 3.05, "feature/readme", ORANGE)
    ax.text(2.4, -1.75, "(merge base)", ha="center", fontsize=10, color=MUTED)
    ax.set_xlim(-1.2, 10.8)
    ax.set_ylim(-2.1, 3.5)
    ax.set_aspect("equal")
    ax.axis("off")
    ax.set_title("Commits point to their parents; branches point to commits",
                 fontsize=13, color=INK, weight="bold")
    fig.tight_layout()
    fig.savefig(OUT / "commit_graph.png", dpi=200, facecolor=SURFACE)
    plt.close(fig)


def draw_box(ax, x, y, w, h, title, sub, color):
    ax.add_patch(plt.Rectangle((x, y), w, h, fc="white", ec=color, lw=2, zorder=2))
    ax.text(x + w / 2, y + h * 0.62, title, ha="center", va="center", fontsize=13, color=INK, weight="bold")
    ax.text(x + w / 2, y + h * 0.3, sub, ha="center", va="center", fontsize=11, color=MUTED)


def draw_arrow(ax, start, end, label, color, dy=0.25):
    ax.annotate("", xy=end, xytext=start, arrowprops=dict(arrowstyle="->", color=color, lw=1.8))
    ax.text((start[0] + end[0]) / 2, start[1] + dy, label, ha="center", fontsize=12, color=INK, family="monospace")


def plot_three_areas():
    fig, ax = plt.subplots(figsize=(9, 3.0), facecolor=SURFACE)
    ax.set_facecolor(SURFACE)
    draw_box(ax, 0, 0, 2.6, 1.4, "Working tree", "files you edit", BLUE)
    draw_box(ax, 4.3, 0, 2.6, 1.4, "Staging area", "next snapshot", BLUE)
    draw_box(ax, 8.6, 0, 2.6, 1.4, "Repository", "commits (history)", ORANGE)
    draw_arrow(ax, (2.75, 0.7), (4.2, 0.7), "git add", BLUE)
    draw_arrow(ax, (7.0, 0.7), (8.5, 0.7), "git commit", ORANGE)
    ax.annotate("", xy=(1.3, -0.12), xytext=(9.9, -0.12),
                arrowprops=dict(arrowstyle="->", color=MUTED, lw=1.6, connectionstyle="arc3,rad=-0.12"))
    ax.text(5.6, -1.25, "git restore / git switch bring a stored version back", ha="center", fontsize=12, color=INK, family="monospace")
    ax.set_xlim(-0.3, 11.5)
    ax.set_ylim(-1.5, 1.8)
    ax.axis("off")
    ax.set_title("A change moves left to right; restoring brings a version back", fontsize=13, color=INK, weight="bold")
    fig.tight_layout()
    fig.savefig(OUT / "three_areas.png", dpi=200, facecolor=SURFACE)
    plt.close(fig)


def plot_push_pull():
    fig, ax = plt.subplots(figsize=(9, 2.8), facecolor=SURFACE)
    ax.set_facecolor(SURFACE)
    draw_box(ax, 0, 0, 3.4, 1.4, "Your laptop", "local main", BLUE)
    draw_box(ax, 6.6, 0, 3.4, 1.4, "GitHub (origin)", "origin/main", ORANGE)
    draw_arrow(ax, (3.45, 0.95), (6.55, 0.95), "git push", BLUE)
    draw_arrow(ax, (6.55, 0.4), (3.45, 0.4), "git pull = fetch + merge", ORANGE, dy=-0.45)
    ax.set_xlim(-0.3, 10.3)
    ax.set_ylim(-0.7, 1.9)
    ax.axis("off")
    ax.set_title("push sends your commits; pull brings others' commits and merges them", fontsize=13, color=INK, weight="bold")
    fig.tight_layout()
    fig.savefig(OUT / "push_pull.png", dpi=200, facecolor=SURFACE)
    plt.close(fig)


if __name__ == "__main__":
    OUT.mkdir(exist_ok=True)
    plot_commit_graph()
    plot_three_areas()
    plot_push_pull()
