#!/usr/bin/env python3
"""Generate the figures for the post on chain length bounds under BIP-54.

Usage: gen_graphs.py [FILENAME...]   (all figures when no names are given)
"""

import math
import os
import sys

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
from matplotlib.patches import Patch  # noqa: E402
from matplotlib.ticker import (FixedFormatter, FixedLocator, FuncFormatter,  # noqa: E402
                               NullFormatter, NullLocator)

# The constants of the post (see the start of its Section 3).
R = 4                       # clamp on the difficulty adjustment ratio
R_MAX = 4 + 3 / 2**15       # maximum difficulty increase per period, including rounding
N_PERIOD = 2016             # blocks per period
T_PERIOD = 600 * N_PERIOD   # intended duration of a period (seconds)
T_FUTURE = 7200             # how far in the future a block timestamp can be (seconds)
T_GRACE = 7200              # grace period of timewarp rule (1) (seconds)
W_UNIT = 2**32 + 2**16      # lower bound on a block's chain work per unit of difficulty

# The running example of the post: the chain at height 966,270, on 2026-Sep-09 21:30 UTC.
T_EXAMPLE = 557982895                       # seconds since genesis
W_EXAMPLE = 0x1462584f360e7dddaf4e7df02     # chain work, 2^96.349377

DAY = 86400.0
WEEK = 7 * DAY

BLUE = "#2a78d6"
ORANGE = "#eb6834"
BLACK = "#16181c"
GRAY = "#b9bbc2"
GRID = "#e3e4e8"
BACKGROUND = "#fbfbfa"
LEGEND_EDGE = "#dcdde1"


def new_figure():
    """Create a figure and axes with the style shared by all figures."""
    plt.rcParams.update({
        "font.size": 20, "axes.labelsize": 22, "legend.fontsize": 20,
        "xtick.labelsize": 19, "ytick.labelsize": 19, "font.family": "DejaVu Sans",
    })
    fig, ax = plt.subplots(figsize=(12.5, 7.8), dpi=200)
    ax.set_facecolor(BACKGROUND)
    fig.patch.set_facecolor(BACKGROUND)
    for side in ["top", "right"]:
        ax.spines[side].set_visible(False)
    return fig, ax


def finish_figure(fig, ax, filename, legend_loc, handles=None, labels=None):
    """Add the legend and write the figure to filename."""
    args = [] if handles is None else [handles, labels]
    ax.legend(*args, loc=legend_loc, frameon=True, facecolor=BACKGROUND,
              edgecolor=LEGEND_EDGE)
    fig.tight_layout()
    fig.savefig(filename, dpi=200)
    plt.close(fig)


def ln_q(m, w):
    """The logarithm of q_m(w), the bound on the tail difficulty (Section 3.1)."""
    return np.log((N_PERIOD + (R_MAX - 1) * w / W_UNIT) / (N_PERIOD + (R_MAX - 1) * m))


def draw_adjust_vs_span(filename):
    """The real difficulty adjustment factor and its approximation (Section 3.3)."""
    s = np.linspace(1e-3, 10 * WEEK, 6000)
    adjust = np.maximum(1 / R, np.minimum(T_PERIOD / s, R))
    approx = np.exp(1 - s / T_PERIOD)

    fig, ax = new_figure()
    ax.set_yscale("log")
    ax.axhline(1, color=GRAY, lw=1.2, zorder=1)
    ax.plot(s / WEEK, approx, color=ORANGE, lw=2.8, ls="--", zorder=3,
            label=r"$f(s_j)=\exp\!\left(1-\dfrac{s_j}{T_{\mathrm{period}}}\right)$")
    ax.plot(s / WEEK, adjust, color=BLUE, lw=3.4, zorder=4,
            label=(r"$\mathrm{adjust}(s_j)=\max\!\left(\dfrac{1}{R},\ \min\!\left("
                   r"\dfrac{T_{\mathrm{period}}}{s_j},\ R\right)\right)$"))
    ax.set_xlim(-0.15, 10.15)
    ax.set_xticks(range(0, 11))
    ax.set_ylim(0.2, 5)
    ax.yaxis.set_major_locator(FixedLocator([0.25, 0.5, 1, 2, 4]))
    ax.set_yticklabels(["1/4", "1/2", "1", "2", "4"])
    ax.yaxis.set_minor_locator(
        FixedLocator([0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.5, 2.5, 3, 3.5, 4.5]))
    ax.yaxis.set_minor_formatter(NullFormatter())
    ax.set_xlabel(r"period span $s_j$ (weeks)")
    ax.set_ylabel("difficulty adjustment factor")
    ax.grid(True, which="major", color=GRID, lw=1)
    finish_figure(fig, ax, filename, "upper right")


def draw_k_bounds(filename):
    """The two bounds on the number of complete periods k, for m = 1 (Section 3.5)."""
    h = T_EXAMPLE + T_FUTURE - T_GRACE
    lnq = ln_q(1, W_EXAMPLE)
    p_max = T_PERIOD - T_GRACE

    def time_bound(p):
        return h / p

    def diff_bound(p):
        return T_PERIOD * lnq / (p_max - p)

    # The intersection of the two bounds.
    p_star = p_max * h / (h + T_PERIOD * lnq)
    k_star = h / p_star

    p = np.linspace(60.0, p_max * (1 - 1e-6), 8000)
    k_min, k_max = 10, 1e5

    fig, ax = new_figure()
    ax.set_yscale("log")
    ax.fill_between(p / DAY, k_min, np.minimum(time_bound(p), diff_bound(p)),
                    color=BLUE, alpha=0.13, lw=0, zorder=1)
    ax.axvline(p_max / DAY, color=GRAY, lw=1.2, ls=(0, (4, 4)), zorder=1)
    ax.plot(p / DAY, time_bound(p), color=BLUE, lw=3.2, zorder=3,
            label=(r"$\mathrm{time\_bound}(\bar{p})=\dfrac{t+T_{\mathrm{future}}"
                   r"-T_{\mathrm{grace}}}{\bar{p}}$"))
    ax.plot(p / DAY, diff_bound(p), color=ORANGE, lw=3.2, zorder=3,
            label=(r"$\mathrm{diff\_bound}(\bar{p})=\dfrac{T_{\mathrm{period}}\,\ln q_m(w)}"
                   r"{T_{\mathrm{period}}-\bar{p}-T_{\mathrm{grace}}}$"))
    ax.plot([p_star / DAY], [k_star], "o", ms=11, color=BLACK, zorder=5)
    ax.plot([p_star / DAY, p_star / DAY], [k_min, k_star],
            color=BLACK, lw=1, ls=(0, (2, 3)), zorder=2)
    ax.plot([0, p_star / DAY], [k_star, k_star],
            color=BLACK, lw=1, ls=(0, (2, 3)), zorder=2)
    ax.set_xlim(0, 14.2)
    ax.set_ylim(k_min, k_max)
    ax.set_xticks(range(0, 15, 2))
    ax.yaxis.set_major_locator(FixedLocator([10, 100, 1000, 1e4, 1e5]))
    ax.yaxis.set_major_formatter(FixedFormatter(["10", "100", "1,000", "10,000", "100,000"]))
    ax.yaxis.set_minor_locator(NullLocator())
    ax.set_xlabel(r"average net period time $\bar{p}$ (days)")
    ax.set_ylabel(r"number of complete periods $k$")
    ax.grid(True, color=GRID, lw=1)
    finish_figure(fig, ax, filename, "upper center")


def draw_u_m(filename):
    """The bound u_m(t,w) for every tail length m, with and without the floor (Section 3.6)."""
    h = T_EXAMPLE + T_FUTURE - T_GRACE
    m = np.arange(1, N_PERIOD + 1)
    k = (h + T_PERIOD * ln_q(m, W_EXAMPLE)) / (T_PERIOD - T_GRACE)
    u_nofloor = N_PERIOD * k + m
    u_floor = N_PERIOD * np.floor(k) + m
    best_nofloor = np.argmax(u_nofloor)
    best_floor = np.argmax(u_floor)

    fig, ax = new_figure()
    ax.plot(m, u_nofloor, color=ORANGE, lw=3.0, ls="--", zorder=3,
            label=r"$u_m(t,w)$ without $\lfloor\cdot\rfloor$")
    ax.step(m, u_floor, where="post", color=BLUE, lw=3.0, zorder=4,
            label=r"$u_m(t,w)$ with $\lfloor\cdot\rfloor$")
    ax.plot([m[best_nofloor]], [u_nofloor[best_nofloor]], "o", ms=10, color=ORANGE,
            mec=BACKGROUND, mew=2, zorder=5)
    ax.plot([m[best_floor]], [u_floor[best_floor]], "o", ms=10, color=BLUE,
            mec=BACKGROUND, mew=2, zorder=5)
    ax.set_xlim(0, N_PERIOD)
    ax.set_xticks([1, 250, 500, 750, 1000, 1250, 1500, 1750, 2016])
    ax.set_xlabel(r"blocks in the tail period $m$")
    ax.set_ylabel(r"$u_m(t,w)$  (blocks)")
    ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: format(int(v), ",")))
    ax.grid(True, color=GRID, lw=1)
    finish_figure(fig, ax, filename, "upper center")


def draw_b_hull(filename):
    """The logarithmic adjustment b(p) and its convex hull (Section 4)."""
    ln_r = math.log(R)
    s_tangent = math.e / R * T_PERIOD   # the span at which the hull border leaves the curve

    def b(p):
        return np.log(np.maximum(1 / R, np.minimum(T_PERIOD / (p + T_GRACE), R)))

    def hull_bottom(p):
        s = p + T_GRACE
        return np.where(s <= s_tangent, ln_r - s / s_tangent, b(p))

    p = np.linspace(-T_GRACE + 1e-6, 9 * WEEK, 6000)
    p_tangent = s_tangent - T_GRACE
    p_floor = R * T_PERIOD - T_GRACE

    fig, ax = new_figure()
    ax.fill_between(p / WEEK, hull_bottom(p), ln_r, color=BLUE, alpha=0.13, lw=0, zorder=1)
    ax.axhline(0, color=GRAY, lw=1.2, zorder=2)
    ax.plot(p / WEEK, b(p), color=BLUE, lw=3.4, label=r"$b(p)$", zorder=4)
    ax.plot(p / WEEK, hull_bottom(p), color=ORANGE, lw=2.8, ls=(0, (1.5, 2.5)),
            label="bottom border of hull", zorder=5)
    ax.plot([p_tangent / WEEK, p_floor / WEEK], [ln_r - 1, -ln_r], "o", ms=11,
            color=ORANGE, mec=BACKGROUND, mew=2, zorder=6)
    handles, labels = ax.get_legend_handles_labels()
    handles.insert(1, Patch(facecolor=BLUE, alpha=0.13, edgecolor="none"))
    labels.insert(1, r"convex hull of $b(p)$")
    ax.set_xlim(-0.15, 9.15)
    ax.set_xticks(range(0, 10))
    ax.set_ylim(-1.6, 1.6)
    ax.set_yticks([-1.5, -1, -0.5, 0, 0.5, 1, 1.5])
    ax.set_yticklabels(["−1.5", "−1", "−0.5", "0", "0.5", "1", "1.5"])
    ax.set_xlabel("net period time $p$ (weeks)")
    ax.set_ylabel("difficulty adjustment steps (nats)")
    ax.grid(True, color=GRID, lw=1)
    finish_figure(fig, ax, filename, "upper right", handles, labels)


TARGETS = {
    "adjust_vs_span.png": draw_adjust_vs_span,
    "k_bounds_linear_log.png": draw_k_bounds,
    "u_m.png": draw_u_m,
    "b_hull.png": draw_b_hull,
}

if __name__ == "__main__":
    outdir = os.path.dirname(os.path.abspath(__file__))
    requested = sys.argv[1:] if len(sys.argv) > 1 else list(TARGETS)
    for name in requested:
        if name not in TARGETS:
            sys.exit(f"error: unknown target {name!r}")
    for name in requested:
        TARGETS[name](os.path.join(outdir, name))
