"""Reproduce the independent arithmetic figure and CSV for Kovacs et al. (2026).

All inputs transcribed from Tables 1–2. Listed-mass ratio is the reported
net-power estimate divided by the sum of the four printed mass columns.
It is a consistency check, not a correction or validated system metric.
"""
from __future__ import annotations

import csv
from pathlib import Path

ROOT = Path(__file__).resolve().parent
rows = list(csv.DictReader((ROOT / "mhd-magnet-swap-data.csv").open(newline="", encoding="utf-8")))
for row in rows:
    power=float(row['reported_net_power_kW'])
    mass=float(row['listed_component_mass_kg'])
    ratio=float(row['reported_power_mass_density_kW_per_kg'])
    row['extra_mass_implied_by_reported_ratio_kg']=f'{power/ratio-mass:.1f}'
    # Printed ratio precision can give a negative residual; this is rounding,
    # not negative physical mass. The SmCo ratio agrees within rounding.
    row['recomputed_from_listed_masses_kW_per_kg']=f'{power/mass:.5f}'
rows[0]['interpretation']='negative residual from rounded reported ratio; listed mass sum is rounding-compatible'
with (ROOT / 'mhd-magnet-swap-data.csv').open('w',newline='',encoding='utf-8') as f:
    writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)

width, height = 1120, 520
left, right, top, row_h = 400, 80, 110, 72
plot_w = width - left - right
max_v = 2.5
colors = {"reported": "#d8339b", "listed": "#39a6db"}
svg = [f'''<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">
<title id="title">Published and independently recalculated MHD system power-to-mass estimates</title>
<desc id="desc">Horizontal paired bars compare the paper's reported kilowatts per kilogram with our division of its reported net kilowatts by the sum of its four printed mass columns. The SmCo row matches after rounding. Two Table 1 HTS rows differ by the equivalent of about 1000 kilograms of unlocated mass. The two Table 2 rows reconcile when the separately described 200 kilogram transformer pack is included.</desc>
<rect width="1120" height="520" fill="#f6f8fc"/>
<text x="32" y="42" font-family="Arial,sans-serif" font-size="25" font-weight="700" fill="#12233f">Reported vs. listed-mass power-to-mass ratio</text>
<text x="32" y="72" font-family="Arial,sans-serif" font-size="16" fill="#40546f">Initial design estimates · kW per kg · the listed-mass calculation is a bookkeeping check</text>
<rect x="698" y="88" width="16" height="16" rx="3" fill="{colors['reported']}"/><text x="722" y="102" font-family="Arial,sans-serif" font-size="15" fill="#253752">Paper table</text>
<rect x="842" y="88" width="16" height="16" rx="3" fill="{colors['listed']}"/><text x="866" y="102" font-family="Arial,sans-serif" font-size="15" fill="#253752">Net kW ÷ four listed masses</text>''']
for t in range(0, 6):
    x = left + plot_w * t / 5
    val = max_v * t / 5
    svg.append(f'<line x1="{x:.1f}" y1="108" x2="{x:.1f}" y2="455" stroke="#d4dce7"/><text x="{x:.1f}" y="477" text-anchor="middle" font-family="Arial,sans-serif" font-size="14" fill="#40546f">{val:.1f}</text>')
svg.append('<text x="590" y="506" text-anchor="middle" font-family="Arial,sans-serif" font-size="15" fill="#253752">Power-to-mass ratio (kW/kg)</text>')
for i, row in enumerate(rows):
    y = top + i * row_h
    label = row["configuration"]
    if len(label) > 40:
        label = label.replace(" cylindrical Halbach", " Halbach").replace("HTS trapped-field", "HTS trapped").replace("HTS split racetrack", "HTS racetrack")
    svg.append(f'<text x="32" y="{y+18}" font-family="Arial,sans-serif" font-size="15" font-weight="600" fill="#20334f">{label}</text>')
    vals = [(float(row["reported_power_mass_density_kW_per_kg"]), "reported"), (float(row["recomputed_from_listed_masses_kW_per_kg"]), "listed")]
    for j, (val, key) in enumerate(vals):
        yy = y + 25 + j * 20
        barw = plot_w * min(val, max_v) / max_v
        svg.append(f'<rect x="{left}" y="{yy}" width="{barw:.1f}" height="14" rx="4" fill="{colors[key]}"/>')
        svg.append(f'<text x="{left+barw+8:.1f}" y="{yy+12}" font-family="Arial,sans-serif" font-size="13" fill="#20334f">{val:.3f}</text>')
svg.append('<text x="32" y="500" font-family="Arial,sans-serif" font-size="12" fill="#56677e">Table 1 HTS differences remain unresolved; Table 2 adds the text-described 200 kg transformer mass.</text></svg>')
(ROOT / "mhd-magnet-swap-power-mass.svg").write_text("\n".join(svg), encoding="utf-8")
print("Wrote mhd-magnet-swap-power-mass.svg from the retained source table values.")
