"""Example task: a winding path across hills, chosen among candidate routes by cut and fill and by
the water left on it after a storm, with conifers on the hills; written up as an HTML report.

    python path_over_hills.py <output folder>

Talks to jifto over MCP (jifto_mcp.py), the way Claude Code or Codex do. Builds the hills as a jifto
terrain, lays each candidate route out with a profile no steeper than the path allows, measures the
earthworks, rains on each design and reads the water standing on the path, then captures and reports.
"""
import csv
import html
import json
import math
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from jifto_mcp import Jifto  # noqa: E402

OUT = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "path-report")
os.makedirs(os.path.join(OUT, "data"), exist_ok=True)
jifto = Jifto()

SIZE, CELL = 180.0, 2.5
MAX_GRADE = 0.08          # an accessible path: 1 in 12.5
PATH_HALF_WIDTH = 1.0     # the default path section is a 2 m walk
RAIN, EVENT = 40.0, 0.5   # mm/h for half an hour
WET_MM = 10.0             # standing water on a path: 10 mm or more
DEPTH_SCALE_MM = 50.0     # the water legend's top: the deepest water on any route is well under it
EDGE_M = 3.0              # the plans leave out the site's outer 3 m, where the model lets runoff leave
PLAN_BOX = {"min": [-SIZE / 2 + EDGE_M, -SIZE / 2 + EDGE_M, -10], "max": [SIZE / 2 - EDGE_M, SIZE / 2 - EDGE_M, 30]}


def ground_height(x, y):
    """The existing hills: two rounded hills, a hollow between them, the land falling gently south."""
    north_hill = 11.0 * math.exp(-((x + 30) ** 2 + (y - 32) ** 2) / (2 * 30.0 ** 2))
    east_hill = 9.0 * math.exp(-((x - 42) ** 2 + (y + 18) ** 2) / (2 * 26.0 ** 2))
    hollow = -1.6 * math.exp(-((x - 4) ** 2 + (y - 2) ** 2) / (2 * 9.0 ** 2))
    return round(north_hill + east_hill + hollow + 0.025 * y, 3)


ROUTES = {
    "Direct": ("Straight from the gate to the lookout, over the east hill's shoulder.",
               [(-82, -62), (-40, -30), (0, 2), (40, 30), (78, 62)]),
    "Valley": ("Through the hollow between the hills, the lowest line.",
               [(-82, -62), (-50, -45), (-15, -12), (8, 4), (30, 30), (55, 52), (78, 62)]),
    "Contour": ("Winding around the north hill, keeping to its contours.",
                [(-82, -62), (-78, -25), (-72, 8), (-58, 42), (-32, 70), (0, 76), (34, 74), (60, 68), (78, 62)]),
}


def densify(plan, step=4.0):
    points = [plan[0]]
    for (x0, y0), (x1, y1) in zip(plan, plan[1:]):
        n = max(1, int(math.hypot(x1 - x0, y1 - y0) / step))
        points += [(x0 + (x1 - x0) * k / n, y0 + (y1 - y0) * k / n) for k in range(1, n + 1)]
    return points


def smooth_plan(plan, rounds=3):
    """Corner-cutting (Chaikin): a winding line from the route's turning points."""
    for _ in range(rounds):
        new = [plan[0]]
        for (x0, y0), (x1, y1) in zip(plan, plan[1:]):
            new += [(0.75 * x0 + 0.25 * x1, 0.75 * y0 + 0.25 * y1), (0.25 * x0 + 0.75 * x1, 0.25 * y0 + 0.75 * y1)]
        new.append(plan[-1])
        plan = new
    return plan


def design_profile(points, ground):
    """The path's levels: the ground smoothed, then no steeper than MAX_GRADE anywhere."""
    n = len(points)
    s = [0.0]
    for (x0, y0), (x1, y1) in zip(points, points[1:]):
        s.append(s[-1] + math.hypot(x1 - x0, y1 - y0))
    window = 3
    z = [sum(ground[max(0, i - window):i + window + 1]) / len(ground[max(0, i - window):i + window + 1]) for i in range(n)]
    for i in range(1, n):
        limit = MAX_GRADE * (s[i] - s[i - 1])
        z[i] = min(max(z[i], z[i - 1] - limit), z[i - 1] + limit)
    for i in range(n - 2, -1, -1):
        limit = MAX_GRADE * (s[i + 1] - s[i])
        z[i] = min(max(z[i], z[i + 1] - limit), z[i + 1] + limit)
    grade = max(abs(z[i + 1] - z[i]) / max(1e-9, s[i + 1] - s[i]) for i in range(n - 1))
    return z, s[-1], grade


def color_at(legend, value):
    """The colour jifto gives a value, from a legend as jifto_capture returns it (stops, min, max)."""
    lo, hi = legend.get("min", 0), legend.get("max", 1)
    t = min(1.0, max(0.0, (value - lo) / ((hi - lo) or 1)))
    stops = legend["stops"]
    for a, b in zip(stops, stops[1:]):
        if a["position"] <= t <= b["position"]:
            span = (b["position"] - a["position"]) or 1
            k = (t - a["position"]) / span
            ca = [int(a["color"][i:i + 2], 16) for i in (1, 3, 5)]
            cb = [int(b["color"][i:i + 2], 16) for i in (1, 3, 5)]
            return "#" + "".join(f"{round(x + (y - x) * k):02x}" for x, y in zip(ca, cb))
    return stops[-1]["color"]


def distance_to_polyline(px, py, line):
    best = float("inf")
    for (x0, y0), (x1, y1) in zip(line, line[1:]):
        dx, dy = x1 - x0, y1 - y0
        t = max(0.0, min(1.0, ((px - x0) * dx + (py - y0) * dy) / (dx * dx + dy * dy or 1)))
        best = min(best, math.hypot(px - (x0 + t * dx), py - (y0 + t * dy)))
    return best


# ── The site ─────────────────────────────────────────────────────────────────
status = jifto.call("jifto_status")
n = int(SIZE / CELL)
heights = [[ground_height(-SIZE / 2 + SIZE * i / n, -SIZE / 2 + SIZE * j / n) for i in range(n + 1)] for j in range(n + 1)]
ground = jifto.call("jifto_geometry", action="add", items=[{"kind": "mesh_grid", "origin": [-SIZE / 2, -SIZE / 2], "size": [SIZE, SIZE],
                                                              "heights": heights, "name": "Hills", "layer": "Site"}])["created"][0]["id"]
terrain = jifto.call("jifto_terrain", action="create", object_id=ground, name="Hills", measure=False)["terrain"]["id"]
# The site is a meadow: grass under everything, so a gravel path reads on it.
half = SIZE / 2 - 0.5
meadow = jifto.call("jifto_geometry", action="add", items=[{"kind": "polyline", "name": "Meadow", "layer": "Planting areas",
                                                            "points": [[-half, -half, 0], [half, -half, 0], [half, half, 0], [-half, half, 0], [-half, -half, 0]]}])["created"][0]["id"]
jifto.call("jifto_terrain", action="add", terrain=terrain, kind="material", sources=[meadow], settings={"Material": "Grass"}, measure=False)

# Conifers on both hilltops: one ecosystem on the terrain, inside the two curves. It keeps off the
# path and follows every design's earthworks; jifto_status counts its trees as they stand at the end.
tops = jifto.call("jifto_geometry", action="add", items=[
    {"kind": "circle", "center": [-30, 32, 0], "radius": 24, "name": "North hill wood", "layer": "Planting areas"},
    {"kind": "circle", "center": [42, -18, 0], "radius": 20, "name": "East hill wood", "layer": "Planting areas"}])["created"]
woods = jifto.call("jifto_trees", type="conifer", area={"terrain": terrain, "within": [top["id"] for top in tops], "spacing_m": 9},
                   height_m=14, crown_m=5)["ecosystem"]
jifto.call("jifto_geometry", action="layers", hide=["Planting areas"])

# Each route laid out on the existing ground: its plan smoothed, levels read from the Base, a profile designed.
designs = {}
for name, (_, plan) in ROUTES.items():
    line = densify(smooth_plan(plan), 4.0)
    base = jifto.call("jifto_terrain", action="heights", terrain=terrain, points=[[x, y] for x, y in line])["heights"]
    z_ground = [h["base_z"] for h in base]
    z, length, grade = design_profile(line, z_ground)
    designs[name] = {"line": line, "z": z, "ground": z_ground, "length": length, "grade": grade}

# ── Each candidate: earthworks, then a storm ─────────────────────────────────
# The water legend runs to 50 mm, so the depths that decide the routes take the whole colour scale.
jifto.call("jifto_settings", set={"stormwater.RainIntensity": RAIN, "stormwater.SimulationDuration": EVENT, "stormwater.Resolution": 1.0,
                                  "stormwater.NeutralTerrain": True, "stormwater.MaxDepth": DEPTH_SCALE_MM})
jifto.call("jifto_analysis", module="stormwater", analysis=[terrain])
path_modifier = None
results = {}
for name, d in designs.items():
    curve = jifto.call("jifto_geometry", action="add", items=[
        {"kind": "polyline", "points": [[x, y, z] for (x, y), z in zip(d["line"], d["z"])], "name": f"{name} route", "layer": "Routes"}])["created"][0]["id"]
    d["curve"] = curve
    if path_modifier is None:
        reply = jifto.call("jifto_terrain", action="add", terrain=terrain, kind="path", sources=[curve])
        path_modifier = reply["did"].split(" ")[1]
    else:
        reply = jifto.call("jifto_terrain", action="set", terrain=terrain, modifier=path_modifier, sources=[curve])
    cut_fill = reply["metrics"]["cut_fill"]

    # Earthworks first, with no water drawn over them: the terrain coloured by cut and fill.
    jifto.call("jifto_analysis", module="stormwater", on=False)
    jifto.call("jifto_terrain", action="set", terrain=terrain, surface="cut_fill", measure=False)
    jifto.call("jifto_capture", view="top", box=PLAN_BOX, width=900, height=900, margin=0.0, path=os.path.join(OUT, f"{name}-cutfill.png"))
    terrain_state = jifto.call("jifto_terrain", action="describe", terrain=terrain)["terrain"]
    jifto.call("jifto_terrain", action="set", terrain=terrain, surface="material", measure=False)

    job = jifto.call("jifto_run", module="stormwater", wait_seconds=600)
    if job["state"] != "done":
        raise RuntimeError(f"{name}: {job}")
    points = jifto.call("jifto_results", module="stormwater", points=True, path=os.path.join(OUT, "data", f"{name}-water.csv"))
    on_path = []
    with open(points["file"], newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            x, y = float(row["x"]), float(row["y"])
            value = row.get("Water depth", "") or next((v for k, v in row.items() if k not in ("object_id", "x", "y", "z")), "")
            if value == "":
                continue
            if distance_to_polyline(x, y, d["line"]) <= PATH_HALF_WIDTH:
                on_path.append(float(value))
    wet = [v for v in on_path if v >= WET_MM]
    shallow = [v for v in on_path if 1.0 <= v < WET_MM]
    storm_capture = jifto.call("jifto_capture", view="top", box=PLAN_BOX, width=900, height=900, margin=0.0,
                               path=os.path.join(OUT, f"{name}-water.png"))
    results[name] = {
        "length_m": d["length"], "grade_pct": 100 * d["grade"],
        "cut_m3": cut_fill["cut_m3"], "fill_m3": cut_fill["fill_m3"], "moved_m3": cut_fill["moved_m3"], "net_m3": cut_fill["net_m3"],
        "deepest_cut_m": cut_fill["deepest_cut_m"], "highest_fill_m": cut_fill["highest_fill_m"],
        "path_points": len(on_path), "wet_share_pct": 100.0 * len(wet) / max(1, len(on_path)), "max_water_mm": max(on_path) if on_path else 0.0,
        "shallow_share_pct": 100.0 * len(shallow) / max(1, len(on_path)),
        "water_legend": storm_capture.get("legend"), "cutfill_legend": terrain_state.get("legend"),
        "event_minutes": job["progress"]["done"],
    }

# The choice: least earth moved among the routes that stay dry (under 5% of the path under 10 mm of water).
dry = [k for k in results if results[k]["wet_share_pct"] < 5]
pool = dry or list(results)
chosen = min(pool, key=lambda k: results[k]["moved_m3"])
d = designs[chosen]
jifto.call("jifto_terrain", action="set", terrain=terrain, modifier=path_modifier, sources=[d["curve"]])
jifto.call("jifto_analysis", module="stormwater", on=False)
jifto.call("jifto_geometry", action="layers", hide=["Routes"])
# The chosen design on its own: the terrain coloured by elevation, the path and the conifers.
# The meadow in its material with contour lines every metre (a thicker one every 5 m), so the hills
# read; the gravel walk reads on the grass.
jifto.call("jifto_terrain", action="set", terrain=terrain, surface="material", measure=False,
           contours={"interval": 1.0, "major_every": 5, "labels": False, "color": "#ffffff"})
jifto.call("jifto_capture", view="perspective", frame=[ground], width=1600, height=820, margin=0.0, path=os.path.join(OUT, "chosen-perspective.png"))
elevation = jifto.call("jifto_terrain", action="set", terrain=terrain, surface="elevation", measure=False,
                       contours={"visible": False})["terrain"].get("legend")
jifto.call("jifto_capture", view="top", frame=[ground], width=900, height=900, margin=0.0, path=os.path.join(OUT, "chosen-plan.png"))

# ── The report ───────────────────────────────────────────────────────────────
jifto.call("jifto_report_kit", folder=OUT)


def attr(data):
    return html.escape(json.dumps(data), quote=True)


def num(value, digits=0):
    return f"{value:,.{digits}f}".replace(",", " ")


r = results[chosen]
others = [k for k in results if k != chosen]
least_other = min(others, key=lambda k: results[k]["moved_m3"])
answer = (f"<b>The {chosen.lower()} route</b> is the one to build: it moves <b>{num(r['moved_m3'])} m³</b> of earth, "
          f"{num(results[least_other]['moved_m3'] - r['moved_m3'])} m³ less than the {least_other.lower()} route" if results[least_other]['moved_m3'] > r['moved_m3']
          else f"<b>The {chosen.lower()} route</b> is the one to build: it moves <b>{num(r['moved_m3'])} m³</b> of earth")
answer += (f", and after half an hour of {num(RAIN)} mm/h rain only {num(r['wet_share_pct'], 1)}% of it stands under {num(WET_MM)} mm of water or more."
           if r["wet_share_pct"] > 0 else f", and after half an hour of {num(RAIN)} mm/h rain none of it stands under water.")
wettest = max(results, key=lambda k: results[k]["wet_share_pct"])
if wettest != chosen and results[wettest]["wet_share_pct"] >= 5:
    w = results[wettest]
    # The trade-off the reader needs: a route that moves less earth but stays wet.
    answer += (f" The {wettest.lower()} route moves less earth ({num(w['moved_m3'])} m³), but water stands on {num(w['wet_share_pct'], 1)}% of it."
               if w["moved_m3"] < r["moved_m3"] else f" The {wettest.lower()} route holds water on {num(w['wet_share_pct'], 1)}% of its length.")

criteria = [
    ("Length", "length_m", "m", 0, min), ("Steepest grade", "grade_pct", "%", 1, min),
    ("Cut", "cut_m3", "m³", 0, min), ("Fill", "fill_m3", "m³", 0, min), ("Earth moved", "moved_m3", "m³", 0, min),
    ("Deepest cut", "deepest_cut_m", "m", 2, max), ("Highest fill", "highest_fill_m", "m", 2, min),
    ("Path under 10 mm of water or more", "wet_share_pct", "%", 1, min), ("Deepest water on the path", "max_water_mm", "mm", 0, min),
]
head = "".join(f'<th>{k}<br><span class="unit">{html.escape(ROUTES[k][0].split(",")[0])}</span></th>' for k in results)
body = []
for label, key, unit, digits, better in criteria:
    values = [results[k][key] for k in results]
    target = better(values)
    cells = "".join(f'<td class="{"best" if results[k][key] == target and max(values) != min(values) else ""}">{num(results[k][key], digits)} <span class="unit">{unit}</span></td>' for k in results)
    body.append(f"<tr><td>{label}</td>{cells}</tr>")

trees = next(e["trees"] for e in jifto.call("jifto_status")["vegetation"]["ecosystems"] if e["id"] == woods)
figures = (f'<div class="figure good"><span class="value">{num(r["moved_m3"])} <small>m³</small></span><span class="label">earth moved by the {chosen.lower()} route ({num(r["cut_m3"])} cut, {num(r["fill_m3"])} fill)</span></div>'
           f'<div class="figure"><span class="value">{num(r["length_m"])} <small>m</small></span><span class="label">long, never steeper than {num(r["grade_pct"], 1)}%</span></div>'
           f'<div class="figure"><span class="value">{num(r["max_water_mm"])} <small>mm</small></span><span class="label">deepest water on it after the storm</span></div>'
           f'<div class="figure"><span class="value">{trees}</span><span class="label">conifers on the two hilltops</span></div>')

CHOSEN_TAG = ' &nbsp;<span class="note">chosen</span>'
columns = "".join(f'<div class="colhead"><b>{k}</b>{CHOSEN_TAG if k == chosen else ""}<br><span class="note">{html.escape(ROUTES[k][0])}</span></div>' for k in results)
cut_row = "".join(f'<figure class="capture{" chosen" if k == chosen else ""}"><img src="{k}-cutfill.png" alt="{k}, cut and fill"><figcaption>Cut and fill <b>{num(results[k]["moved_m3"])} m³</b></figcaption></figure>' for k in results)
water_row = "".join(f'<figure class="capture{" chosen" if k == chosen else ""}"><img src="{k}-water.png" alt="{k}, water"><figcaption>{num(WET_MM)} mm or more on <b>{num(results[k]["wet_share_pct"], 1)}%</b> of the path</figcaption></figure>' for k in results)
cut_legend = next((results[k]["cutfill_legend"] for k in results if results[k]["cutfill_legend"]), None)
water_legend = next((results[k]["water_legend"] for k in results if results[k]["water_legend"]), None)


def path_bands(k):
    """The path's length by water depth at the end of the storm, coloured as the plans colour it."""
    res = results[k]
    standing, film = res["wet_share_pct"], res["shallow_share_pct"]
    rows = [{"label": "dry, under 1 mm", "share_pct": round(100 - standing - film, 1), "color": "#e4e3df"},
            {"label": f"1 to {num(WET_MM)} mm", "share_pct": round(film, 1), "color": color_at(water_legend, 4) if water_legend else "#a6d3fb"},
            {"label": f"{num(WET_MM)} mm or more", "share_pct": round(standing, 1), "color": color_at(water_legend, 25) if water_legend else "#3d7fd1"}]
    return rows


path_bars = "".join(
    f'<div class="bar" data-label="{html.escape(k)}: {num(results[k]["wet_share_pct"], 1)}% under {num(WET_MM)} mm or more, deepest {num(results[k]["max_water_mm"])} mm" '
    f'data-stats="{attr(path_bands(k))}"></div>' for k in results)
meta = f'<div class="meta"><img class="north" src="north.svg" alt="North">Site 180 &times; 180 m<br>jifto {html.escape(status.get("version", ""))}</div>'

report = f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>A path across the hills</title>
<link rel="stylesheet" href="jifto-report.css"><script src="jifto-report.js"></script>
<style>:root {{ --accent: #9d897c; }}</style></head><body>

<section class="page">
  <header class="page-head"><div><h1>A path across the hills</h1>
    <p class="lead">Three routes from the gate in the south-west to the lookout in the north-east, each laid out no steeper than 1 in 12.5, compared by the earth they move and the water they hold after a storm.</p></div>
    {meta}</header>
  <p class="answer">{answer}</p>
  <div class="figures">{figures}</div>
  <div class="columns wide-left"><div>
    <table class="compare"><thead><tr><th>Route</th>{head}</tr></thead><tbody>{"".join(body)}</tbody>
      <caption>Cut and fill against the existing ground at 0.25 m; water after {int(EVENT * 60)} minutes of {num(RAIN)} mm/h rain, on a 1 m grid, within 1 m of the path's line.</caption></table></div>
    <div><figure class="capture chosen"><img src="chosen-plan.png" alt="The chosen route"><figcaption>Top View | <b>{chosen} route</b>, conifers on the hills</figcaption></figure>
      {f'<div class="legend" data-legend="{attr(elevation)}"></div>' if elevation else ''}</div></div>
  <footer><img src="jifto_logo.svg" alt="jifto"><span>1</span></footer>
</section>

<section class="page">
  <header class="page-head"><div><h2>Earthworks and water, route by route</h2>
    <p class="lead">Top: the terrain coloured by cut (below the existing ground) and fill (above it). Bottom: water depth at the end of the storm.</p></div>{meta}</header>
  <div class="plate"><div class="grid with-rowheads">
    <div></div>{columns}
    <div class="rowhead">Cut and fill<span>against the existing ground</span></div>{cut_row}
    <div class="rowhead">Water<span>after {int(EVENT * 60)} min of {num(RAIN)} mm/h</span></div>{water_row}
  </div>
  <div class="side">
    {f'<div class="legend" data-legend="{attr(cut_legend)}"></div>' if cut_legend else ''}
    {f'<div class="legend" data-legend="{attr(water_legend)}"></div>' if water_legend else ''}
    <h3>Water along each path</h3>
    {path_bars}
    <p class="note">Bands of the path's length (within 1 m of its line) by the water on it at the end of the storm: grey dry, pale blue a film of
      1 to {num(WET_MM)} mm, blue {num(WET_MM)} mm or more.</p>
    <p class="note">The palest blue on the open slopes is sheet flow, a film of 1 to 3 mm running downhill, not ponding. The plans leave out the
      site's outer {num(EDGE_M)} m: the model lets runoff leave the site there, and the water at the edge is that outflow.</p>
    <p class="note">Cut and fill are measured against the existing ground; the path's own section (a 2 m gravel walk with grass slopes) is part of the new terrain.</p>
  </div></div>
  <footer><img src="jifto_logo.svg" alt="jifto"><span>2</span></footer>
</section>

<section class="page">
  <header class="page-head"><div><h2>The {chosen.lower()} route</h2>
    <p class="lead">{html.escape(ROUTES[chosen][0])} Seen from the south-west, with the conifers on the hilltops.</p></div>{meta}</header>
  <figure class="capture hero"><img src="chosen-perspective.png" alt="Perspective of the chosen route"><figcaption>Perspective View | <b>{chosen} route</b>, a gravel walk on the meadow, contours every metre, conifers on the hilltops</figcaption></figure>
  <div class="method">
    <h3>Method</h3>
    <p>The hills are a jifto terrain; each route's line is smoothed, its levels read from the existing ground every 4 m, smoothed and limited to an 8% grade both ways, and embedded as a path: a 2 m gravel walk with 30&deg; grass slopes cut into or built up from the ground. jifto measures cut and fill between the existing ground and the new terrain on a 0.25 m grid.</p>
    <p>For each route jifto rains {num(RAIN)} mm/h for {int(EVENT * 60)} minutes on the new terrain (shallow-water flow on a 1 m grid) and the depth left on the cells within 1 m of the path's line is read at the end of the storm. A route counts as dry when less than 5% of it stands under {num(WET_MM)} mm or more.</p>
    <p>The site is a grass meadow and the path a gravel walk: in jifto's materials 20% of the rain on grass runs off and 35% on gravel; the rest soaks in.</p>
    <h3>Limits</h3>
    <p>No drains or culverts are modelled, and the soaking in is a fixed share of the rain, not a soil model. The routes are three hand-drawn candidates, not an optimisation over every line; the earthworks are geometric volumes without bulking.</p>
  </div>
  <footer><img src="jifto_logo.svg" alt="jifto"><span>3</span></footer>
</section>
</body></html>
"""
with open(os.path.join(OUT, "report.html"), "w", encoding="utf-8") as f:
    f.write(report)
with open(os.path.join(OUT, "results.json"), "w", encoding="utf-8") as f:
    json.dump({k: {kk: vv for kk, vv in v.items() if not kk.endswith("legend")} for k, v in results.items()}, f, indent=1)
print(json.dumps({"report": os.path.join(OUT, "report.html"), "chosen": chosen,
                  "routes": {k: {kk: round(vv, 2) for kk, vv in v.items() if isinstance(vv, float)} for k, v in results.items()}}))
