"""Compare required and available rolling-radius differences in a toy wheelset."""

import argparse
import json
import math
import platform
from fractions import Fraction
from pathlib import Path

WHEEL_RADIUS = Fraction("0.46")  # m, centred rolling radius
HALF_CONTACT_SPACING = Fraction("0.75")  # m, half the distance between contact paths
CONICITY = Fraction("0.05")  # change of one wheel's rolling radius per lateral shift
SHIFT_LIMIT = Fraction("0.006")  # m, teaching bound, not an engineering tolerance


def rounded(value, digits=6):
    return round(float(value), digits)


def rolling_case(curve_radius, conicity=CONICITY):
    """A radius of None represents a straight track."""
    if curve_radius is not None and curve_radius <= HALF_CONTACT_SPACING:
        raise ValueError("The toy model requires both contact paths to have positive radii.")
    if conicity < 0:
        raise ValueError("The toy model uses nonnegative conicity.")

    required = (2 * WHEEL_RADIUS * HALF_CONTACT_SPACING / curve_radius
                if curve_radius is not None else Fraction(0))
    if required == 0:
        shift = Fraction(0)
    elif conicity == 0:
        shift = None
    else:
        shift = required / (2 * conicity)

    usable_shift = min(shift, SHIFT_LIMIT) if shift is not None else Fraction(0)
    supplied = 2 * conicity * usable_shift
    inner_r = WHEEL_RADIUS - supplied / 2
    outer_r = WHEEL_RADIUS + supplied / 2
    residual = required - supplied
    valid = shift is not None and shift <= SHIFT_LIMIT
    if valid and curve_radius is not None:
        target_ratio = (curve_radius + HALF_CONTACT_SPACING) / (curve_radius - HALF_CONTACT_SPACING)
        assert outer_r / inner_r == target_ratio
    return {
        "curve_radius_m": rounded(curve_radius) if curve_radius is not None else None,
        "conicity": rounded(conicity),
        "required_radius_difference_mm": rounded(1000 * required),
        "required_outward_shift_mm": rounded(1000 * shift) if shift is not None else None,
        "checked_outward_shift_mm": rounded(1000 * usable_shift),
        "supplied_radius_difference_mm": rounded(1000 * supplied),
        "inner_rolling_radius_mm": rounded(1000 * inner_r),
        "outer_rolling_radius_mm": rounded(1000 * outer_r),
        "ideal_match_within_teaching_bound": valid,
        "required_distance_difference_per_rotation_mm": rounded(2000 * math.pi * required),
        "supplied_distance_difference_per_rotation_mm": rounded(2000 * math.pi * supplied),
        "shortfall_in_differential_distance_per_rotation_mm": rounded(2000 * math.pi * residual),
    }


def quarter_turn(curve_radius):
    inner_arc = math.pi / 2 * (curve_radius - HALF_CONTACT_SPACING)
    outer_arc = math.pi / 2 * (curve_radius + HALF_CONTACT_SPACING)
    turns_at_mean_distance = curve_radius / (4 * WHEEL_RADIUS)
    # Check the required differential distance independent of the direct ratio.
    required_difference = 2 * WHEEL_RADIUS * HALF_CONTACT_SPACING / curve_radius
    assert math.isclose(
        (2 * math.pi * required_difference) * turns_at_mean_distance, outer_arc - inner_arc,
        abs_tol=1e-12,
    )
    return {
        "centerline_radius_m": rounded(curve_radius),
        "inner_arc_m": rounded(inner_arc),
        "outer_arc_m": rounded(outer_arc),
        "outer_minus_inner_m": rounded(outer_arc - inner_arc),
        "rotations_at_mean_distance": rounded(turns_at_mean_distance),
    }


def report():
    radius_threshold = WHEEL_RADIUS * HALF_CONTACT_SPACING / (CONICITY * SHIFT_LIMIT)
    curve_radii = [None, Fraction(1500), radius_threshold, Fraction(300)]
    examples = [rolling_case(radius) for radius in curve_radii]
    cylindrical = rolling_case(Fraction(1500), Fraction(0))
    assert radius_threshold == 1150
    assert [row["required_outward_shift_mm"] for row in examples] == [0.0, 4.6, 6.0, 23.0]
    assert [row["ideal_match_within_teaching_bound"] for row in examples] == [True, True, True, False]
    assert not cylindrical["ideal_match_within_teaching_bound"]
    assert rolling_case(None, Fraction(0))["ideal_match_within_teaching_bound"]
    changed_conicity = [
        rolling_case(Fraction(1500), Fraction("0.025")),
        rolling_case(Fraction(1500), Fraction("0.10")),
        rolling_case(Fraction(300), Fraction("0.10")),
    ]
    assert [r["required_outward_shift_mm"] for r in changed_conicity] == [9.2, 2.3, 11.5]
    assert [r["required_radius_difference_mm"] for r in changed_conicity] == [0.46, 0.46, 2.3]
    return {
        "environment": {
            "macOS": platform.mac_ver()[0] or None,
            "architecture": platform.machine(),
            "python": platform.python_version(),
        },
        "centered_rolling_radius_m": rounded(WHEEL_RADIUS),
        "half_contact_spacing_m": rounded(HALF_CONTACT_SPACING),
        "constant_conicity": rounded(CONICITY),
        "teaching_shift_limit_mm": rounded(1000 * SHIFT_LIMIT),
        "finite_curve_radius_at_shift_limit_m": rounded(radius_threshold),
        "conical_examples": examples,
        "cylindrical_wheelset_case": cylindrical,
        "conicity_sensitivity_cases": changed_conicity,
        "quarter_turn_arc_comparison": [quarter_turn(Fraction(radius)) for radius in (1500, 300)],
    }


def plot(path):
    from matplotlib import use

    use("Agg")
    from matplotlib import pyplot as plt

    fig, ax = plt.subplots(figsize=(8.8, 4.75), layout="constrained")
    slope = float(2 * CONICITY)
    bound = float(1000 * SHIFT_LIMIT)
    ax.axvspan(0, bound, color="#e2f2ed", zorder=0)
    ax.plot([0, bound], [0, bound * slope], color="#00665e", lw=2.7, label="Conical model within bound")
    ax.plot([bound, 25], [bound * slope, 25 * slope], color="#00665e", ls="--", lw=1.9,
            label="Conical formula extrapolated")
    ax.axvline(bound, color="#52616b", ls=":", lw=1.4)
    ax.text(bound + 0.25, 0.12, f"{bound:g} mm teaching bound", color="#3f4e58", va="bottom")
    labels = [
        (1500, "#873b1c", (6.7, 0.38)),
        (300, "#524583", (18, 2.44)),
    ]
    for curve, color, label_position in labels:
        case = rolling_case(Fraction(curve))
        shift = case["required_outward_shift_mm"]
        radius_diff = case["required_radius_difference_mm"]
        ax.hlines(radius_diff, 0, shift, color=color, ls=":", lw=1.35)
        ax.plot(shift, radius_diff, marker="o", color=color, markersize=6)
        ax.annotate(f"Curve radius {curve} m", (shift, radius_diff), xytext=label_position,
                    color=color, arrowprops={"arrowstyle": "-", "color": color})
    ax.set(xlim=(0, 25), ylim=(0, 2.65), xlabel="Outward shift (mm)", ylabel="Outer minus inner rolling radius (mm)")
    ax.set_title("Why a tighter curve needs more lateral shift", loc="left", pad=11)
    ax.grid(alpha=0.18)
    ax.spines[["top", "right"]].set_visible(False)
    ax.legend(loc="upper left", frameon=False)
    fig.savefig(path, dpi=160)
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--plot", type=Path, help="write a PNG (requires Matplotlib)")
    args = parser.parse_args()
    data = report()
    if args.plot:
        plot(args.plot)
    print(json.dumps(data, indent=2, allow_nan=False))


if __name__ == "__main__":
    main()
