#!/usr/bin/env python3
"""
Interactive stacked bar chart of per-round BFS time, from a CSV written by
`./main` (stats.csv by default).

  ./plot [stats.csv] [-o stats.html] [--title TITLE] [--no-open]

Each bar is one round. Segments are the timed phases of the round, plus
"other" for whatever part of the round's total time is not covered by a phase.
Hovering a round shows its times and counts. Lines for the frontier and
BENV sizes are overlaid on a secondary (right) y-axis; click their legend
entries to toggle them.

Writes an HTML page (Plotly, loaded from a CDN) and opens it in the web
browser. Zoom with scroll / trackpad pinch or by dragging a box; double-click
to reset.
"""

import argparse
import csv
import html
import json
import os
import webbrowser
from collections import defaultdict

parser = argparse.ArgumentParser()
parser.add_argument("csv", nargs="?", default="stats.csv")
parser.add_argument("-o", "--output", default="stats.html")
parser.add_argument("--title", default="BFS time per round")
parser.add_argument("--no-open", action="store_true",
                    help="don't open the chart in the web browser")
args = parser.parse_args()

phases = []  # timed phase labels, in order of first appearance
count_labels = []  # count labels, in order of first appearance
times = defaultdict(dict)  # round -> label -> seconds
counts = defaultdict(dict)  # round -> label -> int
with open(args.csv) as f:
    for row in csv.DictReader(f):
        r, label = int(row["round"]), row["label"]
        if row["kind"] == "time":
            times[r][label] = float(row["value"])
            if label != "total time" and label not in phases:
                phases.append(label)
        else:
            counts[r][label] = int(row["value"])
            if label not in count_labels:
                count_labels.append(label)

rounds = sorted(set(times) | set(counts))
data = {
    "rounds": rounds,
    "phases": phases,
    "times": {p: [times[r].get(p, 0.0) for r in rounds] for p in phases},
    "total": [times[r].get("total time", 0.0) for r in rounds],
    "count_labels": count_labels,
    "counts": {c: [counts[r].get(c) for r in rounds] for c in count_labels},
}

PAGE = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>__TITLE__</title>
<script src="https://cdn.jsdelivr.net/npm/plotly.js-dist-min@2.35.2/plotly.min.js"></script>
<style>
  :root {
    --surface: #fcfcfb; --text: #1a1a19; --muted: #6b6a63; --grid: #e4e3de;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --surface: #1a1a19; --text: #f0efec; --muted: #c3c2b7; --grid: #34332f;
    }
  }
  html, body { margin: 0; height: 100%; background: var(--surface); }
  body {
    display: flex; flex-direction: column; box-sizing: border-box;
    padding: 16px; font-family: system-ui, sans-serif; color: var(--text);
  }
  h1 { font-size: 16px; font-weight: 600; margin: 0 0 4px; }
  p { font-size: 12px; color: var(--muted); margin: 0 0 8px; }
  #chart { flex: 1; min-height: 300px; }
</style>
</head>
<body>
<h1>__TITLE__</h1>
<p>Scroll or pinch to zoom, drag to box-zoom, double-click to reset.</p>
<div id="chart"></div>
<script>
const DATA = __DATA__;

const dark = window.matchMedia("(prefers-color-scheme: dark)").matches;
const css = getComputedStyle(document.documentElement);
const tok = (name) => css.getPropertyValue(name).trim();
// categorical slots in fixed order; "other" is a neutral gray
const SERIES = dark
  ? ["#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#008300"]
  : ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"];
const OTHER = dark ? "#6b6a63" : "#b4b3ad";

const fmtTime = (s) => s >= 0.1 ? s.toFixed(3) + "s" : (s * 1000).toFixed(3) + "ms";
const n = DATA.rounds.length;

const other = DATA.total.map((t, i) =>
  Math.max(0, t - DATA.phases.reduce((acc, p) => acc + DATA.times[p][i], 0)));

// hover summary for a round: all of its times and counts
const summary = DATA.rounds.map((r, i) => {
  const lines = [`<b>round ${r}</b>   total ${fmtTime(DATA.total[i])}`];
  for (const p of DATA.phases) lines.push(`${p}: ${fmtTime(DATA.times[p][i])}`);
  lines.push(`other: ${fmtTime(other[i])}`);
  for (const c of DATA.count_labels) {
    const v = DATA.counts[c][i];
    if (v !== null) lines.push(`${c}: ${v.toLocaleString()}`);
  }
  return lines.join("<br>");
});

// colors follow the phase (order of first appearance), but the stacking
// order, bottom to top, is: STACK_ORDER, then any other phases, then "other"
const STACK_ORDER = [
  "inject time", "build visited",
  "frontier' build", "filter visited",
  "compute offsets", "BENV build",
];
const stackRank = (p) =>
  STACK_ORDER.includes(p) ? STACK_ORDER.indexOf(p) : STACK_ORDER.length;
const segments = DATA.phases
  .map((p, k) => ({ name: p, y: DATA.times[p], color: SERIES[k % SERIES.length] }))
  .sort((a, b) => stackRank(a.name) - stackRank(b.name));
segments.push({ name: "other", y: other, color: OTHER });

const bars = segments.map((s) => ({
  type: "bar",
  name: s.name,
  x: DATA.rounds,
  y: s.y,
  // surface-colored outline = gap between stacked segments
  // (dropped when there are so many rounds that bars are only a few pixels wide)
  marker: { color: s.color, line: { color: tok("--surface"), width: n <= 100 ? 1 : 0 } },
  text: summary,
  textposition: "none",
  hovertemplate: "%{text}<extra></extra>",
  legendgroup: "time",
  legendgrouptitle: { text: "time" },
}));

// size lines, on the secondary y-axis; colors continue the categorical order
const SIZES = ["frontier size", "BENV size", "visited size"].filter((c) => c in DATA.counts);
const lines = SIZES.map((c, j) => ({
  type: "scatter",
  mode: "lines+markers",
  name: c,
  x: DATA.rounds,
  y: DATA.counts[c],
  yaxis: "y2",
  line: { color: SERIES[(DATA.phases.length + j) % SERIES.length], width: 2 },
  marker: { size: 8, line: { color: tok("--surface"), width: 2 } },
  hovertemplate: `${c}: %{y:,}<extra></extra>`,
  legendgroup: "size",
  legendgrouptitle: { text: "size (right axis)" },
}));

const traces = [...bars, ...lines];

const layout = {
  barmode: "stack",
  bargap: 0.05,
  paper_bgcolor: tok("--surface"),
  plot_bgcolor: tok("--surface"),
  font: { family: "system-ui, sans-serif", size: 12, color: tok("--muted") },
  margin: { l: 64, r: 64, t: 8, b: 48 },
  hovermode: "closest",
  hoverlabel: {
    align: "left",
    bgcolor: tok("--surface"),
    bordercolor: tok("--grid"),
    font: { color: tok("--text") },
  },
  dragmode: "zoom",
  xaxis: {
    title: { text: "round" },
    tickmode: n <= 40 ? "linear" : "auto",
    range: [DATA.rounds[0] - 0.6, DATA.rounds[n - 1] + 0.6],
    showgrid: false, zeroline: false, linecolor: tok("--grid"),
  },
  yaxis: {
    title: { text: "time (s)" },
    gridcolor: tok("--grid"), zeroline: false, rangemode: "tozero",
  },
  yaxis2: {
    title: { text: "size" },
    overlaying: "y", side: "right",
    showgrid: false, zeroline: false, rangemode: "tozero",
  },
  legend: {
    traceorder: "grouped+reversed", groupclick: "toggleitem",
    x: 1.08, xanchor: "left", font: { color: tok("--text") },
  },
};

Plotly.newPlot("chart", traces, layout, {
  responsive: true,
  scrollZoom: true,
  displaylogo: false,
  modeBarButtonsToRemove: ["lasso2d", "select2d"],
});
</script>
</body>
</html>
"""

page = (PAGE
        .replace("__TITLE__", html.escape(args.title))
        .replace("__DATA__", json.dumps(data).replace("</", "<\\/")))
with open(args.output, "w") as f:
    f.write(page)
print(f"wrote {args.output}")

if not args.no_open:
    webbrowser.open("file://" + os.path.abspath(args.output))
