#!/usr/bin/env python3
"""Regenerate the article figures from the released sanitized CSV data.

Inputs  : the CSV datasets in the parent of this script's directory - in the
          published layout, the article evidence directory itself:
          /evidence/meta-muse-black-box-testing/
Outputs : the four SVG figures, written into that same evidence directory

No third-party dependencies: the SVG markup is written directly. Figures are
deliberately plain and theme-neutral so they stay readable on light and dark
backgrounds, and every figure carries <title>/<desc> for assistive technology.

All paths are resolved relative to this file, so the script can be run from any
current working directory and does not depend on the original release tree.
It never writes outside the article evidence directory.
"""

import csv
from pathlib import Path

TOOLS_DIR = Path(__file__).resolve().parent
EVIDENCE_DIR = TOOLS_DIR.parent
FIGURES_DIR = EVIDENCE_DIR

AXIS = "#6b7280"
TEXT = "#4b5563"
MUTED = "#8a919d"
BAR = "#64748b"
BAR_ALT = "#94a3b8"
FAIL = "#b23a2b"
OK = "#1f7a4d"
WARN = "#b45309"
GRID = "#d1d5db"

# Figure 04 palette. Light values are written as presentation attributes; the
# embedded `prefers-color-scheme: dark` block raises contrast for the graphite
# blog theme and for the always-dark lightbox viewer.
CONCURRENCY_LIGHT = {
    "surface": "#f8f9fa",
    "text": "#2f3640",
    "muted": "#6b7280",
    "grid": "#dcdfe4",
    "axis": "#9aa1ab",
    "burst": "#1f8ea8",
    "staggered": "#2f8f63",
}
CONCURRENCY_DARK = {
    "surface": "#181919",
    "text": "#e6e7e8",
    "muted": "#9ba1a4",
    "grid": "#2a2c2c",
    "axis": "#4a4d4d",
    "burst": "#4fd0e0",
    "staggered": "#5fce9b",
}
CONCURRENCY_WIDTH, CONCURRENCY_HEIGHT = 940, 540
CONCURRENCY_LEFT, CONCURRENCY_RIGHT = 92, 892
CONCURRENCY_PANEL_TOP = {"BURST-80": 92, "STAGGERED-80": 314}
CONCURRENCY_PANEL_HEIGHT = 150
CONCURRENCY_Y_MAX = 80
CONCURRENCY_X_MAX = 140
CONCURRENCY_CSV = "concurrency-burst80-vs-staggered80.csv"


def esc(value: str) -> str:
    return (
        str(value)
        .replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )


def text(x, y, value, size=12, anchor="start", fill=TEXT, weight="normal"):
    return (
        f'<text x="{x:.1f}" y="{y:.1f}" font-family="system-ui, sans-serif" '
        f'font-size="{size}" text-anchor="{anchor}" fill="{fill}" '
        f'font-weight="{weight}">{esc(value)}</text>'
    )


def rect(x, y, w, h, fill="none", stroke=None, dash=None, width=1, opacity=None):
    parts = [f'x="{x:.1f}"', f'y="{y:.1f}"', f'width="{max(w, 0):.1f}"', f'height="{max(h, 0):.1f}"', f'fill="{fill}"']
    if stroke:
        parts.append(f'stroke="{stroke}"')
        parts.append(f'stroke-width="{width}"')
    if dash:
        parts.append(f'stroke-dasharray="{dash}"')
    if opacity is not None:
        parts.append(f'opacity="{opacity}"')
    return "<rect " + " ".join(parts) + " />"


def line(x1, y1, x2, y2, stroke=AXIS, width=1, dash=None):
    parts = [f'x1="{x1:.1f}"', f'y1="{y1:.1f}"', f'x2="{x2:.1f}"', f'y2="{y2:.1f}"', f'stroke="{stroke}"', f'stroke-width="{width}"']
    if dash:
        parts.append(f'stroke-dasharray="{dash}"')
    return "<line " + " ".join(parts) + " />"


def document(width, height, title, desc, body):
    return (
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
        f'width="{width}" height="{height}" role="img" aria-labelledby="fig-title">\n'
        f"  <title id=\"fig-title\">{esc(title)}</title>\n"
        f"  <desc>{esc(desc)}</desc>\n"
        + "\n".join("  " + element for element in body)
        + "\n</svg>\n"
    )


def read_csv(name):
    with (EVIDENCE_DIR / name).open(encoding="utf-8") as handle:
        return list(csv.DictReader(handle))


def figure_failure_rate():
    rows = read_csv("experiments-summary.csv")
    width, height = 900, 430
    left, right, top, bottom = 80, 840, 80, 300
    y_max = 80.0

    def y(value):
        return bottom - (value / y_max) * (bottom - top)

    body = [
        text(40, 42, "Spawn failure rate by configuration", 18, fill="#374151", weight="600"),
        text(
            40,
            62,
            "Single run per configuration, 2026-09-13. Failure type: database lock timeout on subagent.spawn.",
            11.5,
            fill=MUTED,
        ),
    ]

    for tick in range(0, 81, 20):
        body.append(line(left, y(tick), right, y(tick), stroke=GRID if tick else AXIS, width=1))
        body.append(text(left - 10, y(tick) + 4, f"{tick}%", 11, anchor="end", fill=MUTED))

    order = ["PROBE-40", "BURST-80", "BURST-120", "STAGGERED-80"]
    by_id = {row["experiment_id"]: row for row in rows}
    bar_width = 104
    slot = (right - left) / len(order)

    for index, exp_id in enumerate(order):
        row = by_id[exp_id]
        value = float(row["failure_rate_percent"])
        center = left + (index + 0.5) * slot
        x = center - bar_width / 2
        color = FAIL if value >= 50 else BAR
        dashed = exp_id == "STAGGERED-80"
        bar_height = max(y(0) - y(value), 3)
        body.append(
            rect(
                x,
                y(value),
                bar_width,
                bar_height,
                fill="none" if dashed else color,
                stroke=OK if dashed else None,
                dash="5 4" if dashed else None,
                width=2,
            )
        )
        body.append(
            text(
                x + bar_width / 2,
                y(value) - 8,
                f"{value:g}%",
                13,
                anchor="middle",
                fill=OK if dashed else (FAIL if value >= 50 else "#374151"),
                weight="600",
            )
        )
        if exp_id == "STAGGERED-80":
            body.append(
                text(
                    x + bar_width / 2,
                    bottom + 54,
                    "different topology",
                    10,
                    anchor="middle",
                    fill=OK,
                )
            )
        body.append(
            text(x + bar_width / 2, bottom + 22, exp_id, 11.5, anchor="middle", fill="#374151", weight="600")
        )
        body.append(
            text(
                x + bar_width / 2,
                bottom + 38,
                f"{row['attempts']} attempts, {row['created']} created",
                10,
                anchor="middle",
                fill=MUTED,
            )
        )

    body.append(
        text(
            left + (2 + 0.5) * slot,
            y(72.5) - 26,
            "6.25% \u2192 72.5%",
            11,
            anchor="middle",
            fill=FAIL,
            weight="600",
        )
    )
    body.append(
        text(
            40,
            height - 34,
            "Burst variants only: 2.5% \u2192 6.25% \u2192 72.5%. STAGGERED-80 reached 0% while also delegating spawns",
            11,
            fill=MUTED,
        )
    )
    body.append(
        text(
            40,
            height - 18,
            "through a coordinator one level deeper, so the effect cannot be attributed to cadence alone.",
            11,
            fill=MUTED,
        )
    )

    return document(
        width,
        height,
        "Spawn failure rate by configuration",
        "Bar chart of database lock-timeout failure rates: PROBE-40 2.5 percent, BURST-80 6.25 percent, "
        "BURST-120 72.5 percent, and STAGGERED-80 0 percent under a different topology.",
        body,
    )


def figure_burst120_workers():
    rows = read_csv("burst-120-worker-timings.csv")
    rows.sort(key=lambda row: int(row["first_tool_utc"][11:13]) * 3600 + int(row["first_tool_utc"][14:16]) * 60 + int(row["first_tool_utc"][17:19]))

    def offset(stamp):
        h, m, s = int(stamp[11:13]), int(stamp[14:16]), int(stamp[17:19])
        return h * 3600 + m * 60 + s - (6 * 3600 + 45 * 60 + 32)

    width, height = 980, 660
    left, right = 96, 880
    top, bottom = 120, 600
    x_min, x_max = 24.0, 88.0
    row_height = (bottom - top) / len(rows)

    def x(value):
        return left + (value - x_min) / (x_max - x_min) * (right - left)

    body = [
        text(40, 40, "BURST-120: activity windows of the 33 workers that were created", 17, fill="#374151", weight="600"),
        text(
            40,
            62,
            "T0 = 06:45:32 UTC. A worker counts as active from its first tool call until its terminal record (1 s resolution).",
            11.5,
            fill=MUTED,
        ),
        text(
            40,
            80,
            "All 33 admissions were recorded at 06:46:01 UTC; the sweep line peaks at 33 active workers at 06:46:24 UTC.",
            11.5,
            fill=MUTED,
        ),
    ]

    for tick in range(30, 89, 10):
        body.append(line(x(tick), top - 12, x(tick), bottom + 4, stroke=GRID))
        body.append(text(x(tick), bottom + 20, f"+{tick}s", 10, anchor="middle", fill=MUTED))

    body.append(line(x(29), top - 24, x(29), bottom + 4, stroke=WARN, dash="6 4", width=1.5))
    body.append(text(x(29), top - 30, "admissions 06:46:01 (+29 s)", 10.5, anchor="middle", fill=WARN))
    body.append(line(x(52), top - 24, x(52), bottom + 4, stroke=FAIL, dash="2 3", width=1.5))
    body.append(text(x(52), top - 30, "peak 33 active (+52 s)", 10.5, anchor="middle", fill=FAIL))

    for index, row in enumerate(rows):
        start = offset(row["first_tool_utc"])
        end = offset(row["finished_utc"])
        y = top + index * row_height
        unrecoverable = row["workload_status"] != "confirmed_full_workload"
        body.append(
            rect(
                x(start),
                y,
                x(end) - x(start),
                row_height - 4,
                fill="none" if unrecoverable else BAR_ALT,
                stroke=WARN if unrecoverable else None,
                dash="3 2" if unrecoverable else None,
                width=1.5,
            )
        )
        body.append(
            text(left - 12, y + row_height - 8, row["attempt"], 9.5, anchor="end", fill=WARN if unrecoverable else TEXT)
        )

    body.append(
        text(
            40,
            height - 30,
            "Solid bars: workload confirmed for 32 workers (activity 32-43 s). Dashed bar: C-85, whose terminal record",
            11,
            fill=MUTED,
        )
    )
    body.append(
        text(40, height - 14, "exists but whose workload completion cannot be recovered from durable data.", 11, fill=MUTED)
    )

    return document(
        width,
        height,
        "BURST-120 worker activity windows",
        "Horizontal bars for the 33 created workers, showing first tool call and terminal record between "
        "06:46:04 and 06:46:56 UTC; C-85 is marked as unrecoverable.",
        body,
    )


def figure_admission_cadence():
    rows = {row["experiment_id"]: row for row in read_csv("experiments-summary.csv")}
    width, height = 940, 380
    left, right = 170, 860
    x_max = 100.0

    def x(value):
        return left + (value / x_max) * (right - left)

    body = [
        text(40, 40, "How the spawn attempts were spread in time", 17, fill="#374151", weight="600"),
        text(
            40,
            62,
            "Seconds after each burst was issued. Three admission shapes, three observed outcomes.",
            11.5,
            fill=MUTED,
        ),
    ]

    for tick in range(0, 101, 25):
        body.append(line(x(tick), 92, x(tick), 300, stroke=GRID))
        body.append(text(x(tick), 318, f"+{tick}s", 10, anchor="middle", fill=MUTED))

    lanes = [
        ("BURST-80", 18, 38, "75 admissions over ~20 s \u2014 5 lock timeouts (6.25%)", BAR),
        ("STAGGERED-80", 4, 93, "80 admissions, mean gap 1.1266 s (planned 100-200 ms) \u2014 0 timeouts", OK),
        ("BURST-120", 29, 30, "33 admissions within one second \u2014 87 lock timeouts (72.5%)", FAIL),
    ]

    lane_top = 100
    lane_gap = 66
    for index, (label, start, end, note, color) in enumerate(lanes):
        y = lane_top + index * lane_gap
        body.append(text(left - 16, y + 24, label, 12, anchor="end", fill="#374151", weight="600"))
        body.append(rect(x(start), y, x(end) - x(start), 30, fill=color, opacity="0.85"))
        body.append(text(x(start), y + 48, note, 11, fill=TEXT))
        body.append(
            text(
                left - 16,
                y + 60,
                f"{rows[label]['attempts']} attempts, {rows[label]['created']} created",
                10,
                anchor="end",
                fill=MUTED,
            )
        )

    body.append(
        text(
            40,
            height - 34,
            "Admission windows come from database admission records; the staggered cadence was recomputed from the released",
            11,
            fill=MUTED,
        )
    )
    body.append(
        text(
            40,
            height - 18,
            "worker activity rows. Admission policy and any internal queueing are not recorded in the trace.",
            11,
            fill=MUTED,
        )
    )

    return document(
        width,
        height,
        "Admission cadence per configuration",
        "Timeline comparison: BURST-80 admitted 75 workers over twenty seconds, STAGGERED-80 admitted 80 workers "
        "over eighty-nine seconds, and BURST-120 admitted 33 workers within one second.",
        body,
    )


def figure_concurrency_comparison():
    """Figure 04: observed active-agent concurrency, BURST-80 vs STAGGERED-80.

    Draws the two step lines exactly as recorded in the aggregate change-point
    CSV: no smoothing, no interpolation, no extrapolation. The plot carries
    only the title, the two panel labels, the shared axes, the two curves, the
    peak annotations and one short topology note - methodology and provenance
    live in the article figcaption.
    """
    rows = read_csv(CONCURRENCY_CSV)
    series = {}
    for row in rows:
        series.setdefault(row["configuration"], []).append(
            (int(row["relative_second"]), int(row["active_agents"]))
        )
    for points in series.values():
        points.sort()

    def conc_text(x, y, value, size=12.5, anchor="start", css="t-text", weight="normal", fill=None):
        fill_attr = f' fill="{fill}"' if fill else ""
        return (
            f'<text class="{css}" x="{x:.1f}" y="{y:.1f}" '
            f'font-family="system-ui, sans-serif" font-size="{size}" '
            f'text-anchor="{anchor}" font-weight="{weight}"{fill_attr}>{esc(value)}</text>'
        )

    def conc_line(x1, y1, x2, y2, css="g-grid", stroke=None, width=1):
        stroke_attr = f' stroke="{stroke}"' if stroke else ""
        return (
            f'<line class="{css}" x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}"'
            f' stroke-width="{width}"{stroke_attr} />'
        )

    def x(second):
        return CONCURRENCY_LEFT + (
            second / CONCURRENCY_X_MAX
        ) * (CONCURRENCY_RIGHT - CONCURRENCY_LEFT)

    def y(active, top):
        return (
            top
            + CONCURRENCY_PANEL_HEIGHT
            - (active / CONCURRENCY_Y_MAX) * CONCURRENCY_PANEL_HEIGHT
        )

    body = [
        f'<rect class="bg" x="0" y="0" width="{CONCURRENCY_WIDTH}" height="{CONCURRENCY_HEIGHT}" '
        f'fill="{CONCURRENCY_LIGHT["surface"]}" />',
        conc_text(
            36,
            38,
            "Observed active-agent concurrency: BURST-80 vs STAGGERED-80",
            20,
            css="t-text",
            weight="600",
            fill=CONCURRENCY_LIGHT["text"],
        ),
    ]

    # shared axes for both panels
    for active in range(0, CONCURRENCY_Y_MAX + 1, 20):
        for top in CONCURRENCY_PANEL_TOP.values():
            body.append(
                conc_line(
                    CONCURRENCY_LEFT,
                    y(active, top),
                    CONCURRENCY_RIGHT,
                    y(active, top),
                    css="g-grid" if active else "g-axis",
                    stroke=CONCURRENCY_LIGHT["grid"] if active else CONCURRENCY_LIGHT["axis"],
                )
            )
            body.append(
                conc_text(
                    CONCURRENCY_LEFT - 10,
                    y(active, top) + 4,
                    str(active),
                    12.5,
                    anchor="end",
                    css="t-muted",
                    fill=CONCURRENCY_LIGHT["muted"],
                )
            )

    for second in range(0, CONCURRENCY_X_MAX + 1, 20):
        for top in CONCURRENCY_PANEL_TOP.values():
            body.append(
                conc_line(
                    x(second),
                    top,
                    x(second),
                    top + CONCURRENCY_PANEL_HEIGHT,
                    css="g-grid",
                    stroke=CONCURRENCY_LIGHT["grid"],
                )
            )
        body.append(
            conc_text(
                x(second),
                CONCURRENCY_PANEL_TOP["STAGGERED-80"] + CONCURRENCY_PANEL_HEIGHT + 24,
                f"+{second}s",
                12.5,
                anchor="middle",
                css="t-muted",
                fill=CONCURRENCY_LIGHT["muted"],
            )
        )

    labels = {
        "BURST-80": ("BURST-80", "burst", CONCURRENCY_LIGHT["burst"]),
        "STAGGERED-80": ("STAGGERED-80", "staggered", CONCURRENCY_LIGHT["staggered"]),
    }

    for name, (label, css, colour) in labels.items():
        top = CONCURRENCY_PANEL_TOP[name]
        points = series[name]
        body.append(
            conc_text(
                CONCURRENCY_LEFT,
                top - 14,
                label,
                14.5,
                css="t-text",
                weight="600",
                fill=CONCURRENCY_LIGHT["text"],
            )
        )

        # step line: horizontal runs with vertical transitions, exactly as recorded
        path = [f"M {x(points[0][0]):.1f} {y(points[0][1], top):.1f}"]
        for index in range(1, len(points)):
            previous_x, previous_value = points[index - 1]
            current_x, current_value = points[index]
            path.append(f"L {x(current_x):.1f} {y(previous_value, top):.1f}")
            path.append(f"L {x(current_x):.1f} {y(current_value, top):.1f}")
        body.append(
            f'<path class="c-{css}" d="{" ".join(path)}" fill="none" stroke="{colour}" '
            f'stroke-width="2" stroke-linejoin="round" stroke-linecap="round" />'
        )

        peak_second, peak_active = max(points, key=lambda item: item[1])
        peak_x, peak_y = x(peak_second), y(peak_active, top)
        body.append(
            f'<circle class="p-{css}" cx="{peak_x:.1f}" cy="{peak_y:.1f}" r="4.5" '
            f'fill="{CONCURRENCY_LIGHT["surface"]}" stroke="{colour}" stroke-width="2.5" />'
        )
        anchor = "start" if peak_x < CONCURRENCY_RIGHT - 190 else "end"
        offset = 12 if anchor == "start" else -12
        body.append(
            conc_text(
                peak_x + offset,
                peak_y - 12,
                f"peak {peak_active} at +{peak_second}s",
                13,
                anchor=anchor,
                css=f"t-{css}",
                weight="600",
                fill=colour,
            )
        )

    body.append(
        conc_text(
            36,
            CONCURRENCY_HEIGHT - 16,
            "STAGGERED-80 also changed topology.",
            12.5,
            css="t-muted",
            fill=CONCURRENCY_LIGHT["muted"],
        )
    )

    style = "\n".join(
        [
            "  .bg { fill: %s; }" % CONCURRENCY_LIGHT["surface"],
            "  .t-text { fill: %s; }" % CONCURRENCY_LIGHT["text"],
            "  .t-muted { fill: %s; }" % CONCURRENCY_LIGHT["muted"],
            "  .g-grid { stroke: %s; }" % CONCURRENCY_LIGHT["grid"],
            "  .g-axis { stroke: %s; }" % CONCURRENCY_LIGHT["axis"],
            "  .c-burst, .p-burst { stroke: %s; }" % CONCURRENCY_LIGHT["burst"],
            "  .t-burst { fill: %s; }" % CONCURRENCY_LIGHT["burst"],
            "  .c-staggered, .p-staggered { stroke: %s; }" % CONCURRENCY_LIGHT["staggered"],
            "  .t-staggered { fill: %s; }" % CONCURRENCY_LIGHT["staggered"],
            "  @media (prefers-color-scheme: dark) {",
            "    .bg { fill: %s; }" % CONCURRENCY_DARK["surface"],
            "    .t-text { fill: %s; }" % CONCURRENCY_DARK["text"],
            "    .t-muted { fill: %s; }" % CONCURRENCY_DARK["muted"],
            "    .g-grid { stroke: %s; }" % CONCURRENCY_DARK["grid"],
            "    .g-axis { stroke: %s; }" % CONCURRENCY_DARK["axis"],
            "    .c-burst, .p-burst { stroke: %s; }" % CONCURRENCY_DARK["burst"],
            "    .t-burst { fill: %s; }" % CONCURRENCY_DARK["burst"],
            "    .c-staggered, .p-staggered { stroke: %s; }" % CONCURRENCY_DARK["staggered"],
            "    .t-staggered { fill: %s; }" % CONCURRENCY_DARK["staggered"],
            "  }",
        ]
    )

    svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {CONCURRENCY_WIDTH} {CONCURRENCY_HEIGHT}" '
        f'width="{CONCURRENCY_WIDTH}" height="{CONCURRENCY_HEIGHT}" role="img" aria-labelledby="fig-title">\n'
        f'  <title id="fig-title">Observed active-agent concurrency over time: BURST-80 versus STAGGERED-80</title>\n'
        f"  <desc>Two stacked step lines with a shared 0 to 80 active-agents axis and a shared 0 to 140 seconds "
        f"axis relative to each experiment's start. BURST-80 peaks at 72 active agents at +55 seconds; "
        f"STAGGERED-80 peaks at 38 at +45 seconds. STAGGERED-80 also changed topology.</desc>\n"
        f"  <style>\n{style}\n  </style>\n"
        + "\n".join("  " + element for element in body)
        + "\n</svg>\n"
    )

    # No methodology, provenance or absolute timestamps belong inside the plot.
    leftovers = [
        needle
        for needle in ("sweep", "provenance", "archived", "UTC", "resolution", "topology; this")
        if needle.lower() in svg.lower()
    ]
    assert not leftovers, f"unexpected plot text in figure 04: {leftovers}"

    return svg


def main():
    FIGURES_DIR.mkdir(parents=True, exist_ok=True)
    figures = {
        "figure-01-failure-rate.svg": figure_failure_rate(),
        "figure-02-burst-120-workers.svg": figure_burst120_workers(),
        "figure-03-admission-cadence.svg": figure_admission_cadence(),
        "figure-04-concurrency-burst80-vs-staggered80.svg": figure_concurrency_comparison(),
    }
    for name, content in figures.items():
        path = FIGURES_DIR / name
        path.write_text(content, encoding="utf-8")
        print(f"wrote {path}")


if __name__ == "__main__":
    main()
