"""Build an approximate accessible redraw of Ishikawa et al. (2008), Fig. 6."""
from __future__ import annotations

import csv
import hashlib
import json
from pathlib import Path
import xml.etree.ElementTree as ET

HERE = Path(__file__).resolve()
ROOT = HERE.parents[1]
if HERE.parent.name == "scripts":
    OUT = ROOT / "dist/hover/inlet"
    SOURCE = ROOT.parents[1] / "sources/documents-externes/Ishikawa-et-al-2008-3D-HVEPS-Run3-MHD.pdf"
else:
    OUT = HERE.parent
    SOURCE = None
SOURCE_SHA256 = "e903dfb069b9a8c600646a1dd45da59d911327bb8f863a88deb01c0cbda4e7b7"
# Approximate visual readings from the printed graph; these are not underlying samples.
MODEL = [(3, 42), (5, 60), (7, 73), (8, 76), (9, 77), (10, 72), (12, 65),
         (14, 61), (16, 59), (18, 58), (20, 59), (22, 58), (24, 59),
         (26, 61), (28, 66), (30, 72), (31, 71), (32, 68), (34, 61)]
MEASURED_A = 58
INK = "#15304b"
BLUE = "#287eae"
GOLD = "#c98127"
GRID = "#d8e2ea"

def svg(mobile: bool) -> str:
    w, h = (440, 610) if mobile else (1020, 600)
    left, top = (62, 158) if mobile else (100, 130)
    right, bottom = (w - 24, h - 172) if mobile else (w - 50, h - 140)
    pw, ph = right - left, bottom - top
    sx = lambda x: left + x / 35 * pw
    sy = lambda y: bottom - y / 100 * ph
    lines = [
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" aria-labelledby="title desc">',
        '<title id="title">Run 3 modelled and measured generator current</title>',
        '<desc id="desc">Approximate redraw of Figure 6 from Ishikawa and colleagues, 2008. A dashed measured-current line sits near 58 amperes. A modelled current curve is close to it through the active channel and higher near both power take-off ends. The plotted readings are visual estimates, not raw data.</desc>',
        '<rect width="100%" height="100%" rx="20" fill="#f7fbff"/>',
        f'<text x="{left}" y="38" font-family="Arial,sans-serif" font-size="{22 if mobile else 26}" font-weight="700" fill="{INK}">Run 3: current along the channel</text>',
        f'<text x="{left}" y="72" font-family="Arial,sans-serif" font-size="15" fill="#51677e">HVEPS Run 3 · approximate readings from Figure 6</text>',
    ]
    for y in (0, 20, 40, 60, 80, 100):
        Y = sy(y)
        lines += [f'<line x1="{left}" y1="{Y:.1f}" x2="{right}" y2="{Y:.1f}" stroke="{GRID}"/>',
                  f'<text x="{left-10}" y="{Y+5:.1f}" text-anchor="end" font-family="Arial,sans-serif" font-size="13" fill="{INK}">{y}</text>']
    for x in (0, 10, 20, 30):
        X = sx(x)
        lines += [f'<line x1="{X:.1f}" y1="{top}" x2="{X:.1f}" y2="{bottom}" stroke="{GRID}"/>',
                  f'<text x="{X:.1f}" y="{bottom+22}" text-anchor="middle" font-family="Arial,sans-serif" font-size="13" fill="{INK}">{x}</text>']
    lines += [f'<line x1="{left}" y1="{top}" x2="{left}" y2="{bottom}" stroke="{INK}" stroke-width="2"/>',
              f'<line x1="{left}" y1="{bottom}" x2="{right}" y2="{bottom}" stroke="{INK}" stroke-width="2"/>',
              f'<text x="{left-44}" y="{(top+bottom)/2}" transform="rotate(-90 {left-44} {(top+bottom)/2})" text-anchor="middle" font-family="Arial,sans-serif" font-size="15" fill="{INK}">Load current · A</text>',
              f'<text x="{(left+right)/2}" y="{bottom+48}" text-anchor="middle" font-family="Arial,sans-serif" font-size="15" fill="{INK}">Insulator number</text>',
              f'<line x1="{sx(0)}" y1="{sy(MEASURED_A)}" x2="{sx(35)}" y2="{sy(MEASURED_A)}" stroke="{GOLD}" stroke-width="3" stroke-dasharray="9 7"/>']
    points = " ".join(f"{sx(x):.1f},{sy(y):.1f}" for x, y in MODEL)
    lines.append(f'<polyline points="{points}" fill="none" stroke="{BLUE}" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>')
    for x, y in MODEL:
        lines.append(f'<circle cx="{sx(x):.1f}" cy="{sy(y):.1f}" r="3.3" fill="{BLUE}"/>')
    if mobile:
        lines += [f'<line x1="{left+6}" y1="{h-76}" x2="{left+36}" y2="{h-76}" stroke="{BLUE}" stroke-width="4"/>',
                  f'<text x="{left+44}" y="{h-71}" font-family="Arial,sans-serif" font-size="13" fill="{INK}">Model · graph-read</text>',
                  f'<line x1="{left+6}" y1="{h-42}" x2="{left+36}" y2="{h-42}" stroke="{GOLD}" stroke-width="3" stroke-dasharray="8 6"/>',
                  f'<text x="{left+44}" y="{h-37}" font-family="Arial,sans-serif" font-size="13" fill="{INK}">Experiment · ≈58 A</text>']
    else:
        ly = h - 55
        lines += [f'<line x1="{left+10}" y1="{ly}" x2="{left+44}" y2="{ly}" stroke="{BLUE}" stroke-width="4"/>',
                  f'<text x="{left+52}" y="{ly+5}" font-family="Arial,sans-serif" font-size="14" fill="{INK}">3D model (approximate graph reads)</text>',
                  f'<line x1="{left+420}" y1="{ly}" x2="{left+454}" y2="{ly}" stroke="{GOLD}" stroke-width="3" stroke-dasharray="8 6"/>',
                  f'<text x="{left+462}" y="{ly+5}" font-family="Arial,sans-serif" font-size="14" fill="{INK}">Experiment (≈58 A)</text>']
    lines.append('</svg>')
    return "\n".join(lines) + "\n"

def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    for mobile, suffix in ((False, ""), (True, "-mobile")):
        (OUT / f"hveps-run3-current-profile{suffix}.svg").write_text(svg(mobile), encoding="utf-8")
    with (OUT / "hveps-run3-current-profile.csv").open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f); w.writerow(["insulator_number", "model_current_graph_read_A", "experimental_current_graph_read_A", "status"])
        for x, y in MODEL:
            w.writerow([x, y, MEASURED_A, "approximate visual reading from Figure 6; not raw source data"])
    digest = hashlib.sha256(SOURCE.read_bytes()).hexdigest() if SOURCE and SOURCE.exists() else SOURCE_SHA256
    if digest != SOURCE_SHA256:
        raise SystemExit("Retained source PDF hash differs from the recorded provenance.")
    methods = {
        "source": "Ishikawa, Gotoh, Takahashi & Fujino (2008), Three-dimensional analysis of electric current distribution in a small-scale scramjet driven DCW MHD generator, Journal of Optoelectronics and Advanced Materials 10(6), 1442–1447.",
        "source_url": "https://joam.inoe.ro/articles/three-dimensional-analysis-of-electric-current-distribution-in-a-small-scale-scramjet-driven-dcw-mhd-generator/fulltext",
        "figure_locator": "Figure 6, printed p.1445 / PDF p.4",
        "local_source": "sources/documents-externes/Ishikawa-et-al-2008-3D-HVEPS-Run3-MHD.pdf",
        "local_source_sha256": digest,
        "reading_method": "Approximate manually recorded visual readings from the reproduced graph; experimental reference is visually read as approximately 58 A. No underlying numerical samples are claimed.",
        "model_series_A": MODEL,
        "experimental_reference_A": MEASURED_A,
        "interpretation": "Authors report model agreement in the active channel after setting sigma/sigma_ideal = 0.813 (an 18.7% reduction from ideal), but computed current remains about 30% high at inlet PTO and 20% high at outlet PTO. This is model-to-measurement comparison, not independent validation or vehicle net-power evidence.",
        "limits": ["source plot has no pointwise CSV", "visual readings are approximate and no uncertainty bars are inferred", "arcing model and imposed 1000 K wall temperature influence near-electrode voltage drops", "authors state more detailed end-region electrodynamics is required to define PTO power loss"],
        "generator": "Measured experimental HVEPS Run 3 inputs stated by the paper: inlet 0.284 atm, 2480 K, Mach 2.02; imposed wall 1000 K; maximum field 1.48 T.",
        "grid": "128 x 41 x 21 grid; paper says about 0.2 mm resolution would be required to resolve the ~1 mm near-wall arc scale, so the reported grid is coarse for that phenomenon."
    }
    (OUT / "hveps-run3-current-profile-methods.json").write_text(json.dumps(methods, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(f"Generated source-bounded SVG/CSV/methods; source SHA-256={digest}")

if __name__ == "__main__":
    main()
