#!/usr/bin/env python3
"""Rebuild a source-transcribed NASA 2001 MHD ionizer/generator comparison."""
from __future__ import annotations

import csv
import json
from pathlib import Path

OUT = Path(__file__).resolve().parent
DATA = [
    {"quantity": "External ionizer power required", "power_mw": 827, "evidence": "model result, rounded from 8.27e8 W", "color": "#e454b7"},
    {"quantity": "MHD generator power produced", "power_mw": 151, "evidence": "model result, rounded from 1.51e8 W", "color": "#46c4ed"},
]
SOURCE_HASH = "3ABB57E0BF742FA5248B750E9EC4F3F124376D8F403CB0E3A1B20A88713EACE6"


def svg(mobile: bool) -> str:
    width, height = (360, 420) if mobile else (900, 440)
    base_y = 300 if mobile else 305
    left, right = (48, 332) if mobile else (250, 800)
    scale = (right - left) / 900
    bars = []
    if mobile:
        for i, row in enumerate(DATA):
            y = 144 + i * 92
            bar_end = left + row["power_mw"] * scale
            bars.append(f'<text x="{left}" y="{y-13}" fill="#e7eefb" font-family="Arial,sans-serif" font-size="14">{row["quantity"]}</text>')
            bars.append(f'<rect x="{left}" y="{y}" width="{bar_end-left:.1f}" height="30" rx="7" fill="{row["color"]}"/>')
            bars.append(f'<text x="{left}" y="{y+53}" fill="#ffffff" font-family="Arial,sans-serif" font-size="15" font-weight="700">{row["power_mw"]} MW</text>')
        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">A 2001 NASA model required more ionizer power than its MHD generator produced</title>',
            '<desc id="desc">For one modeled case, the calculated external ionizer demand was 827 megawatts and the calculated MHD generator output was 151 megawatts. The demand was about 5.5 times gross generation. The paper assumed a 100 percent efficient ionizer; this was a model, not a hardware test.</desc>',
            '<rect width="100%" height="100%" rx="14" fill="#0b1830"/>',
            '<text x="180" y="38" text-anchor="middle" fill="#f4f7ff" font-family="Arial,sans-serif" font-size="17" font-weight="700">One modeled power trade-off</text>',
            '<text x="180" y="67" text-anchor="middle" fill="#c5d4ed" font-family="Arial,sans-serif" font-size="13">NASA conference preprint · 2001</text>',
            *bars,
            '<line x1="48" y1="330" x2="332" y2="330" stroke="#7385a3"/>',
            '<text x="180" y="357" text-anchor="middle" fill="#ffd69a" font-family="Arial,sans-serif" font-size="14" font-weight="700">Ionizer demand ≈ 5.48 × gross generation</text>',
            '<text x="180" y="383" text-anchor="middle" fill="#c5d4ed" font-family="Arial,sans-serif" font-size="11">Rounded source values · not a net vehicle balance</text>',
            '</svg>',
        ]
    else:
        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">A 2001 NASA model required more ionizer power than its MHD generator produced</title>',
            '<desc id="desc">For one modeled case, the calculated external ionizer demand was 827 megawatts and the calculated MHD generator output was 151 megawatts. The demand was about 5.5 times gross generation. The paper assumed a 100 percent efficient ionizer; this was a model, not a hardware test.</desc>',
            '<rect width="100%" height="100%" rx="14" fill="#0b1830"/>',
            '<text x="450" y="45" text-anchor="middle" fill="#f4f7ff" font-family="Arial,sans-serif" font-size="23" font-weight="700">One modeled power trade-off</text>',
            '<text x="450" y="76" text-anchor="middle" fill="#c5d4ed" font-family="Arial,sans-serif" font-size="16">NASA conference preprint · 2001 · one selected operating case</text>',
        ]
        for i, row in enumerate(DATA):
            y = 150 + i * 105
            bar_end = left + row["power_mw"] * scale
            parts.append(f'<text x="{left}" y="{y-12}" fill="#e7eefb" font-family="Arial,sans-serif" font-size="16">{row["quantity"]}</text>')
            parts.append(f'<rect x="{left}" y="{y}" width="{bar_end-left:.1f}" height="38" rx="9" fill="{row["color"]}"/>')
            parts.append(f'<text x="{bar_end+10:.1f}" y="{y+25}" fill="#ffffff" font-family="Arial,sans-serif" font-size="17" font-weight="700">{row["power_mw"]} MW</text>')
        parts.extend([
            f'<line x1="{left}" y1="{base_y}" x2="{right}" y2="{base_y}" stroke="#7385a3"/>',
            '<text x="525" y="350" text-anchor="middle" fill="#ffd69a" font-family="Arial,sans-serif" font-size="18" font-weight="700">Ionizer demand ≈ 5.48 × gross generator output</text>',
            '<text x="450" y="389" text-anchor="middle" fill="#c5d4ed" font-family="Arial,sans-serif" font-size="14">Rounded values transcribed from Table 1 · comparison excludes other system loads</text>',
            '</svg>',
        ])
    return ''.join(parts)


def main() -> None:
    for filename, mobile in (("nasa-ionizer-power-comparison.svg", False), ("nasa-ionizer-power-comparison-mobile.svg", True)):
        (OUT / filename).write_text(svg(mobile), encoding="utf-8")
    with (OUT / "nasa-ionizer-power-comparison.csv").open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["quantity", "power_mw", "evidence"])
        writer.writeheader()
        writer.writerows({k: v for k, v in row.items() if k != "color"} for row in DATA)
    methods = {
        "title": "NASA 2001 nonequilibrium MHD-bypass ionizer power comparison",
        "source": "Park, Bogdanoff and Mehta, Power Requirement for Nonequilibrium MHD-Bypass Scramjet, AIAA 2001-0463 conference preprint, NASA NTRS 20010066491, printed pp. 1, 5-7.",
        "source_url": "https://ntrs.nasa.gov/citations/20010066491",
        "source_pdf": "https://ntrs.nasa.gov/api/citations/20010066491/downloads/20010066491.pdf",
        "source_pdf_sha256": SOURCE_HASH,
        "data": DATA,
        "calculation": {"ionizer_to_generator_power_ratio": round(827 / 151, 4), "source_rounded_values_used": True},
        "case": "Modeled vehicle at 2500 m/s and 0.5 atm dynamic pressure, with cesium seeding; generator conductivity 109 S/m, field 1.47 T, and generator entrance temperature 1100 K. The source reports 8.27e8 W ionizer demand and 1.51e8 W generated power, rounded here to 827 MW and 151 MW.",
        "additional_reported_quantity": "The paper reports external power divided by hydrogen fuel energy as 0.85 for this modeled case, with fuel energy calculated assuming complete combustion at room temperature. This is the authors’ reported case metric and is not independently recomputed here.",
        "assumptions_and_limits": [
            "The analysis assumed a 100%-efficient nonequilibrium ionization device; this is a theoretical best-case assumption, not a measured device efficiency.",
            "The authors describe one-dimensional flow and ideal MHD devices, assumed no shock inside the generator, and included a separate calculation with skin friction.",
            "The external ionizer power is about 5.48 times the reported gross generator power in this one case; this comparison is not a complete electrical bus or net aircraft power balance.",
            "This is a NASA-hosted conference preprint/model, not an experimental integrated propulsion test or evidence of flight benefit.",
            "The graphic transcribes rounded Table 1 values; no graph points are digitized.",
        ],
        "reproduction": "python nasa-ionizer-power-comparison.py",
        "new_physical_result_claimed": False,
    }
    (OUT / "nasa-ionizer-power-comparison-methods.json").write_text(json.dumps(methods, indent=2) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
