"""解説記事用の図（淡い層から真っ黒まで、30nm と 400nm の b*）を、記事の CSS の名前を使ったインライン SVG で出す。
実行: uv run --no-project --with miepython==2.5.5 --with colour-science==0.4.6 --with numpy python paper/svg_crossover_ja.py > /tmp/fig.svg
"""
import sys, io, contextlib, math
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
with contextlib.redirect_stdout(io.StringIO()):
    import sumi_crossover as sc
ks = {d: sc.KS(d, 1.0) for d in (30, 400)}
X0 = sc.X_for(*ks[30], 0.53 * sc.Rg)
W, H, L, R, T, B = 640, 360, 60, 620, 20, 300
xmin, xmax, ymin, ymax = -1, 2, -4, 16
fx = lambda lx: L + (lx - xmin) / (xmax - xmin) * (R - L)
fy = lambda b: T + (ymax - b) / (ymax - ymin) * (B - T)
o = [f'<svg viewBox="0 0 {W} {H}" role="img" aria-labelledby="figt2">',
     '<title id="figt2">墨の量と淡墨の黄み・青み（b*）。30nm と 400nm の粒</title>']
for b in range(-4, 17, 4):
    o.append(f'<line x1="{L}" x2="{R}" y1="{fy(b):.1f}" y2="{fy(b):.1f}" class="{"zero" if b == 0 else "grid"}"/>')
    o.append(f'<text x="{L-8}" y="{fy(b)+5:.1f}" class="tick" text-anchor="end">{b:+d}</text>'.replace("+0", "0"))
for lx, lab in [(-1, "0.1"), (0, "1"), (1, "10"), (2, "100")]:
    o.append(f'<line x1="{fx(lx):.1f}" x2="{fx(lx):.1f}" y1="{T}" y2="{B}" class="grid"/>')
    o.append(f'<text x="{fx(lx):.1f}" y="{B+22}" class="tick" text-anchor="middle">{lab}</text>')
o.append(f'<text x="{(L+R)/2}" y="{H-8}" class="axis" text-anchor="middle">面積あたりの煤の量（淡墨の量を 1 とする）</text>')
o.append(f'<text x="{fx(0)+6:.1f}" y="{fy(15):.1f}" class="note">淡墨</text>')
for d, cls in [(30, "s2"), (400, "s1")]:
    pts = []
    for lx in np.linspace(xmin, xmax, 160):
        b = sc.lab(sc.R_layer(*ks[d], 10 ** lx * X0))[2]
        pts.append(f"{fx(lx):.1f},{fy(max(ymin, min(ymax, b))):.1f}")
    o.append(f'<polyline class="{cls}" points="{" ".join(pts)}"/>')
o.append(f'<text x="{fx(-0.55):.1f}" y="{fy(9):.1f}" class="lab2">30nm の粒</text>')
o.append(f'<text x="{fx(-0.95):.1f}" y="{fy(-2.6):.1f}" class="lab1">400nm の粒</text>')
o.append(f'<text x="{fx(1.62):.1f}" y="{fy(5.2):.1f}" class="lab1" text-anchor="middle">400nm</text>')
o.append(f'<text x="{fx(1.62):.1f}" y="{fy(-2.6):.1f}" class="lab2" text-anchor="middle">30nm</text>')
o.append('</svg>')
print("\n".join(o))
