"""Figures for the server-card article (2026-11-28).

    python3 make_figures.py results/summary.json OUTDIR
Outputs: cover.png (1600x672), compare.{png,svg} (how a card and a server are compared), paths.{png,svg} (share that
differs by where the card was found). Every number comes from summary.json (compare.py).
Colours: blue #2a78d6 "card = served", grey #c9c7c0 "differs only cosmetically", orange #e0832b "differs in names,
description text or parameters". OKLab distance between any two >= 17 for normal, protan, deutan and tritan vision
(checked 2026-11-28). Every segment also carries a text label, and the article repeats the numbers 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  # noqa: E402

R = json.loads(Path(sys.argv[1]).read_text())
A = Path(sys.argv[2]); A.mkdir(parents=True, exist_ok=True)
BLUE, GREY, ORANGE = "#2a78d6", "#c9c7c0", "#e0832b"
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})
C = R["classes"]


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


def pct(a, b):
    return f"{100 * a / b:.1f}%"


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_body=False, tsize=10.5, bsize=8.8):
    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.025, y + h - 0.022, title, fontsize=tsize, weight="bold", va="top")
    ax.text(x + 0.025, y + h - 0.058, body, fontsize=bsize, color=INK2, va="top", linespacing=1.45,
            family=MONO if mono_body else None)


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


# ---- 1. How a card and a server are compared (portrait, phone-friendly) ---------------------------------------------
fig = plt.figure(figsize=(6.4, 8.6))
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.975, "Comparing a server card with the server it describes", fontsize=12.5, weight="bold", va="top")
ax.text(0.05, 0.945, "HISTOR, 28 November 2026. Both sides go through the same canonical form.", fontsize=9, color=INK2, va="top")
box(ax, 0.05, 0.70, 0.42, 0.215, "The card",
    "Read where robots.txt allows:\n<endpoint>/server-card\nthe host's AI Catalog\n/.well-known/mcp/server-card.json\n/.well-known/mcp.json\nCounted only if every tool has\na name and an inputSchema.")
box(ax, 0.53, 0.70, 0.42, 0.215, "The server",
    "tools/list, all pages,\nwithout credentials:\nthe 2026-07-28 request first,\nthe initialize handshake for\nolder servers.\nHISTOR's own read of the\nsame endpoint.")
box(ax, 0.05, 0.535, 0.90, 0.12, "One canonical form for both lists",
    "mcp-tool-set-digest/1: each tool's name, description, inputSchema and outputSchema,\nRFC 8785 canonical JSON, sorted by name, SHA-256. Annotations, titles and _meta\ngo into a second digest (extras) that this comparison does not use.")
arrow(ax, (0.26, 0.70), (0.26, 0.655)); arrow(ax, (0.74, 0.70), (0.74, 0.655))
total = R["comparable"]["endpoints"]
box(ax, 0.05, 0.415, 0.90, 0.075, f"{n(total)} endpoints with both lists, on {n(R['comparable']['hosts'])} hosts",
    f"Same digest: {n(C['same']['endpoints'])}.   Different digest: {n(R['differ']['endpoints'])} ({pct(R['differ']['endpoints'], total)}).", tsize=10.5)
arrow(ax, (0.5, 0.535), (0.5, 0.49))
ax.text(0.05, 0.385, "A different digest is put in the first class that fits:", fontsize=9.6, weight="bold", va="top")
steps = [
    (ORANGE, "1  Tool names differ", C["names: the card lists tools the server does not serve"]["endpoints"]
     + C["names: the server serves tools the card does not list"]["endpoints"] + C["names: no tool in common"]["endpoints"]
     + C["names: some added, some missing"]["endpoints"]),
    (ORANGE, "2  Same names, description text differs", C["same names: description text differs"]["endpoints"]),
    (ORANGE, "3  Same names and descriptions, parameters differ", C["same names and descriptions: parameters differ"]["endpoints"]),
    (GREY, "4  Only schema annotation keys, whitespace\n    or output schemas differ", R["differ_cosmetic_only"]["endpoints"]),
]
y = 0.345
for colour, label, value in steps:
    h = 0.07 if "\n" in label else 0.055
    ax.add_patch(FancyBboxPatch((0.05, y - h), 0.90, h, boxstyle="round,pad=0,rounding_size=0.01", fc="#ffffff", ec=RULE, lw=1))
    ax.add_patch(FancyBboxPatch((0.05, y - h), 0.018, h, boxstyle="square,pad=0", fc=colour, ec="none"))
    ax.text(0.09, y - h / 2, label, fontsize=9.2, va="center", linespacing=1.3)
    ax.text(0.925, y - h / 2, n(value), fontsize=10.5, weight="bold", va="center", ha="right")
    y -= h + 0.012
ax.text(0.05, 0.03, "Orange: differs in substance. Grey: differs only cosmetically. Source: HISTOR database, export 2026-11-28 17:59 UTC.",
        fontsize=7.6, color=INK2, va="bottom", wrap=True)
save(fig, "compare")

# ---- 2. Share that differs, by where the card was found ----------------------------------------------------------------
order = [("<endpoint>/server-card", "<endpoint>/server-card"), (".well-known/mcp/server-card.json", "/.well-known/mcp/server-card.json"),
         (".well-known/mcp.json", "/.well-known/mcp.json")]
rows = []
for key, label in order:
    p = R["by_path"][key]
    same = p["endpoints"] - p["differ"]; cos = p["differ"] - p["differ_substantive"]; sub = p["differ_substantive"]
    rows.append((label, p["endpoints"], same, cos, sub))
allsame = C["same"]["endpoints"]; allsub = R["differ_substantive"]["endpoints"]; allcos = R["differ_cosmetic_only"]["endpoints"]
rows.append(("all cards (incl. 10 via AI Catalog)", total, allsame, allcos, allsub))
fig = plt.figure(figsize=(6.4, 4.9))
ax = fig.add_axes([0.05, 0.16, 0.9, 0.62]); ax.set_xlim(0, 1); ax.set_ylim(-0.6, len(rows) - 0.4); ax.invert_yaxis(); ax.axis("off")
fig.text(0.05, 0.955, "How often the card differs from the server", fontsize=12.5, weight="bold", va="top")
fig.text(0.05, 0.905, "By where HISTOR found the card. 1,743 endpoints that have both a card with a full tool list\nand a served list, 28 November 2026.",
         fontsize=8.8, color=INK2, va="top", linespacing=1.4)
gap = 0.004
for i, (label, tot, same, cos, sub) in enumerate(rows):
    ax.text(0, i - 0.36, f"{label}  ·  {n(tot)}", fontsize=9, va="center", family=MONO if label.startswith(("<", "/")) else None,
            weight="bold" if label.startswith("all") else None)
    raw = [100 * v / tot for v in (same, cos, sub)]
    shown = [int(r) for r in raw]
    for k in sorted(range(3), key=lambda k: raw[k] - shown[k], reverse=True)[:100 - sum(shown)]:
        shown[k] += 1                                   # largest remainder: the three labels add up to 100
    x = 0
    for value, label, colour, ink in zip((same, cos, sub), shown, (BLUE, GREY, ORANGE), ("#ffffff", INK, INK)):
        w = value / tot
        ax.add_patch(FancyBboxPatch((x + gap / 2, i - 0.17), max(w - gap, 0.001), 0.34, boxstyle="square,pad=0", fc=colour, ec="none"))
        if w > 0.07:
            ax.text(x + w / 2, i, f"{label}%", fontsize=8.8, ha="center", va="center", color=ink, weight="bold")
        x += w
for j, (colour, label) in enumerate(((BLUE, "same as served"), (GREY, "differs only cosmetically"),
                                     (ORANGE, "differs in names, descriptions or parameters"))):
    yy = 0.095 - j * 0.032
    fig.patches.append(plt.Rectangle((0.05, yy - 0.009), 0.022, 0.018, transform=fig.transFigure, fc=colour, ec="none"))
    fig.text(0.08, yy, label, fontsize=8.6, color=INK2, va="center")
save(fig, "paths")

# ---- 3. Cover (1600 x 672) ---------------------------------------------------------------------------------------------
fig = plt.figure(figsize=(8, 3.36))
ax = fig.add_axes([0, 0, 1, 1]); ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
fig.text(0.045, 0.83, "Server card", fontsize=21, weight="bold", va="top")
fig.text(0.045, 0.69, "vs. tools/list", fontsize=21, weight="bold", va="top", family=MONO)
fig.text(0.045, 0.47, f"{n(R['differ']['endpoints'])} of {n(total)} cards that list tools\ndescribe a different set than\nthe server serves.",
         fontsize=10.5, color=INK2, va="top", linespacing=1.45)
fig.text(0.045, 0.09, "HISTOR · 28 November 2026", fontsize=8.5, color=INK2, va="bottom")
# One real pair from the data (the card says "(free)", the server does not; host left out). The other rows are
# neutral placeholders, not tools of that server.
REAL = ("get_order_status", "Check the status of an on/off-ramp\norder by partnerOrderId (free).",
        "Check the status of an on/off-ramp\norder by partnerOrderId.")


def panel(x, title, desc):
    ax.add_patch(FancyBboxPatch((x, 0.1), 0.235, 0.8, boxstyle="round,pad=0,rounding_size=0.02", fc="#ffffff", ec=RULE, lw=1.2))
    ax.text(x + 0.018, 0.85, title, fontsize=9, weight="bold", va="top", family=MONO)
    ax.add_patch(FancyBboxPatch((x + 0.01, 0.47), 0.215, 0.27, boxstyle="round,pad=0,rounding_size=0.01", fc=ORANGE, ec="none", alpha=0.2))
    ax.text(x + 0.018, 0.71, REAL[0], fontsize=7.6, family=MONO, va="top", weight="bold")
    ax.text(x + 0.018, 0.635, desc, fontsize=6.9, color=INK2, va="top", linespacing=1.35)
    for k, yy in enumerate((0.38, 0.27, 0.16)):
        ax.add_patch(FancyBboxPatch((x + 0.018, yy), 0.09 - 0.012 * k, 0.03, boxstyle="round,pad=0,rounding_size=0.008", fc=GREY, ec="none"))
        ax.add_patch(FancyBboxPatch((x + 0.018, yy - 0.05), 0.17 - 0.02 * k, 0.022, boxstyle="round,pad=0,rounding_size=0.008", fc="#e9e7e1", ec="none"))


panel(0.47, "server card", REAL[1])
panel(0.735, "tools/list", REAL[2])
ax.text(0.7175, 0.6, "≠", fontsize=22, ha="center", va="center", color=ORANGE, weight="bold")
save(fig, "cover", svg=False, dpi=200)
print("figures written to", A)
