#!/usr/bin/env python3
"""Reproduce the rail figure: read rail-traffic-and-track.csv → HTML+SVG → 2x PNG via headless Chrome.

This file sits in public/data/ because it is published: readers are told they can
regenerate the figure from the CSV, and pointing them at a file inside a repository
would stop working the moment the repository stopped being public. It is not part of
the site build — the PNG is rendered once here and committed.

Usage:
  python3 public/data/make_figure_rail.py   # writes build/fig-rail.html + public/figures/rail-track-vs-traffic.png
Data source: World Bank WDI (CC BY 4.0), see the CSV header for indicator codes + retrieval date.
"""
import csv
import os
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))   # public/data/ → repository root
CSV = os.path.join(HERE, "rail-traffic-and-track.csv")
OUT_HTML = os.path.join(ROOT, "build", "fig-rail.html")
OUT_PNG = os.path.join(ROOT, "public", "figures", "rail-track-vs-traffic.png")
W = 1440          # canvas width (px, 1x)
WIN = W - 80      # drawing width inside .fig padding (40px each side)
SCALE = 2

# ---- data ------------------------------------------------------------------
series = {}      # (country, year) -> dict
countries = ["CHN", "USA", "IND"]
with open(CSV) as f:
    rows = [r for r in f if not r.startswith("#")]
for row in csv.DictReader(rows):
    c, y = row["country"], int(row["year"])
    if c not in countries:
        continue
    series[(c, y)] = {k: (float(v) if v else None) for k, v in row.items() if k not in ("country", "year")}


def line(metric, c):
    """Series in the panel's unit (route_km → thousand km, passenger/freight mn → bn)."""
    div = 1000.0
    pts = [(y, series[(c, y)][metric] / div) for y in range(1995, 2022)
           if (c, y) in series and series[(c, y)][metric]]
    return pts


NAMES = {"CHN": "China", "USA": "United States", "IND": "India"}

# numbers used in the headline/annotation (2019 = last pre-COVID year)
def at(c, y, m):
    return series[(c, y)][m]


chn19, usa19 = at("CHN", 2019, "passenger_km_mn"), at("USA", 2019, "passenger_km_mn")
ratio19 = chn19 / usa19
route19 = at("CHN", 2019, "route_km") / at("USA", 2019, "route_km") * 100


# ---- svg helpers -----------------------------------------------------------
OFFSCALE = []   # (metric, country, year, value, ymax) — 画出画布外的点，必须为 0


def panel(x0, y0, w, h, title, unit, ymax, metric, yticks, note=None):
    """Return SVG for one panel with real axes."""
    pad_l, pad_b, pad_t = 84, 46, 58
    px, py = x0 + pad_l, y0 + pad_t
    pw, ph = w - pad_l - 150, h - pad_t - pad_b   # leave room for direct end labels

    def sx(year):
        return px + (year - 1995) / (2021 - 1995) * pw

    def sy(v):
        return py + ph - (v / ymax) * ph

    out = [f'<text class="ptitle" x="{x0}" y="{y0 + 26}">{title}</text>',
           f'<text class="pun" x="{x0}" y="{y0 + 48}">{unit}</text>']
    # y ticks + hairlines
    for t in yticks:
        yy = sy(t)
        out.append(f'<line class="hair" x1="{px}" y1="{yy:.1f}" x2="{px + pw}" y2="{yy:.1f}"/>')
        out.append(f'<text class="tick" x="{px - 10}" y="{yy + 4:.1f}" text-anchor="end">{t:,}</text>')
    # x ticks
    for yr in range(1995, 2022, 5):
        xx = sx(yr)
        out.append(f'<line class="hairx" x1="{xx:.1f}" y1="{py + ph}" x2="{xx:.1f}" y2="{py + ph + 6}"/>')
        out.append(f'<text class="tick" x="{xx:.1f}" y="{py + ph + 24}" text-anchor="middle">{yr}</text>')
    # axis
    out.append(f'<line class="axis" x1="{px}" y1="{py}" x2="{px}" y2="{py + ph}"/>')
    out.append(f'<line class="axis" x1="{px}" y1="{py + ph}" x2="{px + pw}" y2="{py + ph}"/>')
    # series (draw grey ones first, focus last)
    order = [c for c in countries if c != "CHN"] + ["CHN"]
    for c in order:
        pts = line(metric, c)
        if not pts:
            continue
        focus = c == "CHN"
        cls = "l-focus" if focus else ("l-usa" if c == "USA" else "l-ind")
        d = " ".join(f'{"M" if i == 0 else "L"}{sx(y):.1f},{sy(v):.1f}' for i, (y, v) in enumerate(pts))
        for y, v in pts:                      # 越界点=画布外的线，静态检查拦下
            if v > ymax:
                OFFSCALE.append((metric, c, y, v, ymax))
        out.append(f'<path class="{cls}" d="{d}"/>')
        ly, lv = pts[-1]
        out.append(f'<circle class="{"dot-focus" if focus else "dot"}" cx="{sx(ly):.1f}" cy="{sy(lv):.1f}" r="3.5"/>')
        out.append(f'<text class="endlabel {"el-focus" if focus else ""}" x="{sx(ly) + 9:.1f}" y="{sy(lv) + 4:.1f}">{NAMES[c]}</text>')
    if note:
        out.append(note(px, py, pw, ph, sx, sy))
    return "\n".join(out)


def note_a(px, py, pw, ph, sx, sy):
    return (f'<text class="annot" x="{px + 24}" y="{py + 26}">'
            f'China, 2019: <tspan class="k">{route19:.0f}%</tspan> of America\u2019s route-km</text>')


def note_b(px, py, pw, ph, sx, sy):
    """Annotate the 2019 multiple + the COVID dip, inside the plot."""
    x19 = sx(2019)
    return "\n".join([
        f'<line class="vline" x1="{x19:.1f}" y1="{py}" x2="{x19:.1f}" y2="{py + ph}"/>',
        f'<text class="annot" x="{px + 24}" y="{py + 26}">China, 2019: <tspan class="k">{ratio19:.0f}\u00d7</tspan>'
        f' the US</text>',
        f'<text class="annot2" x="{px + pw:.1f}" y="{sy(1150):.1f}" text-anchor="end">2020\u201321:'
        f' the fall is Covid \u2014 and the US stopped reporting</text>',
    ])


panels = [
    panel(0, 0, WIN, 470, "Track", "thousand route-km, all railways", 220, "route_km",
          [0, 50, 100, 150, 200], note_a),
    panel(0, 520, WIN, 560, "Traffic", "billion passenger-km a year", 1500, "passenger_km_mn",
          [0, 500, 1000, 1500], note_b),
]

HTML = f"""<!doctype html><meta charset="utf-8"><title>rail figure</title>
<style>
  :root {{ --ink:#1c1a17; --ink2:#57534b; --ink3:#8b857a; --hair:#e6e1d8; --accent:#b8562f;
           --grey:#8d8880; --ind:#c2a58c; --paper:#fdfcfa; }}
  * {{ box-sizing:border-box }}
  html,body {{ margin:0; background:var(--paper); }}
  .fig {{ width:{W}px; padding:44px 40px 28px; font-family:'Inter','Helvetica Neue',Arial,sans-serif; color:var(--ink); }}
  .headline {{ font-size:38px; font-weight:700; letter-spacing:-.01em; margin:0 0 10px; line-height:1.15 }}
  .deck {{ font-size:19px; color:var(--ink2); margin:0 0 26px; max-width:1180px; line-height:1.45 }}
  .ptitle {{ font-size:23px; font-weight:650; fill:var(--ink) }}
  .pun {{ font-size:17px; fill:var(--ink2) }}
  .tick {{ font-size:16px; fill:var(--ink3); font-variant-numeric:tabular-nums }}
  .hair {{ stroke:var(--hair); stroke-width:1 }}
  .hairx {{ stroke:var(--ink3); stroke-width:1 }}
  .axis {{ stroke:#b9b2a6; stroke-width:1.4 }}
  .l-focus {{ fill:none; stroke:var(--accent); stroke-width:3.2; stroke-linejoin:round }}
  .l-usa {{ fill:none; stroke:var(--grey); stroke-width:2.2 }}
  .l-ind {{ fill:none; stroke:var(--ind); stroke-width:2.2; stroke-dasharray:7 5 }}
  .dot {{ fill:var(--grey) }} .dot-focus {{ fill:var(--accent) }}
  .endlabel {{ font-size:17px; fill:var(--ink2) }} .el-focus {{ fill:var(--accent); font-weight:650 }}
  .annot {{ font-size:21px; fill:var(--ink2) }}
  .annot2 {{ font-size:17px; fill:var(--ink3) }}
  .annot .k {{ font-size:30px; font-weight:750; fill:var(--accent) }}
  .vline {{ stroke:var(--ink3); stroke-width:1; stroke-dasharray:5 5; opacity:.7 }}
  .foot {{ margin-top:26px; font-size:15px; color:var(--ink3); line-height:1.5 }}
  .foot b {{ color:var(--ink2); font-weight:600 }}
</style>
<div class="fig" data-qa>
  <div class="headline" data-qa>The US has more track. China runs 44&times; the traffic.</div>
  <div class="deck" data-qa>Railways, 1995&ndash;2021. Route length and passenger traffic from the same source, so the two
    panels can be read together. India is dashed for reference: it sits between the two on track, far below China on traffic.</div>
  <svg width="{WIN}" height="1080" viewBox="0 0 {WIN} 1080" data-qa>
    {"".join(panels)}
  </svg>
  <div class="foot" data-qa><b>Data:</b> World Bank World Development Indicators &mdash; <i>Rail lines (total route-km)</i>
    and <i>Railways, passengers carried</i>, retrieved 2026-10-12 (WDI update 2026-10-08). Both panels use the same
    country-years; 2021 passenger-km is missing for the US, so the left end of that line is 2020.
    <b>Reuse:</b> figure and data CC BY 4.0 &mdash; copy it, link back to this page.</div>
</div>
<pre id="qa" style="display:none"></pre>
<script>
  const innermost = [...document.querySelectorAll('[data-qa]')].filter(el => !el.querySelector('[data-qa]'));
  const fig = document.querySelector('.fig').getBoundingClientRect();
  const boxes = innermost.map(el => ({{ el, r: el.getBoundingClientRect(), t: (el.textContent||'').trim().slice(0,40) }}))
                         .filter(b => b.t.length);
  const outOfBox = boxes.filter(b => b.r.left < fig.left - 0.5 || b.r.right > fig.right + 0.5 ||
                                     b.r.top < fig.top - 0.5 || b.r.bottom > fig.bottom + 0.5)
                        .map(b => b.t);
  const overlaps = [];
  for (let i = 0; i < boxes.length; i++) for (let j = i + 1; j < boxes.length; j++) {{
    const a = boxes[i].r, b = boxes[j].r;
    const ox = Math.min(a.right,b.right) - Math.max(a.left,b.left);
    const oy = Math.min(a.bottom,b.bottom) - Math.max(a.top,b.top);
    if (ox > 0 && oy > 0 && ox * oy > 80) overlaps.push([boxes[i].t, boxes[j].t, Math.round(ox*oy)]);
  }}
  const svg = document.querySelector('svg');
  const svgBox = svg.getBoundingClientRect();
  const clipped = [...svg.querySelectorAll('text')].filter(t => {{
    const r = t.getBoundingClientRect();
    return r.left < svgBox.left - 0.5 || r.right > svgBox.right + 0.5 || r.top < svgBox.top - 0.5 || r.bottom > svgBox.bottom + 0.5;
  }}).map(t => (t.textContent||'').slice(0,40));
  document.getElementById('qa').textContent = JSON.stringify({{
    height: Math.ceil(document.body.scrollHeight), width: document.body.scrollWidth,
    outOfBox, overlaps, clipped,
    overflowX: document.body.scrollWidth > {W}
  }});
</script>
"""

os.makedirs(os.path.dirname(OUT_HTML), exist_ok=True)
os.makedirs(os.path.dirname(OUT_PNG), exist_ok=True)
open(OUT_HTML, "w").write(HTML)
print("wrote", OUT_HTML)

dump = subprocess.run(["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", "--hide-scrollbars",
                       "--force-device-scale-factor=1", "--virtual-time-budget=4000", "--dump-dom",
                       f"file://{OUT_HTML}"], capture_output=True, text=True).stdout
import json
import re

m = re.search(r'<pre id="qa"[^>]*>(.*?)</pre>', dump, re.S)
qa = json.loads(m.group(1)) if m else {"error": "qa not found"}
print("QA:", json.dumps(qa, ensure_ascii=False)[:600])
print("OFFSCALE (画布外的点):", OFFSCALE if OFFSCALE else "0")
if OFFSCALE:
    print("!! 有系列点超出 y 轴范围：调大 ymax 再出图", file=sys.stderr)
    sys.exit(4)

subprocess.run(["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", "--hide-scrollbars",
                f"--force-device-scale-factor={SCALE}", "--virtual-time-budget=4000",
                f"--window-size={W},{qa.get('height', 1200)}", f"--screenshot={OUT_PNG}",
                f"file://{OUT_HTML}"], capture_output=True)
print("wrote", OUT_PNG, os.path.getsize(OUT_PNG), "bytes")
sys.exit(0 if not (qa.get("overlaps") or qa.get("clipped") or qa.get("overflowX") or qa.get("outOfBox")) else 3)
