"""Example task: three design options around a courtyard, compared by sun hours on the equinox and
both solstices, written up as an HTML report in jifto's look.

    python courtyard_sunlight.py <output folder>

Talks to jifto over MCP (jifto_mcp.py), the way Claude Code or Codex do. Builds the options in an
empty Rhino document, runs one sunlight job per option and day, reads the courtyard's sun hours from
the points, captures each result and writes report.html with the report kit.
"""
import csv
import html
import json
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 "courtyard-report")
os.makedirs(OUT, exist_ok=True)
jifto = Jifto()

HALF = 16.0      # the courtyard is 32 x 32 m
DEPTH = 12.0     # wings are 12 m deep
DAYS = [
    ("equinox", "Equinox", "20 March", "6–18 h"),
    ("summer", "Summer Solstice", "21 June", "5–21 h"),
    ("winter", "Winter Solstice", "21 December", "9–15 h"),
]


def wing(side, height, option):
    c, d = HALF, DEPTH
    box = {
        "north": (-c - d, c, c + d, c + d),
        "south": (-c - d, -c - d, c + d, -c),
        "west": (-c - d, -c, -c, c),
        "east": (c, -c, c + d, c),
    }[side]
    x0, y0, x1, y1 = box
    return {"kind": "extrusion", "outline": [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], "base_z": 0, "height": height,
            "name": f"{option} {side} wing", "layer": f"Option {option}"}


OPTIONS = {
    "A": ("Closed courtyard", "Four wings of six storeys (18 m) close the courtyard on every side.",
          [("north", 18), ("south", 18), ("west", 18), ("east", 18)]),
    "B": ("Open to the south", "Three wings of six storeys (18 m); the south side stays open.",
          [("north", 18), ("west", 18), ("east", 18)]),
    "C": ("Stepped to the south", "North wing seven storeys (21 m), east and west four (12 m), south wing two (6 m).",
          [("north", 21), ("south", 6), ("west", 12), ("east", 12)]),
}

# ── The scene ────────────────────────────────────────────────────────────────
status = jifto.call("jifto_status")
location = status.get("location", {})
flat = [[0.0] * 8 for _ in range(8)]
ground = jifto.call("jifto_geometry", action="add", items=[
    {"kind": "mesh_grid", "origin": [-70, -70], "size": [140, 140], "heights": flat, "name": "Ground", "layer": "Site"}])["created"][0]["id"]
wings = {}
for key, (_, _, sides) in OPTIONS.items():
    made = jifto.call("jifto_geometry", action="add", items=[wing(side, height, key) for side, height in sides])
    wings[key] = [m["id"] for m in made["created"]]
GRID_M = 0.5  # half a metre: the shadows' edges read smoothly in the plans, and a day still takes well under a second
# One legend for every day, fitted to the longest day studied (summer, 5 to 21 h): the panel's Range
# (sunlight.MaxSunHours), so summer's open ground does not saturate and the days still compare.
SCALE_HOURS = 16
jifto.call("jifto_settings", set={"sunlight.MaxSunHours": SCALE_HOURS})
jifto.call("jifto_settings", set={"sunlight.Resolution": GRID_M, "sunlight.TemporalResolution": 15})


def bands(hours, legend):
    """Shares of the courtyard in each band of the legend (between two stops), coloured as jifto does."""
    stops = sorted(legend["stops"], key=lambda s: s["position"])
    lo, hi = legend["min"], legend["max"]
    edges = [lo + (hi - lo) * s["position"] for s in stops]
    rows = []
    for i in range(len(stops) - 1):
        last = i == len(stops) - 2
        inside = sum(1 for h in hours if edges[i] <= h < edges[i + 1] or (last and h >= edges[i + 1]))
        rows.append({"label": f"{stops[i]['label']}–{stops[i + 1]['label']}", "share_pct": round(100.0 * inside / len(hours), 1), "color": stops[i]["color"]})
    return rows


def courtyard_hours(points_file):
    """Sun hours of the analysis points inside the courtyard (ground only, z near 0)."""
    hours = []
    with open(points_file, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            x, y, z, value = float(row["x"]), float(row["y"]), float(row["z"]), row.get("Sun hours", "")
            if value == "" or abs(z) > 0.5 or abs(x) >= HALF or abs(y) >= HALF:
                continue
            hours.append(float(value))
    return hours


results = {}
legends = {}
site_stats = {}
courtyard_bands = {}
for key, (title, _, _) in OPTIONS.items():
    jifto.call("jifto_geometry", action="layers", only=["Site", f"Option {key}"])
    # The wings are analysis surfaces too: their roofs and facades get sun hours, and they shade.
    jifto.call("jifto_analysis", module="sunlight", analysis=[ground] + wings[key], clear="context")
    for day, day_title, _, _ in DAYS:
        jifto.call("jifto_settings", set={"sunlight.day": day})
        job = jifto.call("jifto_run", module="sunlight", wait_seconds=300)
        if job["state"] != "done":
            raise RuntimeError(f"Option {key}, {day}: {job}")
        points = jifto.call("jifto_results", module="sunlight", points=True, path=os.path.join(OUT, "data", f"{key}-{day}.csv"))
        capture = jifto.call("jifto_capture", view="top", box={"min": [-48, -48, 0], "max": [48, 48, 21]},
                             width=900, height=900, margin=0, path=os.path.join(OUT, f"{key}-{day}.png"))
        hours = courtyard_hours(points["file"])
        courtyard_bands[(key, day)] = bands(hours, capture["legend"])
        results[(key, day)] = {
            "mean": sum(hours) / len(hours),
            "two_hours": 100.0 * sum(1 for h in hours if h >= 2) / len(hours),
            "min": min(hours), "max": max(hours),
        }
        legends[day] = capture["legend"]
        site_stats[(key, day)] = capture["legend"].get("statistics", [])
    jifto.call("jifto_settings", set={"sunlight.day": "equinox"})
    jifto.call("jifto_run", module="sunlight", wait_seconds=300)
    jifto.call("jifto_capture", view="perspective", frame=wings[key] + [ground], width=1200, height=800, margin=0.0,
               camera={"location": [-95, -120, 85], "target": [0, 0, 6], "lens_mm": 50},
               path=os.path.join(OUT, f"{key}-perspective.png"))

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


def fmt(value, digits=1):
    return f"{value:.{digits}f}"


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


equinox = {k: results[(k, "equinox")] for k in OPTIONS}
best = max(OPTIONS, key=lambda k: equinox[k]["mean"])
worst = min(OPTIONS, key=lambda k: equinox[k]["mean"])
passing = [k for k in OPTIONS if equinox[k]["two_hours"] >= 50]
winter_best = max(OPTIONS, key=lambda k: results[(k, "winter")]["mean"])
gain = equinox[best]["mean"] - equinox[worst]["mean"]
answer = (f"<b>Option {best} ({OPTIONS[best][0].lower()})</b> gives the courtyard the most sun: "
          f"<b>{fmt(equinox[best]['mean'])} hours</b> on average at the equinox, {fmt(gain)} more than option {worst}. ")
if passing:
    names = "Option " + passing[0] if len(passing) == 1 else "Options " + ", ".join(passing[:-1]) + " and " + passing[-1]
    rest = [k for k in OPTIONS if k not in passing]
    answer += (f"{names} {'meets' if len(passing) == 1 else 'meet'} the guideline of two hours of sun on half the courtyard on 20 March"
               + (f"; {'option ' + rest[0] if len(rest) == 1 else 'options ' + ' and '.join(rest)} {'does' if len(rest) == 1 else 'do'} not." if rest else "."))
else:
    answer += "No option meets the guideline of two hours of sun on half the courtyard on 20 March."
if winter_best != best:
    answer += f" In midwinter option {winter_best} does best."

rows = []
for key, (title, _, _) in OPTIONS.items():
    cells = []
    for day, _, _, _ in DAYS:
        values = [results[(k, day)]["mean"] for k in OPTIONS]
        v = results[(key, day)]["mean"]
        cls = "best" if v == max(values) and max(values) > min(values) else ("worst" if v == min(values) and max(values) > min(values) else "")
        cells.append(f'<td class="{cls}">{fmt(v)} <span class="unit">h</span></td>')
        if day == "equinox":
            share = results[(key, day)]["two_hours"]
            shares = [results[(k, day)]["two_hours"] for k in OPTIONS]
            cls2 = "best" if share == max(shares) and max(shares) > min(shares) else ""
            cells.append(f'<td class="{cls2}">{fmt(share, 0)} <span class="unit">%</span></td>')
    verdict = "meets" if equinox[key]["two_hours"] >= 50 else "below"
    rows.append(f'<tr class="{"chosen" if key == best else ""}"><td><b>{key}</b> {html.escape(title)}<br><span class="unit">{html.escape(OPTIONS[key][1])}</span></td>{"".join(cells)}'
                f'<td class="{"best" if verdict == "meets" else "worst"}">{verdict}</td></tr>')

figures = "".join(
    f'<div class="figure{" good" if k == best else ""}"><span class="value">{fmt(equinox[k]["mean"])} <small>h</small></span>'
    f'<span class="label">Option {k}: courtyard at the equinox; {fmt(equinox[k]["two_hours"], 0)}% of it gets two hours or more</span></div>'
    for k in OPTIONS)

grid = ['<div></div>'] + [f'<div class="colhead"><b>{d_title}</b><br><span class="note">{d_date}, {d_hours}</span></div>' for _, d_title, d_date, d_hours in DAYS]
for key, (title, note, _) in OPTIONS.items():
    grid.append(f'<div class="rowhead">Option {key}<span>{html.escape(title)}</span></div>')
    for day, d_title, _, _ in DAYS:
        r = results[(key, day)]
        grid.append(f'<figure class="capture{" chosen" if key == best and day == "equinox" else ""}"><img src="{key}-{day}.png" alt="Option {key}, {d_title}">'
                    f'<figcaption>Courtyard <b>{fmt(r["mean"])} h</b></figcaption></figure>')

perspectives = "".join(
    f'<figure class="capture{" chosen" if k == best else ""}"><img src="{k}-perspective.png" alt="Option {k}">'
    f'<figcaption>Perspective View | <b>Option {k}</b>, {html.escape(OPTIONS[k][0].lower())}</figcaption></figure>' for k in OPTIONS)
descriptions = "".join(f"<li><b>Option {k}: {html.escape(t)}.</b> {html.escape(n)}</li>" for k, (t, n, _) in OPTIONS.items())
lat, lon = location.get("latitude", 0), location.get("longitude", 0)
place = f"{abs(lat):.2f}° {'N' if lat >= 0 else 'S'}, {abs(lon):.2f}° {'E' if lon >= 0 else 'W'}"
page_meta = f'<div class="meta"><img class="north" src="north.svg" alt="North">{html.escape(place)}<br>jifto {html.escape(status.get("version", ""))}</div>'

report = f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Courtyard sunlight: three options</title>
<link rel="stylesheet" href="jifto-report.css"><script src="jifto-report.js"></script></head><body>

<section class="page">
  <header class="page-head"><div><h1>Courtyard sunlight</h1>
    <p class="lead">Three ways to build around a 32 &times; 32 m courtyard, compared by the hours of direct sun on its ground on the equinox and both solstices.</p></div>
    {page_meta}</header>
  <p class="answer">{answer}</p>
  <div class="figures">{figures}</div>
  <div class="columns wide-left"><div>
  <table class="compare">
    <thead><tr><th>Option</th><th>Equinox<br><span class="unit">mean</span></th><th>Equinox<br><span class="unit">area with 2 h or more</span></th>
      <th>Summer solstice<br><span class="unit">mean</span></th><th>Winter solstice<br><span class="unit">mean</span></th><th>2-hour guideline<br><span class="unit">20 March</span></th></tr></thead>
    <tbody>{"".join(rows)}</tbody>
    <caption>Hours of direct sun on the courtyard's ground, averaged over its area ({GRID_M:g} m grid, 15-minute steps). The guideline: at least half of an outdoor amenity space should see two hours of sun on 20 March.</caption>
  </table></div>
    <div><h3>The courtyard at the equinox, by hours of sun</h3>
      {"".join(f'<div class="bar" data-label="Option {k}" data-stats="{attr(courtyard_bands[(k, "equinox")])}"></div>' for k in OPTIONS)}
      <div class="legend" data-legend="{attr(legends['equinox'])}"></div></div></div>
  <footer><img src="jifto_logo.svg" alt="jifto"><span>1</span></footer>
</section>

<section class="page">
  <header class="page-head"><div><h2>Where the sun reaches</h2>
    <p class="lead">Sun hours on the ground, roofs and facades of each option, seen from above (north up).</p></div>
    {page_meta}</header>
  <div class="plate"><div class="grid with-rowheads">{"".join(grid)}</div>
    <div class="side"><div class="legend" data-legend="{attr(legends['equinox'])}"></div>
      <p class="note">One scale for every day, 0 to {SCALE_HOURS} h (the length of the longest day studied, set with the panel's Range), so the days compare at a glance and summer does not saturate.</p>
      <p class="note">The green frame marks the answer: option {best} at the equinox.</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 options in 3D</h2>
    <p class="lead">Sun hours at the equinox, seen from the south-west.</p></div>{page_meta}</header>
  <div class="grid three">{perspectives}</div>
  <div class="legend" data-legend="{attr(legends['equinox'])}"></div>
  <div class="method">
    <h3>Method</h3>
    <p>jifto's sunlight analysis traces the sun's direct beam to every point of a {GRID_M:g} m grid on the ground, the roofs and the facades, every 15 minutes between the hours given for each day, and counts the hours in sun. Every building casts shadows on the others and on the ground.</p>
    <p>The courtyard's figures average the ground points inside its 32 &times; 32 m. Days and hours: 20 March 6&ndash;18 h, 21 June 5&ndash;21 h, 21 December 9&ndash;15 h, at {html.escape(place)}.</p>
    <h3>Limits</h3>
    <p>Direct sun only: no diffuse sky light, no reflections, no weather; surrounding buildings and trees outside the scheme are not modelled. Wings are simple blocks without balconies or roof plant.</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({f"{k}-{d}": v for (k, d), v in results.items()}, f, indent=1)
print(json.dumps({"report": os.path.join(OUT, "report.html"), "best": best, "equinox": equinox}))
