"""Generate a responsive, reproducible chart from the AIAA 2003-4285 prose load-factor span."""
import csv
from pathlib import Path

ROOT = Path(__file__).resolve().parent
DATA = ROOT / "nasa-ames-core-flow-partition.csv"
COLORS = {"navy": "#08172d", "panel": "#122443", "white": "#f2f6ff", "muted": "#c2d1e8", "cyan": "#63dcff", "amber": "#ffbd70"}

def read_rows():
    with DATA.open(encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))

def make_svg(rows, mobile=False):
    w, h = (540, 790) if mobile else (1080, 575)
    c = COLORS
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" aria-labelledby="title desc">',
      '<title id="title">Approximate core-flow energy shares derived from the NASA Ames load-factor span</title>',
      '<desc id="desc">Three stacked bars show paired kinetic-energy increase and Joule-heating shares calculated from the author-reported load factors 2.1, midpoint 2.2, and 2.3. Kinetic shares are about 47.6, 45.5, and 43.5 percent; Joule shares are about 52.4, 54.5, and 56.5 percent. These are approximate calculated partitions in the accelerator core flow, not error bars, recovered electricity, or whole-system efficiencies.</desc>',
      f'<rect width="{w}" height="{h}" rx="24" fill="{c["navy"]}"/>']
    if mobile:
        out += [f'<text x="24" y="42" fill="{c["white"]}" font-family="Arial,sans-serif" font-size="21" font-weight="700">From load factor to core-flow shares</text>', f'<text x="24" y="72" fill="{c["muted"]}" font-family="Arial,sans-serif" font-size="16">Author-reported span · core flow only</text>']
    else:
        out += [f'<text x="36" y="48" fill="{c["white"]}" font-family="Arial,sans-serif" font-size="25" font-weight="700">A load factor above one means part of the input heats the flow</text>', f'<text x="36" y="82" fill="{c["muted"]}" font-family="Arial,sans-serif" font-size="18">Source-text calculation · NASA Ames EAST accelerator · core flow only</text>']
    out += [f'<text x="36" y="125" fill="{c["cyan"]}" font-family="Arial,sans-serif" font-size="20" font-weight="700">LF = (ΔK + Q<tspan baseline-shift="sub" font-size="14">J</tspan>) / ΔK</text>', f'<text x="36" y="154" fill="{c["muted"]}" font-family="Arial,sans-serif" font-size="16">Kinetic share = 1/LF · Joule-heating share = (LF − 1)/LF</text>']
    bw, bh = (492, 42) if mobile else (670, 40)
    bx = 24 if mobile else 330
    y0, gap = (235, 142) if mobile else (220, 102)
    for i, row in enumerate(rows):
        lf = row["load_factor_decimal_source_convention"]
        k = float(row["kinetic_share_percent_approx_source_convention"])
        j = float(row["joule_share_percent_approx_source_convention"])
        label = "LF " + lf + " · " + ("midpoint" if "midpoint" in row["factor_label"] else ("lower end" if i == 0 else "upper end"))
        y = y0 + i * gap
        if mobile:
            out.append(f'<text x="{bx}" y="{y}" fill="{c["white"]}" font-family="Arial,sans-serif" font-size="17" font-weight="700">{label}</text>')
            y += 18
        else:
            out.append(f'<text x="36" y="{y+27}" fill="{c["white"]}" font-family="Arial,sans-serif" font-size="18" font-weight="700">{label}</text>')
        kw = bw * k / 100
        out += [f'<rect x="{bx}" y="{y}" width="{bw}" height="{bh}" rx="8" fill="{c["panel"]}"/>',
          f'<path d="M {bx+8} {y} H {bx+kw} V {y+bh} H {bx+8} Q {bx} {y+bh} {bx} {y+bh-8} V {y+8} Q {bx} {y} {bx+8} {y} Z" fill="{c["cyan"]}"/>',
          f'<path d="M {bx+kw} {y} H {bx+bw-8} Q {bx+bw} {y} {bx+bw} {y+8} V {y+bh-8} Q {bx+bw} {y+bh} {bx+bw-8} {y+bh} H {bx+kw} Z" fill="{c["amber"]}"/>',
          f'<text x="{bx+kw/2}" y="{y+27}" text-anchor="middle" fill="{c["navy"]}" font-family="Arial,sans-serif" font-size="16" font-weight="700">{k:.1f}%</text>',
          f'<text x="{bx+kw+(bw-kw)/2}" y="{y+27}" text-anchor="middle" fill="{c["navy"]}" font-family="Arial,sans-serif" font-size="16" font-weight="700">{j:.1f}%</text>']
    legy = y0 + 3*gap + (8 if mobile else 4)
    out += [f'<rect x="{24 if mobile else 36}" y="{legy}" width="18" height="18" rx="3" fill="{c["cyan"]}"/>', f'<text x="{50 if mobile else 64}" y="{legy+15}" fill="{c["white"]}" font-family="Arial,sans-serif" font-size="15">Kinetic increase (ΔK)</text>', f'<rect x="{255 if mobile else 390}" y="{legy}" width="18" height="18" rx="3" fill="{c["amber"]}"/>', f'<text x="{281 if mobile else 418}" y="{legy+15}" fill="{c["white"]}" font-family="Arial,sans-serif" font-size="15">Joule heating (QJ)</text>', f'<text x="{24 if mobile else 36}" y="{h-26}" fill="{c["muted"]}" font-family="Arial,sans-serif" font-size="14">Calculated source span; not a confidence interval.</text>', '</svg>']
    return "\n".join(out) + "\n"

if __name__ == "__main__":
    rows = read_rows()
    (ROOT / "nasa-ames-core-flow-partition.svg").write_text(make_svg(rows), encoding="utf-8")
    (ROOT / "nasa-ames-core-flow-partition-mobile.svg").write_text(make_svg(rows, mobile=True), encoding="utf-8")
