"""Static SVG line chart (perplexity vs sparsity, log y) for posting in a Sakura room.

Sakura's SVG rules: no script, CSS, links, images, filters or animation; explicit colors; <= 32 KiB and
<= 256 tags. Colors are the dataviz reference palette (light): categorical slots 1-3 and the chart ink.
"""
import json
import math
import sys

SURFACE, INK, INK2, MUTED, GRID, AXIS = "#fcfcfb", "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7"
SERIES = [("layerwise", "層ごと(layer-wise)", "#2a78d6"),
          ("global", "全体まとめて(global)", "#eb6834"),
          ("random", "ランダム", "#1baf7a")]
W, H = 760, 470
X0, X1, Y0, Y1 = 78, 728, 118, 410  # plot area


def main(path, out, stop_ratio=0.0):
    rows = [json.loads(line) for line in open(path) if line.strip()]
    dense = [r for r in rows if r["method"] == "dense"][-1]
    data = {m: sorted((r["sparsity"], r["ppl"]) for r in rows if r["method"] == m) for m, _, _ in SERIES}
    top = max([p for pts in data.values() for _, p in pts if math.isfinite(p)] + [dense["ppl"]])
    lo, hi = math.log10(5), math.ceil(math.log10(top) + 1e-9)
    xmax = math.ceil((max(s for pts in data.values() for s, _ in pts) + 0.05) * 20 - 1e-9) / 20  # one 5% step past the last point
    xs = lambda s: X0 + (X1 - X0) * s / xmax
    ys = lambda p: Y1 - (Y1 - Y0) * (min(math.log10(p), hi) - lo) / (hi - lo)

    e = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" font-family="sans-serif">',
         f'<rect x="0.5" y="0.5" width="{W - 1}" height="{H - 1}" rx="8" fill="{SURFACE}" stroke="{GRID}"/>',
         f'<text x="24" y="34" fill="{INK}" font-size="17" font-weight="bold">Gemma 4 E2B:刈った割合と perplexity(学習し直しなし)</text>',
         f'<text x="24" y="56" fill="{INK2}" font-size="12">WikiText-2 テスト {dense["windows"]}ウィンドウ × {dense["seq_len"]}トークン。'
         f'対象は decoder の attention と MLP の{dense["targets"]}行列({dense["prunable_weights"] / 1e9:.2f}B 重み)。縦軸は対数。</text>']
    # legend (identity is never color-alone: key line + dot + name in ink)
    lx = 24
    for _, name, color in SERIES:
        e += [f'<line x1="{lx}" y1="82" x2="{lx + 22}" y2="82" stroke="{color}" stroke-width="2" stroke-linecap="round"/>',
              f'<circle cx="{lx + 11}" cy="82" r="4" fill="{color}" stroke="{SURFACE}" stroke-width="2"/>',
              f'<text x="{lx + 30}" y="86" fill="{INK2}" font-size="12">{name}</text>']
        lx += 30 + sum(12 if ord(ch) > 0x2000 else 7 for ch in name) + 28  # full-width ~12px, ASCII ~7px at 12px
    # y grid + ticks (compact labels, one style per axis)
    e.append(f'<text x="{X0 - 8}" y="{Y0 - 14}" text-anchor="end" fill="{MUTED}" font-size="11">perplexity</text>')
    for k in range(1, hi + 1):
        y = ys(10 ** k)
        lab = {1: "10", 2: "100", 3: "1K", 4: "10K", 5: "100K", 6: "1M", 7: "10M"}.get(k, f"1e{k}")
        e += [f'<line x1="{X0}" y1="{y:.1f}" x2="{X1}" y2="{y:.1f}" stroke="{GRID}" stroke-width="1"/>',
              f'<text x="{X0 - 8}" y="{y + 4:.1f}" text-anchor="end" fill="{MUTED}" font-size="11">{lab}</text>']
    # x axis + ticks
    e.append(f'<line x1="{X0}" y1="{Y1}" x2="{X1}" y2="{Y1}" stroke="{AXIS}" stroke-width="1"/>')
    for k in range(round(xmax * 20) + 1):
        x = xs(k / 20)
        e.append(f'<text x="{x:.1f}" y="{Y1 + 18}" text-anchor="middle" fill="{MUTED}" font-size="11">{k * 5}%</text>')
    e.append(f'<text x="{(X0 + X1) / 2:.0f}" y="{Y1 + 42}" text-anchor="middle" fill="{INK2}" font-size="12">刈った重みの割合(対象の行列の中で)</text>')
    # dense reference
    yd = ys(dense["ppl"])
    e += [f'<line x1="{X0}" y1="{yd:.1f}" x2="{X1}" y2="{yd:.1f}" stroke="{INK2}" stroke-width="1"/>',
          f'<text x="{X1}" y="{yd + 16:.1f}" text-anchor="end" fill="{INK2}" font-size="11">刈らない状態 {dense["ppl"]:.2f}</text>']
    if stop_ratio:  # where each method's evaluation was cut off
        yt = ys(stop_ratio * dense["ppl"])
        e += [f'<line x1="{X0}" y1="{yt:.1f}" x2="{X1}" y2="{yt:.1f}" stroke="{MUTED}" stroke-width="1"/>',
              f'<text x="{X1}" y="{yt + 15:.1f}" text-anchor="end" fill="{MUTED}" font-size="11">打ち切り基準({stop_ratio:g}倍)</text>']
    # series: 2px lines, r=4 markers with a 2px surface ring; the end point is labeled (name + value) in ink
    for m, name, color in SERIES:
        pts = [(0.0, dense["ppl"])] + data[m]
        if len(pts) < 2:
            continue
        path = " ".join(f"{xs(s):.1f},{ys(p if math.isfinite(p) else 10 ** hi):.1f}" for s, p in pts)
        e.append(f'<polyline points="{path}" fill="none" stroke="{color}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>')
        for s, p in pts[1:]:
            e.append(f'<circle cx="{xs(s):.1f}" cy="{ys(p if math.isfinite(p) else 10 ** hi):.1f}" r="4" fill="{color}" stroke="{SURFACE}" stroke-width="2"/>')
        s_end, p_end = pts[-1]
        right = xs(s_end) < X1 - 150
        label = f'{name.split("(")[0]} {s_end * 100:.0f}%: {p_end:,.1f}'
        e.append(f'<text x="{xs(s_end) + (10 if right else -10):.1f}" y="{ys(p_end) + 4:.1f}" text-anchor="{"start" if right else "end"}" '
                 f'fill="{INK}" font-size="12">{label}</text>')
    e.append("</svg>")
    svg = "\n".join(e)
    open(out, "w", encoding="utf-8").write(svg)
    print(f"wrote {out}: {len(svg.encode())} bytes, {svg.count('<') - svg.count('</')} tags")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2], float(sys.argv[3]) if len(sys.argv) > 3 else 0.0)
