#!/usr/bin/env python3
"""Rebuild the source-derived NASA Ames MHD-channel velocity comparison."""
from __future__ import annotations

import csv
import json
from pathlib import Path

OUT = Path(__file__).resolve().parent
DATA = [
    {"run": "15", "series": "NASA Ames experiment", "value_percent": 27, "evidence": "reported experiment"},
    {"run": "15", "series": "2-D calculation", "value_percent": 26, "evidence": "reported calculation"},
    {"run": "15", "series": "3-D calculation", "value_percent": 26, "evidence": "reported calculation"},
    {"run": "16", "series": "NASA Ames experiment", "value_percent": 38, "evidence": "reported experiment"},
    {"run": "16", "series": "2-D calculation", "value_percent": 31, "evidence": "reported calculation"},
    {"run": "16", "series": "3-D calculation", "value_percent": 30, "evidence": "reported calculation"},
]
COLORS = {"NASA Ames experiment": "#e454b7", "2-D calculation": "#46c4ed", "3-D calculation": "#a6d98d"}


def svg(desktop: bool) -> str:
    width, height = (1100, 650) if desktop else (320, 930)
    left, right = (150, 1000) if desktop else (166, 286)
    top, bottom = (155, 520) if desktop else (165, 840)
    scale = (right - left) / 45
    parts = [
        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">NASA Ames MHD-channel velocity increase: experiment and model comparison</title>',
        '<desc id="desc">Two separate test runs. Run 15: approximately 27 percent measured, 26 percent in both two-dimensional and three-dimensional calculations. Run 16: approximately 38 percent measured, 31 percent in the two-dimensional calculation, and 30 percent in the three-dimensional calculation. Values are reported in a 2004 NASA conference paper; no uncertainty bars were reported.</desc>',
        '<rect width="100%" height="100%" fill="#0b1830"/>',
        f'<text x="{width/2}" y="48" text-anchor="middle" fill="#f4f7ff" font-family="Arial,sans-serif" font-size="{25 if desktop else 17}" font-weight="700">{"A laboratory MHD channel accelerated the flow" if desktop else "MHD channel: test vs model"}</text>',
        f'<text x="{width/2}" y="82" text-anchor="middle" fill="#c5d4ed" font-family="Arial,sans-serif" font-size="{17 if desktop else 13}">{"Area-averaged velocity increase · separate NASA Ames runs" if desktop else "Averaged velocity increase · NASA Ames"}</text>',
    ]
    max_x = 40
    for tick in range(0, 46, 10 if desktop else 20):
        x = left + tick * scale
        parts.append(f'<line x1="{x:.1f}" y1="{top}" x2="{x:.1f}" y2="{bottom}" stroke="#294060"/>')
        parts.append(f'<text x="{x:.1f}" y="{bottom+28}" text-anchor="middle" fill="#d7e2f4" font-family="Arial,sans-serif" font-size="{15 if desktop else 12}">{tick}%</text>')
    if desktop:
        rows = [("15", 245), ("16", 405)]
        offsets = [-42, 0, 42]
        for run, center in rows:
            parts.append(f'<text x="75" y="{center+7}" text-anchor="start" fill="#f4f7ff" font-family="Arial,sans-serif" font-size="19" font-weight="700">Run {run}</text>')
            for entry, dy in zip([d for d in DATA if d["run"] == run], offsets):
                y = center + dy
                x2 = left + entry["value_percent"] * scale
                parts.append(f'<line x1="{left}" y1="{y}" x2="{x2:.1f}" y2="{y}" stroke="{COLORS[entry["series"]]}" stroke-width="14" stroke-linecap="round"/>')
                parts.append(f'<circle cx="{x2:.1f}" cy="{y}" r="9" fill="{COLORS[entry["series"]]}"/>')
                parts.append(f'<text x="{x2+(14 if desktop else 6):.1f}" y="{y+6}" fill="#ffffff" font-family="Arial,sans-serif" font-size="{16 if desktop else 11}">{entry["value_percent"]}%</text>')
        legend_y = 590
        for i, (label, color) in enumerate(COLORS.items()):
            x = 240 + i * 285
            parts.append(f'<circle cx="{x}" cy="{legend_y}" r="8" fill="{color}"/><text x="{x+16}" y="{legend_y+6}" fill="#e4edfb" font-family="Arial,sans-serif" font-size="15">{label}</text>')
    else:
        y = 175
        for run in ("15", "16"):
            parts.append(f'<text x="42" y="{y+28}" fill="#ffffff" font-family="Arial,sans-serif" font-size="21" font-weight="700">Run {run}</text>')
            y += 45
            for entry in [d for d in DATA if d["run"] == run]:
                x2 = left + entry["value_percent"] * scale
                parts.append(f'<text x="24" y="{y+5}" fill="#e4edfb" font-family="Arial,sans-serif" font-size="15">{entry["series"]}</text>')
                parts.append(f'<line x1="{left}" y1="{y+34}" x2="{x2:.1f}" y2="{y+34}" stroke="{COLORS[entry["series"]]}" stroke-width="12" stroke-linecap="round"/>')
                parts.append(f'<text x="{x2+12:.1f}" y="{y+40}" fill="#ffffff" font-family="Arial,sans-serif" font-size="15">{entry["value_percent"]}%</text>')
                y += 100
            y += 35
        parts.append(f'<text x="{width/2}" y="{height-20}" text-anchor="middle" fill="#c5d4ed" font-family="Arial,sans-serif" font-size="11">Approximate reported values · source gives no uncertainty bars</text>')
    parts.append('</svg>')
    return ''.join(parts)


def main() -> None:
    for filename, desktop in (("nasa-ames-accelerator-comparison.svg", True), ("nasa-ames-accelerator-comparison-mobile.svg", False)):
        (OUT / filename).write_text(svg(desktop), encoding="utf-8")
    with (OUT / "nasa-ames-accelerator-comparison.csv").open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=DATA[0].keys())
        writer.writeheader()
        writer.writerows(DATA)
    methods = {
        "title": "NASA Ames MHD accelerator channel: reported experiment/model comparison",
        "source": "Kato et al. (2004), AIAA 2004-0317, NASA NTRS 20040105526, printed pp. 5-6.",
        "source_url": "https://ntrs.nasa.gov/citations/20040105526",
        "source_pdf": "https://ntrs.nasa.gov/api/citations/20040105526/downloads/20040105526.pdf",
        "source_pdf_sha256": "3D89659A267AA245B4B7BA1034D2B535965CA4559F6A15FA52288CDF8543EA72",
        "quantity": "Approximate increase in cross-section-averaged velocity relative to channel entrance velocity.",
        "values": DATA,
        "method": "Values are transcribed from the article text; none were digitized from a graph. The paper reports about 27% experimental increase and 26% for both 2-D and 3-D calculations for Run 15; about 38% experimental increase and 31% (2-D) / 30% (3-D) calculated for Run 16. The abstract summarizes the maximum as up to 40%.",
        "conditions": "The report describes a roughly 0.5 m channel, uniform width 2.03 cm, total nozzle-entry temperature 5560 K, 0.92 T magnetic field, electrical conductivity 130 mho/m (Run 15) and 140 mho/m (Run 16), and approximately 1.2 ms steady-flow periods. These are hot laboratory channel conditions, not an aircraft inlet or flight engine.",
        "measurement_note": "The 2004 paper says experimental velocity was inferred from the voltage generated by the flow at the last, unpowered electrode pair, which inherently averages the velocity profile. It cites NASA TM-2001-210922 and a 2003 AIAA paper for the experiment; those original records should be consulted before a standalone quantitative reanalysis.",
        "limits": [
            "Reported percentages are approximate; the source does not provide uncertainty bars for these comparisons.",
            "The article is a conference paper centered on numerical modeling and reports selected experimental comparisons, not a complete propulsion-system test.",
            "No engine-level net thrust, fuel use, generator-to-accelerator energy loop, aircraft integration or flight benefit is established.",
            "The 2004 numerical comparison assumes turbulent flow, constant gamma 1.25, and an isothermal wall; the reported experiment's powered steady-flow period was only about 1.2 ms.",
        ],
        "reproduction": "python nasa-ames-accelerator-comparison.py",
        "generated_from_source_data": True,
        "new_physical_result_claimed": False,
    }
    (OUT / "nasa-ames-accelerator-comparison-methods.json").write_text(json.dumps(methods, indent=2) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
