"""Recreate an approximate, accessible redraw of NASA TN D-7998 Figure 12(c)."""

from __future__ import annotations

import csv
import json
from pathlib import Path


HERE = Path(__file__).resolve().parent
POINTS = [(-5, 0.75), (0, 0.74), (3, 0.80), (5, 0.81)]
SOURCE = {
    "title": "Experimental investigation of a Mach 6 fixed-geometry inlet featuring a swept external-internal compression flow field",
    "author": "M. G. Torrence",
    "report": "NASA-TN-D-7998 (1975)",
    "record": "https://ntrs.nasa.gov/citations/19750024978",
    "pdf": "https://ntrs.nasa.gov/api/citations/19750024978/downloads/19750024978.pdf",
    "figure": "Figure 12(c), printed p. 57 (PDF p. 58)",
    "local_primary_source_sha256": "8C37ACC003C561749D6E1EC3EB0D559041DC4A562BE2EB7DAC519409D13FD7D0",
}


def render(mobile: bool) -> str:
    width, height = ((760, 520) if mobile else (1120, 620))
    left, right, top, bottom = ((88, width - 32, 72, height - 100) if mobile else (108, width - 48, 66, height - 108))
    x = lambda a: left + (a + 6) / 12 * (right - left)
    y = lambda v: bottom - (v - 0.5) / 0.5 * (bottom - top)
    color, grid, ink = "#80d9ff", "#354b70", "#dce8ff"
    xticks = [-6, -4, -2, 0, 2, 4, 6]
    yticks = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
    chunks = [
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" role="img" aria-labelledby="title desc">',
        '<title id="title">Mach 6 inlet average recovery versus angle of attack</title>',
        '<desc id="desc">Approximate visual readings of four wind-tunnel points from NASA TN D-7998 Figure 12(c). The arithmetic area-average throat recovery is about 0.75 at minus 5 degrees, 0.74 at zero, 0.80 at 3 degrees, and 0.81 at 5 degrees. A thin line connects points only as a visual guide.</desc>',
        f'<rect width="{width}" height="{height}" rx="20" fill="#09172f"/>',
        f'<text x="{left}" y="30" fill="{ink}" font-family="system-ui,sans-serif" font-size="18" font-weight="700">Mach 6 fixed-geometry inlet · wind-tunnel test</text>',
    ]
    for tick in yticks:
        yy = y(tick)
        chunks.append(f'<line x1="{left}" y1="{yy:.2f}" x2="{right}" y2="{yy:.2f}" stroke="{grid}"/>')
        chunks.append(f'<text x="{left-12}" y="{yy+5:.2f}" text-anchor="end" fill="{ink}" font-family="system-ui,sans-serif" font-size="14">{tick:.1f}</text>')
    for tick in xticks:
        xx = x(tick)
        chunks.append(f'<line x1="{xx:.2f}" y1="{top}" x2="{xx:.2f}" y2="{bottom}" stroke="{grid}"/>')
        chunks.append(f'<text x="{xx:.2f}" y="{bottom+24}" text-anchor="middle" fill="{ink}" font-family="system-ui,sans-serif" font-size="14">{tick}</text>')
    coords = " ".join(f"{x(a):.2f},{y(v):.2f}" for a, v in POINTS)
    chunks.append(f'<polyline points="{coords}" fill="none" stroke="{color}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>')
    for a, v in POINTS:
        xx, yy = x(a), y(v)
        chunks.append(f'<circle cx="{xx:.2f}" cy="{yy:.2f}" r="7" fill="{color}" stroke="#09172f" stroke-width="2"/>')
        chunks.append(f'<text x="{xx:.2f}" y="{yy-15:.2f}" text-anchor="middle" fill="{ink}" font-family="system-ui,sans-serif" font-size="13">{v:.2f}</text>')
    chunks.extend([
        f'<text x="{(left+right)/2:.2f}" y="{height-24}" text-anchor="middle" fill="{ink}" font-family="system-ui,sans-serif" font-size="15">Angle of attack (degrees)</text>',
        f'<text transform="translate(24 {(top+bottom)/2:.2f}) rotate(-90)" text-anchor="middle" fill="{ink}" font-family="system-ui,sans-serif" font-size="15">Area-averaged throat total-pressure recovery</text>',
        f'<text x="{right-4}" y="{height-48}" text-anchor="end" fill="#b4c6e5" font-family="system-ui,sans-serif" font-size="11">Points visually read from published Figure 12(c); line is a guide only.</text>',
        '</svg>',
    ])
    return "\n".join(chunks) + "\n"


def main() -> None:
    with (HERE / "nasa-mach6-inlet-fig12c.csv").open("w", newline="", encoding="utf-8") as stream:
        writer = csv.writer(stream)
        writer.writerow(["angle_of_attack_deg", "approx_area_averaged_throat_total_pressure_recovery", "visual_reading_tolerance"])
        for angle, recovery in POINTS:
            writer.writerow([angle, f"{recovery:.2f}", "about +/-0.01; visual read-off only"])
    methods = {
        "source": SOURCE,
        "data_status": "Approximate visual digitization of Figure 12(c); the source presents these four points graphically, not as a numeric table.",
        "test": {
            "freestream_mach": 6.0,
            "test_section_reynolds_number_per_m": 1.55e7,
            "stagnation_pressure_atm": 20,
            "stagnation_temperature_K": 500,
            "angles_of_attack_deg": [-5, 0, 3, 5],
            "chosen_data_reduction_limit_eta_D_max": 0.91,
            "data_reduction_limit_note": "A limiting recovery used in the data reduction to correct survey quantities. The report considers 0.91 the most realistic of the limits examined; this is not the measured average recovery.",
            "reported_mean_area_averaged_throat_total_pressure_recovery": 0.78,
            "reported_corresponding_adiabatic_kinetic_energy_efficiency": 0.99,
            "measurements": "Pitot and static pressure surveys in the inlet throat, wall static pressures, and surface temperatures; boundary-layer bleed was used on the centerbody and cowl internal surface.",
            "figure_12c_average_definition": "The report describes an arithmetic average of recovery over the throat area for each angle of attack. It is not the mass-weighted recovery quantity discussed separately elsewhere in the report.",
        },
        "digitization": {
            "method": "Four marker centers in Figure 12(c) were read against the printed axes and rounded to 0.01. The connecting line is only a visual guide and does not assert intermediate measurements.",
            "estimated_visual_reading_tolerance": "About +/-0.01 in recovery, estimated from line width, marker size, and scan quality. This is digitization tolerance only, not experimental repeatability, uncertainty in the report's data reduction, or uncertainty in the inlet model.",
            "points": [{"angle_of_attack_deg": a, "approx_area_averaged_throat_total_pressure_recovery": v} for a, v in POINTS],
        },
        "limits": [
            "This is one tested inlet configuration and these specific Mach-6 ground-test conditions, not a universal inlet curve or flight test.",
            "The report states that the 0.91 recovery cap was judged the most realistic for data reduction; other caps were also examined.",
            "The reported 0.78 recovery and 0.99 adiabatic kinetic-energy efficiency are different metrics. Do not interpret either as recovered electrical energy or as whole-engine efficiency.",
            "This plot does not report heat flux from the inlet wall, nor does it show an integrated propulsion-cycle result.",
        ],
    }
    (HERE / "nasa-mach6-inlet-fig12c-methods.json").write_text(json.dumps(methods, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    (HERE / "nasa-mach6-inlet-fig12c.svg").write_text(render(False), encoding="utf-8")
    (HERE / "nasa-mach6-inlet-fig12c-mobile.svg").write_text(render(True), encoding="utf-8")
    print("Wrote four approximate Figure 12(c) readings, methods, and desktop/mobile SVG redraws.")


if __name__ == "__main__":
    main()
