"""Figures for the observer cross-check article (2026-11-28).

    python3 make_figures.py results.json OUTDIR
Outputs: cover.png (1600x672), flow.{png,svg}, days.{png,svg}, causes.{png,svg}.
Numbers come only from results.json (summarize.py). Colours: the two categorical slots validated for the 2026-11-19
article (blue #2a78d6 for "same digest", orange #eb6834 for "different digest") and neutral greys for reads that
could not be compared; every mark also carries a text label, and the article repeats the figures in tables.
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch, Rectangle  # noqa: E402

R = json.loads(Path(sys.argv[1]).read_text())
A = Path(sys.argv[2])
A.mkdir(parents=True, exist_ok=True)
BLUE, ORANGE, GREY, GREY2 = "#2a78d6", "#eb6834", "#c9c7c0", "#e6e4de"
SURF, INK, INK2, RULE = "#fcfcfb", "#0b0b0b", "#52514e", "#dedcd5"
MONO = ["Menlo", "DejaVu Sans Mono"]
plt.rcParams.update({"font.family": ["Helvetica", "Arial Unicode MS", "DejaVu Sans"], "svg.fonttype": "none",
                     "text.color": INK, "figure.facecolor": SURF, "axes.facecolor": SURF})
CC = R["crawlcheck_feed"]
FULL = CC["full_history"]


def n(x):
    return f"{x:,}"


def save(fig, name, svg=True, dpi=200):
    fig.savefig(A / f"{name}.png", dpi=dpi, facecolor=fig.get_facecolor())
    if svg:
        fig.savefig(A / f"{name}.svg", facecolor=fig.get_facecolor())
    plt.close(fig)


def box(ax, x, y, w, h, title, body, ec=RULE, fc="#ffffff", lw=1.2, mono_title=False):
    ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0,rounding_size=0.012", fc=fc, ec=ec, lw=lw))
    ax.text(x + 0.018, y + h - 0.02, title, fontsize=10, weight="bold", va="top", family=MONO if mono_title else None)
    ax.text(x + 0.018, y + h - 0.052, body, fontsize=8.4, color=INK2, va="top", linespacing=1.4)


def arrow(ax, a, b):
    ax.add_patch(FancyArrowPatch(a, b, arrowstyle="-|>", mutation_scale=13, color=INK2, lw=1.2))


# ---- 1. The daily comparison (portrait, phone-friendly) -----------------------------------------------------------
hf = list(R["heldfast_runs"].values())[0]
mtl = list(R["mcp_transparency_log_runs"].values())[-1]
fig = plt.figure(figsize=(7.6, 9.2))
ax = fig.add_axes([0, 0, 1, 1])
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis("off")
ax.text(0.05, 0.965, "One run a day, four observers", fontsize=15, weight="bold", va="top")
ax.text(0.05, 0.932, "What each one publishes, and what HISTOR sets beside it", fontsize=9.6, color=INK2, va="top")
obs = [
    ("CrawlCheck", "a change feed: the digest before and after\neach change, with both read times\n(about 2.5 days of events)", "digest"),
    ("MCP Transparency Log", f"one row per server each night: digest\nand read time ({n(mtl['rows_in_source'])} rows;\na share of about 1,000 a day)", "digest"),
    ("heldfast", f"one file per server: a fingerprint of\nevery tool ({n(hf['rows_in_source'])} files;\na share of about 1,000 a day)", "per-tool fingerprints"),
    ("ScraperWatch", f"a daily diff on a fixed panel of\n{n(2993)} endpoints: JSON paths with\nold and new values", "field by field"),
]
y = 0.775
for name, body, how in obs:
    box(ax, 0.05, y, 0.43, 0.118, name, body)
    arrow(ax, (0.485, y + 0.059), (0.56, y + 0.059))
    ax.text(0.575, y + 0.079, "compared by", fontsize=8, color=INK2, va="center")
    ax.text(0.575, y + 0.047, how, fontsize=9.4, weight="bold", va="center")
    y -= 0.135
box(ax, 0.05, 0.215, 0.9, 0.125, "HISTOR's own record of the same server",
    "every read it made (30 minutes to 6 hours apart), with the digest, the protocol revision and the time.\n"
    "A read by another observer is judged against HISTOR's reads just before and just after it,\n"
    "then against everything HISTOR saw within 24 hours.", ec=BLUE, lw=1.6)
arrow(ax, (0.5, 0.365), (0.5, 0.343))
box(ax, 0.05, 0.05, 0.9, 0.125, "/datasets/peers/<observer>/<day>/",
    "the file as it was read, a verdict for every row (agree, disagree, could not be compared and why),\n"
    "a summary and SHA256SUMS. Disagreements are published with the rest.", mono_title=True)
arrow(ax, (0.5, 0.213), (0.5, 0.178))
ax.plot([0.9, 0.9], [0.37, 0.87], color=RULE, lw=1.2)
for yy in (0.834, 0.699, 0.564, 0.429):
    ax.plot([0.86, 0.9], [yy, yy], color=RULE, lw=1.2)
ax.text(0.925, 0.62, "12:00 UTC, every day", fontsize=8.6, color=INK2, rotation=90, va="center", ha="center")
save(fig, "flow")

# ---- 2. Three weeks with CrawlCheck, by the day a read was first compared ------------------------------------------
days = sorted(CC["by_first_day"])
agree = [CC["by_first_day"][d].get("agree", 0) for d in days]
nodig = [CC["by_first_day"][d].get("histor_no_digest", 0) for d in days]
dis = [CC["by_first_day"][d].get("disagree", 0) for d in days]
fig = plt.figure(figsize=(9.6, 6.4))
fig.text(0.06, 0.955, f"{n(CC['reads'])} reads by CrawlCheck set beside HISTOR's record, 7 to 28 November 2026", fontsize=13.5, weight="bold", va="top")
fig.text(0.06, 0.915, "Each read is counted on the day it was first compared. Verdicts recomputed against HISTOR's full history.",
         fontsize=9.4, color=INK2, va="top")
for i, (colour, label) in enumerate(((BLUE, f"same digest ({n(FULL['agree'])})"), (GREY, f"no HISTOR digest to compare with ({n(FULL['histor_no_digest'])})"),
                                     (ORANGE, f"different digest ({n(FULL['disagree'])})"))):
    fig.patches.append(Rectangle((0.06 + i * 0.27 + (0.07 if i == 2 else 0), 0.862), 0.016, 0.016, transform=fig.transFigure, fc=colour, ec="none"))
    fig.text(0.082 + i * 0.27 + (0.07 if i == 2 else 0), 0.870, label, fontsize=8.8, color=INK2, va="center")
ax = fig.add_axes([0.07, 0.37, 0.9, 0.46])
x = range(len(days))
ax.bar(x, agree, width=0.74, color=BLUE, ec=SURF, lw=1.2)
ax.bar(x, nodig, width=0.74, bottom=agree, color=GREY, ec=SURF, lw=1.2)
for s in ("top", "right", "left"):
    ax.spines[s].set_visible(False)
ax.spines["bottom"].set_color(RULE)
ax.yaxis.grid(True, color=RULE, lw=0.8)
ax.set_axisbelow(True)
ax.tick_params(axis="both", length=0, labelsize=8.4, colors=INK2)
ax.set_xlim(-0.6, len(days) - 0.4)
ax.set_ylabel("reads", fontsize=8.6, color=INK2)
ax2 = fig.add_axes([0.07, 0.115, 0.9, 0.19], sharex=ax)
ax2.bar(x, dis, width=0.74, color=ORANGE, ec=SURF, lw=1.2)
for i, v in enumerate(dis):
    ax2.text(i, v + 0.25, str(v) if v else "0", ha="center", va="bottom", fontsize=8.2, color=INK if v else INK2)
for s in ("top", "right", "left"):
    ax2.spines[s].set_visible(False)
ax2.spines["bottom"].set_color(RULE)
ax2.set_yticks([])
ax2.set_ylim(0, max(dis) + 2.2)
ax2.set_xticks(list(x))
ax2.set_xticklabels([d[8:] for d in days], fontsize=8.4, color=INK2)
ax2.tick_params(axis="both", length=0)
ax.tick_params(axis="x", labelbottom=False)
ax2.set_ylabel("different", fontsize=8.6, color=INK2)
fig.text(0.07, 0.045, "day of November 2026", fontsize=8.6, color=INK2)
fig.text(0.97, 0.045, "source: histor.modelmarket.dev/datasets/peers/crawlcheck/, copied 28 Nov 18:10 UTC", fontsize=7.8, color=INK2, ha="right")
save(fig, "days")

# ---- 3. The disagreements by cause --------------------------------------------------------------------------------
causes = CC["disagree_causes"]
steady = CC["steady_explained"]
invented = CC["published_last_to_full"]["disagree -> agree"] + R["same_read_under_two_addresses"]["dropped_published_last"].get("disagree", 0)
rows = [
    ("HISTOR read a different list just before\nand just after: the server was changing", causes["changed between HISTOR's two reads"], ORANGE),
    ("The list differs on every read\n(71 to 94 different digests in 48 hours)", causes["list differs on every read"], ORANGE),
    ("Read on 28 November; HISTOR had not\nread the server again yet", causes["no HISTOR read after it yet"], ORANGE),
    ("Steady: their digest is what the server lists\nunder the other protocol revision", steady["their digest is what the server lists under the other protocol revision"], ORANGE),
    ("Steady: the server answers the two revisions\ndifferently; that day's lists are not kept", steady["the server answers the two revisions differently; that day's lists are not kept"], ORANGE),
    ("Steady: their digest is a list HISTOR\nrecorded 12 to 23 days earlier", steady["their digest is a list HISTOR recorded 12 to 23 days earlier"], ORANGE),
    ("Steady: no cause found", steady["open"], ORANGE),
    ("Published as different by our daily run,\nthough HISTOR had read the same list", invented, GREY),
]
fig = plt.figure(figsize=(9.6, 6.6))
fig.text(0.05, 0.95, f"The {FULL['disagree']} reads where CrawlCheck and HISTOR have different digests", fontsize=13.5, weight="bold", va="top")
fig.text(0.05, 0.905, f"{CC['disagree_servers']} servers, 7 to 28 November 2026. Below the line: {rows[-1][1]} more that the comparison itself got wrong.",
         fontsize=9.4, color=INK2, va="top")
ax = fig.add_axes([0.47, 0.08, 0.48, 0.76])
ys = [7.6, 6.6, 5.6, 4.6, 3.6, 2.6, 1.6, 0.2]
for (label, v, colour), yy in zip(rows, ys):
    ax.barh(yy, v, height=0.62, color=colour, ec="none")
    ax.text(v + 0.25, yy, str(v), va="center", fontsize=10.5, weight="bold")
    ax.text(-0.4, yy, label, va="center", ha="right", fontsize=8.9, color=INK, linespacing=1.3)
ax.axhline(0.92, color=RULE, lw=1.0, xmin=-0.95, clip_on=False)
ax.set_xlim(0, 16.5)
ax.set_ylim(-0.4, 8.15)
ax.axis("off")
save(fig, "causes")

# ---- cover: every paired read as a dot ------------------------------------------------------------------------------
both = CC["both_have_a_digest"]
cols = 100
fig = plt.figure(figsize=(8, 3.36))
ax = fig.add_axes([0.035, 0.07, 0.56, 0.86])
xs = [i % cols for i in range(both)]
ys_ = [-(i // cols) for i in range(both)]
step = both // FULL["disagree"]
marked = {min(both - 1, step // 2 + k * step) for k in range(FULL["disagree"])}
ax.scatter([xs[i] for i in range(both) if i not in marked], [ys_[i] for i in range(both) if i not in marked], s=2.3, color=BLUE, lw=0)
ax.scatter([xs[i] for i in marked], [ys_[i] for i in marked], s=15, color=ORANGE, lw=0, zorder=3)
ax.set_xlim(-1, cols)
ax.set_ylim(-(both // cols) - 1, 1)
ax.axis("off")
fig.text(0.63, 0.80, n(both), fontsize=30, weight="bold", va="center")
fig.text(0.63, 0.645, "times two observers read the same\nMCP server and both hashed its tool list", fontsize=9.6, color=INK2, va="center", linespacing=1.35)
fig.text(0.63, 0.40, str(FULL["disagree"]), fontsize=30, weight="bold", va="center", color=ORANGE)
n_open = CC["steady_explained"]["open"]
fig.text(0.63, 0.245, "times the two digests differed.\n" + ("One of those has" if n_open == 1 else f"{n_open} of those have") + " no explanation yet.", fontsize=9.6, color=INK2, va="center", linespacing=1.35)
fig.text(0.63, 0.075, "HISTOR and CrawlCheck, 7 to 28 November 2026", fontsize=7.8, color=INK2, va="center")
fig.savefig(A / "cover.png", dpi=200, facecolor=SURF)
plt.close(fig)
print("figures ok:", ", ".join(sorted(p.name for p in A.iterdir())))
