#!/usr/bin/env python3
"""Rebuild accessible source-status diagrams for HVEPS flow records."""

import json
from html import escape
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATA = json.loads((HERE / "hveps-input-availability.json").read_text(encoding="utf-8"))
FLOW = DATA["published_flow_evidence"]
TARGET = FLOW["targeted_operation"]
SET = FLOW["demonstration_test_set"]
BASE = FLOW["separate_baseline"]
POWER = DATA["test_3"]


def text(x, y, value, size=18, color="#253750", weight=400):
    return (f'<text x="{x}" y="{y}" font-family="Arial,sans-serif" '
            f'font-size="{size}" font-weight="{weight}" fill="{color}">'
            f'{escape(str(value))}</text>')


def card(x, y, width, height, label, heading, rows, note, accent, mobile=False):
    out = [f'<rect x="{x}" y="{y}" width="{width}" height="{height}" rx="18" fill="#ffffff" stroke="#d4deea" stroke-width="2"/>',
           f'<rect x="{x+18}" y="{y+18}" width="{width-36}" height="38" rx="19" fill="{accent}" opacity="0.13"/>',
           text(x+32, y+44, label.upper(), 15 if mobile else 14, accent, 700),
           text(x+22, y+88, heading, 20 if mobile else 18, "#14253a", 700)]
    step = 34 if mobile else 35
    size = 18 if mobile else 17
    start = y + 132
    for i, row in enumerate(rows):
        out.append(text(x+24, start+i*step, row, size, "#253750", 400))
    note_y = y + height - (51 if mobile else 44)
    out.extend([f'<line x1="{x+20}" y1="{note_y-25}" x2="{x+width-20}" y2="{note_y-25}" stroke="#e2e8f0"/>',
                text(x+24, note_y, note, 15 if mobile else 14, "#51677e", 600)])
    return "".join(out)


def build_desktop():
    w, h = 1200, 820
    target_rows = [
        f"Air: {TARGET['conditions']['air_flow_kg_s']:.3f} kg/s",
        f"NaK seed: {TARGET['conditions']['nak_seed_flow_kg_s']:.3f} kg/s",
        f"Preheater H2: {TARGET['conditions']['preheater_h2_flow_kg_s']:.3f} kg/s",
        f"Ethylene: {TARGET['conditions']['scramjet_fuel_ethylene_flow_kg_s']:.3f} kg/s",
        f"Total throughput: {TARGET['conditions']['total_throughput_kg_s']:.3f} kg/s",
    ]
    set_rows = [
        f"Air: {SET['flows']['air_lbm_s']:.2f} lbm/s",
        f"Ethylene: {SET['flows']['ethylene_lbm_s']:.2f} lbm/s",
        f"Air + fuel: {SET['flows']['total_air_plus_fuel_lbm_s']:.2f} lbm/s",
        f"NaK seed: {SET['flows']['nak_seed_lbm_s']:.3f} lbm/s",
        "Conditions listed for the MHD test series",
    ]
    base_rows = [
        f"Air: {BASE['flows_pps']['air']:.2f} pps",
        f"Oxygen: {BASE['flows_pps']['oxygen']:.2f} pps",
        f"Hydrogen: {BASE['flows_pps']['hydrogen']:.4f} pps",
        f"Ethylene: {BASE['flows_pps']['ethylene']:.2f} pps",
        "No NaK seed in this baseline test",
    ]
    parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" aria-labelledby="title desc">',
             '<title id="title">HVEPS target, demonstration-set and baseline flow records</title>',
             '<desc id="desc">Three cards separate calculated target flows in Table II, set conditions for the HVEPS MHD demonstration series in Table III, and a distinct unseeded March 2006 Run 195.1 baseline. A lower panel lists Test 3 power values and warns that the flow records are not synchronized to its electrical samples, so they cannot be combined into specific energy.</desc>',
             f'<rect width="{w}" height="{h}" rx="24" fill="#f7faff"/>',
             text(36, 48, "HVEPS flow figures describe different records", 29, "#14253a", 700),
             text(38, 82, "Tables II–III · keep target, test-set and baseline conditions separate", 17, "#51677e"),
             card(28, 110, 360, 400, "Table II · calculated target", "75%, 85% and 95% cases", target_rows, "RASCAL + LyTec calculation", "#2779a7"),
             card(420, 110, 360, 400, "Table III · MHD test set", "Series set conditions", set_rows, "Not synchronized to Test 3 power", "#7656a5"),
             card(812, 110, 360, 400, "Table III · separate baseline", "Run 195.1 · March 2006", base_rows, "Reference test; no NaK seeding", "#087f8c"),
             '<rect x="28" y="535" width="1144" height="245" rx="18" fill="#fff9ed" stroke="#e4c98e" stroke-width="2"/>',
             text(52, 575, "Test 3 electrical results · Table VI", 22, "#533b10", 700),
             text(52, 615, f"{POWER['reported_load_bank_dissipation_kW']:.2f} kW measured at load bank", 18, "#253750", 700),
             text(52, 648, f"{POWER['post_test_active_channel_output_kW']:.2f} kW post-test active-channel estimate · {POWER['post_test_matched_load_maximum_kW']:.2f} kW matched-load maximum calculation", 16, "#253750"),
             text(52, 697, "The report does not align these flow records with Test 3's selected power samples.", 18, "#713b20", 700),
             text(52, 731, "Do not divide the kW values by target or baseline flows to claim kJ/kg.", 17, "#713b20", 700),
             '</svg>']
    return "".join(parts)


def build_mobile():
    w, h = 640, 1460
    target_rows = [f"Air: {TARGET['conditions']['air_flow_kg_s']:.3f} kg/s", f"NaK seed: {TARGET['conditions']['nak_seed_flow_kg_s']:.3f} kg/s", f"Preheater H2: {TARGET['conditions']['preheater_h2_flow_kg_s']:.3f} kg/s", f"Ethylene: {TARGET['conditions']['scramjet_fuel_ethylene_flow_kg_s']:.3f} kg/s", f"Total: {TARGET['conditions']['total_throughput_kg_s']:.3f} kg/s"]
    set_rows = [f"Air: {SET['flows']['air_lbm_s']:.2f} lbm/s", f"Ethylene: {SET['flows']['ethylene_lbm_s']:.2f} lbm/s", f"Air + fuel: {SET['flows']['total_air_plus_fuel_lbm_s']:.2f} lbm/s", f"NaK seed: {SET['flows']['nak_seed_lbm_s']:.3f} lbm/s"]
    base_rows = [f"Air: {BASE['flows_pps']['air']:.2f} pps", f"Oxygen: {BASE['flows_pps']['oxygen']:.2f} pps", f"Hydrogen: {BASE['flows_pps']['hydrogen']:.4f} pps", f"Ethylene: {BASE['flows_pps']['ethylene']:.2f} pps"]
    parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" aria-labelledby="title desc">',
             '<title id="title">HVEPS flow records have different statuses</title>',
             '<desc id="desc">Vertical mobile version: calculated target, MHD demonstration-series set conditions, and separate unseeded March 2006 baseline, followed by Test 3 electrical results. The report does not synchronize those flows to the selected power samples.</desc>',
             f'<rect width="{w}" height="{h}" rx="24" fill="#f7faff"/>',
             text(26, 46, "HVEPS flow records", 27, "#14253a", 700),
             text(28, 80, "Tables II–III · different records", 17, "#51677e"),
             card(22, 104, 596, 360, "Table II · calculated target", "75%, 85% and 95% cases", target_rows, "RASCAL + LyTec calculation", "#2779a7", True),
             card(22, 474, 596, 340, "Table III · MHD test set", "Series set conditions", set_rows, "Not synchronized to Test 3 power", "#7656a5", True),
             card(22, 824, 596, 340, "Table III · separate baseline", "Run 195.1 · March 2006", base_rows, "Reference test; no NaK seeding", "#087f8c", True),
             '<rect x="22" y="1184" width="596" height="242" rx="18" fill="#fff9ed" stroke="#e4c98e" stroke-width="2"/>',
             text(44, 1224, "Test 3 · Table VI power", 21, "#533b10", 700),
             text(44, 1264, f"{POWER['reported_load_bank_dissipation_kW']:.2f} kW load-bank measurement", 18, "#253750", 700),
             text(44, 1297, f"{POWER['post_test_active_channel_output_kW']:.2f} kW active-channel estimate", 17, "#253750"),
             text(44, 1330, f"{POWER['post_test_matched_load_maximum_kW']:.2f} kW matched-load calculation", 17, "#253750"),
             text(44, 1372, "No flow is aligned to these power samples.", 16, "#713b20", 700),
             text(44, 1402, "Do not calculate kJ/kg from target/baseline flows.", 14, "#713b20", 700),
             '</svg>']
    return "".join(parts)


def main():
    (HERE / "hveps-flow-provenance.svg").write_text(build_desktop(), encoding="utf-8")
    (HERE / "hveps-flow-provenance-mobile.svg").write_text(build_mobile(), encoding="utf-8")


if __name__ == "__main__":
    main()
