"""Charts for the npm malware counting project.

Usage (from the project folder, after analysis.py):
    python code/charts.py
Reads data/*.csv, writes assets/*.png (dark card frame, same style as the other projects).
"""
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import FancyBboxPatch, Patch
import pandas as pd

ROOT = Path(__file__).resolve().parent.parent
DATA, OUT = ROOT / "data", ROOT / "assets"

# categorical slots 1-3, validated (dark mode, #0A0D18 surface): all checks pass
C1, C2, C3 = "#3987e5", "#d95926", "#199e70"
GRAYMARK = "#8a8a96"
TEXT, TEXT_MUTED, GRID = "#F5F4F1", "#B7B6C2", "#2A2B3A"
CANVAS_BG, CARD_BORDER = "#0A0D18", "#3A4560"

plt.rcParams.update({
    "figure.facecolor": CANVAS_BG, "axes.facecolor": "none", "savefig.facecolor": CANVAS_BG,
    "text.color": TEXT, "axes.edgecolor": GRID, "axes.labelcolor": TEXT_MUTED,
    "xtick.color": TEXT_MUTED, "ytick.color": TEXT_MUTED,
    "font.family": "DejaVu Sans", "font.size": 13,
})


def card(fig, margin=0.018, left=0.075, bottom=0.11, top=0.09, right=0.02):
    bg = fig.add_axes((0, 0, 1, 1), zorder=-10)
    bg.set_xlim(0, 1); bg.set_ylim(0, 1)
    bg.add_patch(FancyBboxPatch((margin, margin), 1 - 2 * margin, 1 - 2 * margin,
                                boxstyle="round,pad=0,rounding_size=0.018", transform=bg.transAxes,
                                linewidth=1.3, edgecolor=CARD_BORDER, facecolor=CANVAS_BG))
    bg.axis("off")
    fig.subplots_adjust(left=margin + left, right=1 - margin - right, top=1 - margin - top, bottom=margin + bottom)


def title(fig, main, sub):
    fig.text(0.045, 0.935, main, fontsize=19, fontweight="bold", color=TEXT, va="top")
    fig.text(0.045, 0.885, sub, fontsize=12.5, color=TEXT_MUTED, va="top")


def tidy(ax, grid_axis="y"):
    for s in ["top", "right", "left"]:
        ax.spines[s].set_visible(False)
    getattr(ax, f"{grid_axis}axis").grid(True, color=GRID, lw=0.8, zorder=0)
    ax.set_axisbelow(True)
    ax.tick_params(length=0)


def week_labels(weeks):
    return [pd.Timestamp(w).strftime("%b %-d") for w in weeks]


def weekly_units(w):
    """Grouped bars: three counting units per UTC week."""
    fig = plt.figure(figsize=(12, 6.8), dpi=150)
    card(fig, left=0.07, bottom=0.17, top=0.17)
    ax = fig.add_subplot(111)
    title(fig, "Same weeks, three counting units",
          "npm malware advisories per UTC week (Monday start), GitHub Advisory Database")
    x = range(len(w)); bw = 0.27
    series = [("records", "Advisory records", C1, -bw), ("distinct_packages", "Distinct packages", C2, 0),
              ("exact_pairs", "Exact package-version pairs", C3, bw)]
    for col, lab, colr, dx in series:
        ax.bar([i + dx for i in x], w[col], width=bw - 0.03, color=colr, label=lab, zorder=3)
    focus = len(w) - 1
    for col, _, _, dx in series:
        ax.text(focus + dx, w[col].iloc[focus] + 18, f"{w[col].iloc[focus]:,}", ha="center", fontsize=10, color=TEXT)
    peak = int(w.records.idxmax())
    ax.text(peak - bw, w.records.iloc[peak] + 18, f"{w.records.iloc[peak]:,}", ha="center", fontsize=10, color=TEXT)
    ax.axvspan(3.5, len(w) - 0.5, color="#ffffff", alpha=0.035, zorder=0)
    ax.text(3.6, 1290, "Study window", fontsize=11, color=TEXT_MUTED)
    ax.text(-0.4, 1290, "Baseline", fontsize=11, color=TEXT_MUTED)
    ax.set_xticks(list(x)); ax.set_xticklabels(week_labels(w.week))
    ax.set_ylim(0, 1360); ax.set_ylabel("Count")
    tidy(ax)
    fig.legend(loc="lower left", ncol=3, frameon=False, fontsize=11.5, bbox_to_anchor=(0.04, 0.035), labelcolor=TEXT_MUTED)
    fig.savefig(OUT / "chart_units_weekly.png", dpi=150)
    plt.close(fig)


def template_split(w):
    """Stacked bars: one naming template vs everything else."""
    fig = plt.figure(figsize=(12, 6.4), dpi=150)
    card(fig, left=0.07, bottom=0.17, top=0.17)
    ax = fig.add_subplot(111)
    title(fig, "One naming template drives the Nov 9-15 peak",
          "Advisory records per week, split by whether the package name starts with \"dowload_ebok_\"")
    x = list(range(len(w)))
    ax.bar(x, w.records_excl_template, width=0.6, color=C1, label="All other records", zorder=3)
    ax.bar(x, w.template_records, width=0.6, bottom=w.records_excl_template + 4, color=C2,
           label="\"dowload_ebok_*\" naming template", zorder=3)
    for i, r in w.iterrows():
        ax.text(i, r.records + 20, f"{r.records:,}", ha="center", fontsize=10.5, color=TEXT)
    pk = int(w.records.idxmax())
    ax.text(pk + 0.36, w.records_excl_template.iloc[pk] + w.template_records.iloc[pk] / 2,
            f"{w.template_records.iloc[pk]} template\nrecords", va="center", fontsize=10.5, color=TEXT_MUTED)
    ax.set_xticks(x); ax.set_xticklabels(week_labels(w.week)); ax.set_ylim(0, 1320); ax.set_ylabel("Advisory records")
    tidy(ax)
    fig.legend(loc="lower left", ncol=2, frameon=False, fontsize=11.5, bbox_to_anchor=(0.04, 0.035), labelcolor=TEXT_MUTED)
    fig.savefig(OUT / "chart_template_split.png", dpi=150)
    plt.close(fig)


def focus_ratios(c):
    """Single-series dot plot: Nov 16-22 divided by the mean of the three prior weeks."""
    names = {"records": "Advisory records", "distinct_packages": "Distinct packages",
             "packages_first_seen": "Packages not reported in earlier weeks",
             "exact_pairs": "Exact package-version pairs",
             "records_excl_template": "Records, excluding the naming template",
             "records_specific_behaviour": "Records with specific behaviour text"}
    c = c.set_index("unit").loc[list(names)]
    fig = plt.figure(figsize=(12, 6.6), dpi=150)
    card(fig, left=0.34, bottom=0.14, top=0.17, right=0.16)
    ax = fig.add_subplot(111)
    title(fig, "Is Nov 16-22 up or down? It depends on the unit",
          "Focus week divided by the mean of Oct 26 - Nov 15 (1.0 = no change)")
    ys = list(range(len(c)))[::-1]
    for y, (k, r) in zip(ys, c.iterrows()):
        ax.plot([1, r.ratio_vs_prior3], [y, y], color=GRAYMARK, lw=2, zorder=2, solid_capstyle="round")
        ax.scatter([r.ratio_vs_prior3], [y], s=90, color=C1, edgecolors=CANVAS_BG, linewidths=2, zorder=4)
        dx = 0.035 if r.ratio_vs_prior3 >= 1 else -0.035
        ax.text(r.ratio_vs_prior3 + dx, y + 0.28, f"{r.ratio_vs_prior3:.2f}x", va="center",
                ha="left" if dx > 0 else "right", fontsize=12, color=TEXT, fontweight="bold")
        ax.text(1.0, y, f"   {int(r.focus_week):,} vs {r.prior3_mean:,.0f}", va="center", fontsize=10.5,
                color=TEXT_MUTED, transform=ax.get_yaxis_transform())
    ax.axvline(1, color=TEXT_MUTED, lw=1, zorder=1)
    ax.set_yticks(ys); ax.set_yticklabels(list(names.values()), fontsize=12, color=TEXT)
    ax.set_xlim(0.4, 1.7); ax.set_xticks([0.5, 0.75, 1, 1.25, 1.5])
    ax.set_xticklabels(["0.5x", "0.75x", "1x", "1.25x", "1.5x"])
    ax.set_ylim(-0.6, len(c) - 0.4)
    tidy(ax, "x")
    fig.text(0.965, 0.83, "Nov 16-22 vs\nprior mean", fontsize=10, color=TEXT_MUTED, ha="right", va="bottom")
    fig.savefig(OUT / "chart_focus_ratios.png", dpi=150)
    plt.close(fig)


def pair_relations(p):
    """Horizontal bars: how the second record of each same-package pair relates to the first."""
    order = [("scope_widening_only", "Replaces listed versions with \"all versions\""),
             ("redundant", "Same versions, nothing added"),
             ("complementary_versions", "Names versions the first record lacked"),
             ("placeholder_version_only", "Adds only a placeholder version")]
    n = p.groupby("evidence_relation").pairs.sum()
    fig = plt.figure(figsize=(12, 5.8), dpi=150)
    card(fig, left=0.36, bottom=0.12, top=0.19, right=0.08)
    ax = fig.add_subplot(111)
    title(fig, "What the second advisory adds",
          f"All {n.sum()} packages with two advisories, Sep 28 - Nov 22; in every pair the second record is GitHub's boilerplate")
    ys = list(range(len(order)))[::-1]
    for y, (k, lab) in zip(ys, order):
        ax.barh(y, n.get(k, 0), height=0.56, color=C1, zorder=3)
        ax.text(n.get(k, 0) + 3, y, f"{n.get(k, 0)}", va="center", fontsize=12, color=TEXT)
    ax.set_yticks(ys); ax.set_yticklabels([l for _, l in order], fontsize=12, color=TEXT)
    ax.set_xlim(0, 245); ax.set_xlabel("Pairs")
    tidy(ax, "x")
    fig.savefig(OUT / "chart_pair_relations.png", dpi=150)
    plt.close(fig)


def leadstack_upset(v):
    """UpSet-style chart of exact version sets in the two @leadstack/crm-connect advisories."""
    a, b = "GHSA-hqfp-fhqg-4xc5", "GHSA-6crj-9fxx-v653"
    sets = {g: set(v[(v.ghsa_id == g) & (v.range_type == "exact")].exact_version) for g in (a, b)}
    inter = [("both", sets[a] & sets[b]), ("a", sets[a] - sets[b]), ("b", sets[b] - sets[a])]
    fig = plt.figure(figsize=(12, 6.6), dpi=150)
    card(fig, left=0.0, bottom=0.0, top=0.0)
    title(fig, "Two advisories, one package, overlapping version lists",
          "@leadstack/crm-connect, both published Nov 22, 2026 about four minutes apart")
    top = fig.add_axes((0.40, 0.42, 0.52, 0.38))
    mat = fig.add_axes((0.40, 0.11, 0.52, 0.22), sharex=top)
    cols = [C1, C1, C1]
    for i, (key, s) in enumerate(inter):
        top.bar(i, len(s), width=0.5, color=cols[i], zorder=3)
        top.text(i, len(s) + 0.15, f"{len(s)}", ha="center", fontsize=13, color=TEXT, fontweight="bold")
        top.text(i, -0.55, ", ".join(sorted(s, key=lambda t: [int(p) for p in t.split('.')])), ha="center",
                 fontsize=9.5, color=TEXT_MUTED, va="top", wrap=True)
    top.set_ylim(0, 6.2); top.set_yticks([0, 2, 4, 6]); top.set_ylabel("Versions in intersection")
    top.tick_params(axis="x", labelbottom=False); tidy(top)
    rows = {a: 1, b: 0}
    member = {"both": [a, b], "a": [a], "b": [b]}
    for i, (key, _) in enumerate(inter):
        for g, y in rows.items():
            on = g in member[key]
            mat.scatter(i, y, s=170, color=TEXT if on else GRID, zorder=3)
        ys = [rows[g] for g in member[key]]
        if len(ys) > 1:
            mat.plot([i, i], [min(ys), max(ys)], color=TEXT, lw=3, zorder=2)
    mat.set_ylim(-0.6, 1.6); mat.set_xlim(-0.6, 2.6)
    mat.set_yticks([1, 0])
    mat.set_yticklabels([f"{a}  (OpenSSF import, {len(sets[a])} versions)", f"{b}  (GitHub-written, {len(sets[b])} versions)"],
                        fontsize=11, color=TEXT)
    mat.set_xticks([])
    for s in mat.spines.values():
        s.set_visible(False)
    mat.tick_params(length=0)
    fig.text(0.06, 0.76, "Which explicitly listed versions\neach advisory names.", fontsize=12, color=TEXT, va="top")
    fig.text(0.06, 0.65, "Dots below a bar show which\nadvisories share that set.\n\nThe OpenSSF import carries a\nbehaviour description; the\nGitHub-written record uses the\nstandard text.",
             fontsize=11, color=TEXT_MUTED, va="top")
    fig.savefig(OUT / "chart_leadstack_upset.png", dpi=150)
    plt.close(fig)


def social(w, c):
    fig = plt.figure(figsize=(12, 6.3), dpi=100)
    card(fig)
    fig.text(0.07, 0.80, "Counting npm malware", fontsize=34, fontweight="bold", color=TEXT)
    fig.text(0.07, 0.71, "How reporting units change the trend, GitHub advisories, Oct 26 - Nov 22, 2026",
             fontsize=16, color=TEXT_MUTED)
    c = c.set_index("unit")
    for x, unit, lab, col in [(0.07, "records", "advisory records", C1),
                              (0.39, "exact_pairs", "exact version pairs", C3),
                              (0.71, "records_excl_template", "records, minus one\nnaming template", C2)]:
        fig.text(x, 0.42, f"{c.loc[unit, 'ratio_vs_prior3']:.2f}x", fontsize=64, fontweight="bold", color=col)
        fig.text(x, 0.33, lab, fontsize=16, color=TEXT, va="top")
    fig.text(0.07, 0.08, "Nov 16-22 compared with the mean of the three weeks before it", fontsize=14, color=TEXT_MUTED)
    fig.savefig(OUT / "social-card.png", dpi=100)
    plt.close(fig)


def main():
    OUT.mkdir(exist_ok=True)
    w = pd.read_csv(DATA / "weekly_units.csv")
    c = pd.read_csv(DATA / "week_comparison.csv")
    p = pd.read_csv(DATA / "pair_relations.csv")
    v = pd.read_csv(DATA / "versions.csv", dtype=str)
    weekly_units(w); template_split(w); focus_ratios(c); pair_relations(p); leadstack_upset(v); social(w, c)
    print(sorted(f.name for f in OUT.glob("*.png")))


if __name__ == "__main__":
    main()
