"""Compute grades and contour crossings on small synthetic terrain profiles."""
import argparse
import json
import math
import platform
import sys
from pathlib import Path


def map_grade(gap_mm, scale_denominator, interval_m):
    if min(gap_mm, scale_denominator, interval_m) <= 0:
        raise ValueError("map gap, scale denominator and interval must be positive")
    run = gap_mm * scale_denominator / 1000
    ratio = interval_m / run
    return {
        "gap_mm": gap_mm, "scale_denominator": scale_denominator,
        "contour_interval_m": interval_m, "horizontal_run_m": run,
        "grade_percent": round(100 * ratio, 6),
        "angle_deg": round(math.degrees(math.atan(ratio)), 6),
    }


def route(vertices, interval_m=10):
    """Each segment is linear in height, with no vertex on a contour."""
    if len(vertices) < 2 or interval_m <= 0 or any(z % interval_m == 0 for _, _, z in vertices):
        raise ValueError("expected a profile with at least two off-contour vertices")
    run, ascent, descent = 0, 0, 0
    crossings, crossing_distances = [], []
    for (x0, y0, z0), (x1, y1, z1) in zip(vertices, vertices[1:]):
        distance = math.hypot(x1 - x0, y1 - y0)
        if not distance:
            raise ValueError("segment has zero horizontal length")
        rise = z1 - z0
        ascent += max(0, rise)
        descent += max(0, -rise)
        lo, hi = sorted((z0, z1))
        levels = list(range((lo // interval_m + 1) * interval_m, hi, interval_m))
        for level in levels if rise > 0 else reversed(levels):
            crossings.append(level)
            crossing_distances.append(round(run + distance * (level - z0) / rise, 6))
        run += distance
    net = vertices[-1][2] - vertices[0][2]
    return {
        "vertices_xyz_m": vertices, "horizontal_length_m": run,
        "net_change_m": net, "total_ascent_m": ascent, "total_descent_m": descent,
        "net_grade_percent": 100 * net / run, "crossed_contours_m": crossings,
        "horizontal_distance_at_crossings_m": crossing_distances,
    }


def run_lab():
    cases = [map_grade(2, scale, interval) for scale, interval in
             ((25000, 10), (50000, 20), (50000, 10), (25000, 20))]
    measurement = [map_grade(gap, 25000, 10) for gap in (1.8, 2.2)]
    assert [round(row["grade_percent"], 2) for row in measurement] == [22.22, 18.18]
    straight = route([(0, 0, 104), (120, 0, 128)])
    zigzag = route([(0, 0, 104), (60, 80, 116), (120, 0, 128)])
    ridge = route([(0, 0, 104), (60, 0, 116), (120, 0, 104)])
    small_bump = route([(0, 0, 104), (60, 0, 108), (120, 0, 104)])
    along = route([(0, 0, 104), (0, 100, 104)])
    assert [item["grade_percent"] for item in cases] == [20, 20, 10, 40]
    assert [round(item["angle_deg"], 2) for item in cases] == [11.31, 11.31, 5.71, 21.80]
    assert straight["crossed_contours_m"] == zigzag["crossed_contours_m"] == [110, 120]
    assert straight["horizontal_distance_at_crossings_m"] == [30, 80]
    assert zigzag["horizontal_distance_at_crossings_m"] == [50, 133.333333]
    assert ridge["horizontal_distance_at_crossings_m"] == [30, 90]
    assert straight["horizontal_length_m"] == 120 and straight["net_grade_percent"] == 20
    assert zigzag["horizontal_length_m"] == 200 and zigzag["net_grade_percent"] == 12
    assert straight["net_change_m"] == zigzag["net_change_m"] == 24
    assert ridge["crossed_contours_m"] == [110, 110]
    assert ridge["net_change_m"] == small_bump["net_change_m"] == 0
    assert ridge["total_ascent_m"] == ridge["total_descent_m"] == 12
    assert small_bump["crossed_contours_m"] == [] and small_bump["total_ascent_m"] == 4
    assert along["net_grade_percent"] == 0 and along["total_ascent_m"] == 0
    for operation in (
        lambda: map_grade(0, 25000, 10),
        lambda: route([(0, 0, 110), (10, 0, 116)]),
        lambda: route([(0, 0, 104), (0, 0, 106)]),
    ):
        try:
            operation()
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")
    return {
        "environment": {"os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
                        "machine": platform.machine(), "python": sys.version.split()[0]},
        "map_cases": cases, "gap_uncertainty": measurement,
        "straight": straight, "zigzag": zigzag,
        "ridge": ridge, "small_bump": small_bump, "parallel_to_contours": along,
        "rejected": ["zero map gap", "vertex on contour", "zero horizontal segment"],
    }


def schematic(result):
    def point(x, y):
        return 116 + x * 3.8, 404 - y * 3.8

    def path(name):
        return " ".join(f"{px:g},{py:g}" for x, y, _ in result[name]["vertices_xyz_m"]
                        for px, py in [point(x, y)])

    lines = []
    for level in result["straight"]["crossed_contours_m"]:
        x, _ = point((level - 104) * 5, 0)
        lines.append(f'<path d="M{x:g} 75V429" stroke="#947349" stroke-width="2" stroke-dasharray="6 5"/>')
        lines.append(f'<text x="{x:g}" y="65" text-anchor="middle">{level} m</text>')
    contours = "\n".join(lines)
    return f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 710 485" role="img" aria-labelledby="title desc">
<title id="title">Two routes over the same slope</title>
<desc id="desc">A direct route and a zigzag share endpoints and cross the same two contours. The zigzag is longer.</desc>
<rect width="710" height="485" rx="20" fill="#f8f6ee"/>
<g font-family="system-ui, sans-serif" font-size="19" fill="#342d20">
<text x="32" y="39" font-weight="700">Plan view · horizontal geometry</text>
{contours}
<polyline points="{path("zigzag")}" fill="none" stroke="#98621b" stroke-width="5" stroke-linejoin="round"/>
<polyline points="{path("straight")}" fill="none" stroke="#165764" stroke-width="5"/>
<circle cx="116" cy="404" r="6" fill="#342d20"/>
<circle cx="572" cy="404" r="6" fill="#342d20"/>
<text x="116" y="456" text-anchor="middle">A · 104 m</text>
<text x="572" y="456" text-anchor="middle">B · 128 m</text>
<text x="439" y="96" fill="#7a4b10" font-weight="700">200 m · 12%</text>
<text x="341" y="385" text-anchor="middle" fill="#165764" font-weight="700">120 m · 20%</text>
</g>
</svg>
'''


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--svg", type=Path, help="write the route schematic")
    args = parser.parse_args()
    report = run_lab()
    if args.svg:
        args.svg.write_text(schematic(report), encoding="utf-8")
    print(json.dumps(report, indent=2))
