"""Displacement Dashboard: data layer for the annual update.

Purpose: read the Metropolitan Council's transit and permit layers (as GeoJSON
exported from ArcGIS, or fetched from the Council's public ArcGIS REST
services), order every line's stations, assign each permitted home to its
nearest station on each line it is flagged for, and return one plain data
model the page renderer and the map read.

Standard library only (Python 3.9+), so it runs in the Python that ships with
ArcGIS Pro or any stock Python 3. No network access unless --fetch is used.

Owner: Metropolitan Council, Metro Transit TOD Office (built by Stoa).
"""
from __future__ import annotations

import json
import math
import re
import time
import urllib.request
from collections import defaultdict
from pathlib import Path

ARCGIS = "https://arcgis.metc.state.mn.us/arcgis/rest/services"
SERVICES = {
    "dtat": ARCGIS + "/transit/DevelopmentTrendsAlongTransit/FeatureServer",
    "transit": ARCGIS + "/LPH/Transportation_Transit/FeatureServer",
    "admin": ARCGIS + "/LPH/AdministrativeDemographic/MapServer",
    # Census Bureau TIGERweb (public domain): the seven metro counties as whole outlines
    "census": "https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/State_County/MapServer",
}
METRO_COUNTY_WHERE = "STATE%3D%2727%27+AND+COUNTY+IN+(%27003%27,%27019%27,%27037%27,%27053%27,%27123%27,%27139%27,%27163%27)"
# City names as the cities write them (the layers abbreviate some).
CITY_NAMES = {
    "St Paul": "Saint Paul", "St. Paul": "Saint Paul",
    "St Louis Park": "St. Louis Park", "West St Paul": "West St. Paul",
    "Fort Snelling (unorg.)": "Fort Snelling", "Fort Snelling (Unorganized)": "Fort Snelling",
}


def city_name(raw):
    raw = (raw or "").strip()
    return CITY_NAMES.get(raw, raw)


# input file stem -> (service, layer id, extra query)
LAYERS = {
    "dtat-stations": ("dtat", 4, ""),
    "dtat-alignments": ("dtat", 5, ""),
    "high-frequency-network": ("dtat", 6, ""),
    "dtat-areas": ("dtat", 7, ""),
    "dtat-permits-residential": ("dtat", 0, ""),
    "transitway-stations-existing": ("transit", 3, ""),
    "transitway-stations-planned": ("transit", 4, ""),
    "counties": ("census", 1, "&maxAllowableOffset=0.0005"),
    "cities-townships": ("admin", 3, "&maxAllowableOffset=0.0003"),
}

# The fields this update reads from each layer. Before anything is written, every
# layer is checked for them, so a renamed field stops the update with a plain
# message instead of a wrong page.
FIELDS_READ = {
    "dtat-stations": ["RT_NAME", "STATION", "CITY"],
    "dtat-alignments": ["RT_NAME", "RT_STATUS", "LENGTH_MI"],
    "high-frequency-network": ["LINE_ID", "DIRECTION"],
    "dtat-areas": ["AREA_NAME", "AREA_ACRES"],
    "dtat-permits-residential": ["YEAR", "UNITS", "TENURE", "HOUSING_TYPE_DESC", "CTU_NAME", "NAME", "HFLOCALBUS"],
    "transitway-stations-existing": ["NameTransitway", "MapLabel", "NameStation", "StationStatus", "CompletionDate"],
    "transitway-stations-planned": ["NameTransitway", "MapLabel", "NameStation", "StationStatus", "CompletionDate"],
}
# If the Council renames a field, add it here as "new name": "name above" and run
# the update again; nothing else in the code changes. Example: {"PERMIT_YEAR": "YEAR"}
FIELD_RENAMES: dict[str, str] = {}

FIRST_YEAR, LAST_YEAR = 2009, 2024  # years covered by the DTAT permit data

# The lines the TOD Office tracks in Development Trends Along Transit, in the
# office's own order, with its map colors. `flag` is the permit field that marks
# a permit inside the line's half-mile corridor; `dtat` is the alignment/area
# name; `transitway` is the name in the Council's transitway station layer.
LINES = [
    {"id": "blue-line", "name": "Blue Line", "mode": "lrt", "color": "#0053A0", "flag": "BLUELINE", "dtat": "Blue Line", "transitway": "Blue Line"},
    {"id": "green-line", "name": "Green Line", "mode": "lrt", "color": "#008244", "flag": "GREENLINE", "dtat": "Green Line", "transitway": "Green Line"},
    {"id": "a-line", "name": "A Line", "mode": "abrt", "color": "#A10080", "flag": "ALINE", "dtat": "A Line", "transitway": "A Line"},
    {"id": "b-line", "name": "B Line", "mode": "abrt", "color": "#3A0078", "flag": "BLINE", "dtat": "B Line", "transitway": "B Line"},
    {"id": "c-line", "name": "C Line", "mode": "abrt", "color": "#0097D0", "flag": "CLINE", "dtat": "C Line", "transitway": "C Line"},
    {"id": "d-line", "name": "D Line", "mode": "abrt", "color": "#D96FF0", "flag": "DLINE", "dtat": "D Line", "transitway": "D Line"},
    {"id": "e-line", "name": "E Line", "mode": "abrt", "color": "#A00000", "flag": "ELINE", "dtat": "E Line", "transitway": "E Line"},
    {"id": "orange-line", "name": "Orange Line", "mode": "brt", "color": "#F68B1F", "flag": "ORANGELINE", "dtat": "Orange Line", "transitway": "Orange Line"},
    {"id": "gold-line", "name": "Gold Line", "mode": "brt", "color": "#FFD200", "flag": "GOLDLINE", "dtat": "Gold Line", "transitway": "Gold Line"},
    {"id": "f-line", "name": "F Line", "mode": "abrt", "color": "#007048", "flag": "FLINE", "dtat": "F Line", "transitway": "F Line"},
    {"id": "g-line", "name": "G Line", "mode": "abrt", "color": "#0097D0", "flag": "GLINE", "dtat": "G Line", "transitway": "G Line"},
    {"id": "green-line-extension", "name": "Green Line Extension", "mode": "lrt", "color": "#008244", "flag": "GREENEXTENSION", "dtat": "Green Line Ext.", "transitway": "Green Line Extension"},
    {"id": "blue-line-extension", "name": "Blue Line Extension", "mode": "lrt", "color": "#0053A0", "flag": "BLUEEXTENSION", "dtat": "Blue Line Ext.", "transitway": "Blue Line Extension"},
]
HF_BUS = {"id": "high-frequency-bus", "name": "High Frequency Network", "mode": "hfbus", "color": "#484848", "flag": "HFLOCALBUS", "dtat": "All High Frequency Routes"}

MODES = {
    "lrt": "Light rail",
    "brt": "Bus rapid transit",
    "abrt": "Arterial bus rapid transit",
    "hfbus": "High Frequency bus",
}
TENURE = {"OWN": "own", "RNT": "rent", "COP": "co-op"}
HOUSING_TYPE = {
    "Multifamily (5 units or more)": "mf",
    "Townhomes (single-family attached)": "th",
    "Duplex, triplex and quad": "dtq",
    "Accessory Dwelling Unit": "adu",
}

# ---------------------------------------------------------------- geometry ---

EARTH_MI = 3958.7613


def miles(a, b):
    """Great-circle distance in miles between two (lon, lat) points."""
    lon1, lat1, lon2, lat2 = map(math.radians, (a[0], a[1], b[0], b[1]))
    h = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
    return 2 * EARTH_MI * math.asin(min(1.0, math.sqrt(h)))


def _perp(p, a, b):
    # perpendicular distance in degrees (lat-scaled) from p to segment a-b
    k = math.cos(math.radians(a[1]))
    ax, ay, bx, by, px, py = a[0] * k, a[1], b[0] * k, b[1], p[0] * k, p[1]
    dx, dy = bx - ax, by - ay
    if dx == 0 and dy == 0:
        return math.hypot(px - ax, py - ay)
    t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
    return math.hypot(px - (ax + t * dx), py - (ay + t * dy))


def simplify(points, eps):
    """Douglas-Peucker simplification (iterative) of a list of (lon, lat)."""
    if len(points) < 3:
        return points
    keep = [False] * len(points)
    keep[0] = keep[-1] = True
    stack = [(0, len(points) - 1)]
    while stack:
        i, j = stack.pop()
        best, idx = 0.0, None
        for m in range(i + 1, j):
            d = _perp(points[m], points[i], points[j])
            if d > best:
                best, idx = d, m
        if idx is not None and best > eps:
            keep[idx] = True
            stack.append((i, idx))
            stack.append((idx, j))
    return [p for p, k in zip(points, keep) if k]


def _round(coords, nd=5):
    if isinstance(coords[0], (int, float)):
        return [round(coords[0], nd), round(coords[1], nd)]
    return [_round(c, nd) for c in coords]


def simplify_geometry(geom, eps=0.00008):
    t = geom["type"]
    c = geom["coordinates"]
    if t == "LineString":
        c = simplify(c, eps)
    elif t == "MultiLineString":
        c = [simplify(part, eps) for part in c]
    elif t == "Polygon":
        c = [r for r in (simplify(ring, eps) for ring in c) if len(r) >= 4]
    elif t == "MultiPolygon":
        c = [[r for r in (simplify(ring, eps) for ring in poly) if len(r) >= 4] for poly in c]
        c = [poly for poly in c if poly]
    return {"type": t, "coordinates": _round(c)}


def bbox_of(geoms):
    xs, ys = [], []

    def walk(c):
        if isinstance(c[0], (int, float)):
            xs.append(c[0]); ys.append(c[1])
        else:
            for x in c:
                walk(x)

    for g in geoms:
        if g:
            walk(g["coordinates"])
    return [round(min(xs), 5), round(min(ys), 5), round(max(xs), 5), round(max(ys), 5)] if xs else None


# --------------------------------------------------------------- inputs -----

def fetch_inputs(inputs: Path, log=print):
    """Download every layer this dashboard reads from the Council's ArcGIS REST
    services into `inputs/` as GeoJSON (paged, WGS84)."""
    inputs.mkdir(parents=True, exist_ok=True)
    ua = {"User-Agent": "MetCouncil-DisplacementDashboard-update/1.0"}
    for stem, (svc, layer, extra) in LAYERS.items():
        feats, offset = [], 0
        while True:
            where = METRO_COUNTY_WHERE if svc == "census" else "1%3D1"
            order = "" if svc == "census" else "&orderByFields=OBJECTID"
            url = (f"{SERVICES[svc]}/{layer}/query?where={where}&outFields=*&outSR=4326&f=geojson"
                   f"&resultOffset={offset}&resultRecordCount=2000{order}{extra}")
            req = urllib.request.Request(url, headers=ua)
            with urllib.request.urlopen(req, timeout=180) as r:
                page = json.load(r)
            got = page.get("features", [])
            feats.extend(got)
            if len(got) < 2000:
                break
            offset += 2000
            time.sleep(0.5)
        (inputs / f"{stem}.geojson").write_text(json.dumps({"type": "FeatureCollection", "features": feats}))
        log(f"  fetched {stem}: {len(feats)} features")


def load(inputs: Path, stem: str):
    path = inputs / f"{stem}.geojson"
    if not path.exists():
        raise SystemExit(f"Missing input {path}. Export it from ArcGIS as GeoJSON, or run with --fetch.")
    feats = json.loads(path.read_text())["features"]
    if FIELD_RENAMES:
        for f in feats:
            props = f.get("properties") or {}
            for new, old in FIELD_RENAMES.items():
                if new in props and old not in props:
                    props[old] = props.pop(new)
    need = FIELDS_READ.get(stem)
    if need and feats:
        have = set()
        for f in feats:
            have.update((f.get("properties") or {}).keys())
        missing = [k for k in need if k not in have]
        if missing:
            raise SystemExit(f"{path.name} has no {' or '.join(missing)} field, so the update stopped and the site was not changed. "
                             f"If the Council renamed it, add the new name to FIELD_RENAMES at the top of dashboard_data.py "
                             f'(for example {{"NEW_NAME": "{missing[0]}"}}) and run the update again.')
    return feats


# ------------------------------------------------------------- stations -----

ABBREV = [
    (r"\bWhse Dist\b", "Warehouse District"), (r"\bGov't\b", "Government"), (r"\bStn\b", "Station"),
    (r"\bCntr\b", "Center"), (r"\bMOA\b", "Mall of America"), (r"\bP&R\b", "Park & Ride"),
]


def clean_name(raw: str) -> str:
    s = (raw or "").strip()
    for pat, rep in ABBREV:
        s = re.sub(pat, rep, s)
    s = re.sub(r"\s+Station$", "", s)
    s = re.sub(r"\s+", " ", s).strip()
    return s


def slugify(s: str) -> str:
    s = s.lower().replace("&", " and ").replace("/", " ").replace("'", "")
    s = re.sub(r"[^a-z0-9]+", "-", s).strip("-")
    return s or "station"


def _key(name: str) -> str:
    n = clean_name(name).lower()
    n = re.sub(r"[^a-z0-9]+", " ", n).strip()
    n = n.replace("theatre", "theater")
    return n


def order_stops(points):
    """Ride order for a set of station points: the longest path through their
    minimum spanning tree, with every other point inserted where it projects
    onto that path. Returns indexes in order."""
    n = len(points)
    if n <= 2:
        return list(range(n))
    # Prim's MST
    in_tree = [False] * n
    dist = [math.inf] * n
    parent = [-1] * n
    dist[0] = 0
    adj = defaultdict(list)
    for _ in range(n):
        u = min((i for i in range(n) if not in_tree[i]), key=lambda i: dist[i])
        in_tree[u] = True
        if parent[u] >= 0:
            w = miles(points[u], points[parent[u]])
            adj[u].append((parent[u], w)); adj[parent[u]].append((u, w))
        for v in range(n):
            if not in_tree[v]:
                d = miles(points[u], points[v])
                if d < dist[v]:
                    dist[v], parent[v] = d, u

    def farthest(src):
        best = {src: 0.0}
        prev = {src: None}
        stack = [src]
        while stack:
            u = stack.pop()
            for v, w in adj[u]:
                if v not in best:
                    best[v] = best[u] + w
                    prev[v] = u
                    stack.append(v)
        end = max(best, key=best.get)
        return end, prev

    a, _ = farthest(0)
    b, prev = farthest(a)
    path = []
    cur = b
    while cur is not None:
        path.append(cur)
        cur = prev[cur]
    path.reverse()
    on_path = set(path)
    # cumulative distance along the path
    cum = [0.0]
    for i in range(1, len(path)):
        cum.append(cum[-1] + miles(points[path[i - 1]], points[path[i]]))
    pos = {p: cum[i] for i, p in enumerate(path)}
    for i in range(n):
        if i in on_path:
            continue
        best_d, best_pos = math.inf, 0.0
        for j in range(1, len(path)):
            p0, p1 = points[path[j - 1]], points[path[j]]
            seg = miles(p0, p1) or 1e-9
            d0, d1 = miles(points[i], p0), miles(points[i], p1)
            t = max(0.0, min(1.0, (d0 * d0 - d1 * d1 + seg * seg) / (2 * seg * seg)))
            d = _perp(points[i], p0, p1)
            if d < best_d:
                best_d, best_pos = d, cum[j - 1] + t * seg
        pos[i] = best_pos
    return sorted(range(n), key=lambda i: pos[i])


def build_stations(line, dtat_stations, official):
    """Unique stations for one line, named from the Council's transitway layer
    where a station sits within 0.2 miles of an official one, in ride order."""
    raw = [f for f in dtat_stations if f["properties"].get("RT_NAME") == line["dtat"] and f.get("geometry")]
    groups = {}
    for f in raw:
        p = f["properties"]
        k = _key(p.get("STATION") or "")
        g = groups.setdefault(k, {"names": [], "pts": [], "city": p.get("CITY")})
        g["names"].append(p.get("STATION"))
        g["pts"].append(f["geometry"]["coordinates"][:2])
    offs = [f for f in official if f["properties"].get("NameTransitway") == line["transitway"] and f.get("geometry")]
    stops = []
    for k, g in groups.items():
        lon = sum(p[0] for p in g["pts"]) / len(g["pts"])
        lat = sum(p[1] for p in g["pts"]) / len(g["pts"])
        name = clean_name(g["names"][0])
        status, opened = None, None
        best = None
        for o in offs:
            d = miles((lon, lat), o["geometry"]["coordinates"][:2])
            if d < 0.2 and (best is None or d < best[0]):
                best = (d, o)
        if best:
            op = best[1]["properties"]
            official_name = (op.get("MapLabel") or op.get("NameStation") or "").strip()
            if official_name and line["mode"] in ("lrt", "brt"):
                name = official_name
            status = op.get("StationStatus")
            cd = str(op.get("CompletionDate") or "")
            opened = int(cd) if cd.isdigit() else None
        stops.append({"name": name, "lon": round(lon, 5), "lat": round(lat, 5), "city": city_name(g["city"]),
                      "status": status, "opened": opened})
    order = order_stops([(s["lon"], s["lat"]) for s in stops])
    stops = [stops[i] for i in order]
    # direction: west to east when the line runs more east-west, else north to south
    if len(stops) > 1:
        dx = abs(stops[-1]["lon"] - stops[0]["lon"]) * math.cos(math.radians(stops[0]["lat"]))
        dy = abs(stops[-1]["lat"] - stops[0]["lat"])
        flip = (stops[0]["lon"] > stops[-1]["lon"]) if dx >= dy else (stops[0]["lat"] < stops[-1]["lat"])
        if flip:
            stops.reverse()
    seen = set()
    for s in stops:
        base = slugify(s["name"])
        slug, n = base, 2
        while slug in seen:
            slug, n = f"{base}-{n}", n + 1
        seen.add(slug)
        s["id"] = slug
    return stops


class Area:
    """Point-in-polygon for a GeoJSON Polygon or MultiPolygon (even-odd rule,
    holes respected), with a bounding-box test first."""

    def __init__(self, geometry):
        polys = geometry["coordinates"] if geometry["type"] == "MultiPolygon" else [geometry["coordinates"]]
        self.polys = [[ring for ring in poly] for poly in polys]
        xs = [pt[0] for poly in self.polys for pt in poly[0]]
        ys = [pt[1] for poly in self.polys for pt in poly[0]]
        self.box = (min(xs), min(ys), max(xs), max(ys))

    @staticmethod
    def _in_ring(x, y, ring):
        inside = False
        j = len(ring) - 1
        for i in range(len(ring)):
            xi, yi = ring[i][0], ring[i][1]
            xj, yj = ring[j][0], ring[j][1]
            if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / ((yj - yi) or 1e-15) + xi:
                inside = not inside
            j = i
        return inside

    def contains(self, x, y):
        x0, y0, x1, y1 = self.box
        if x < x0 or x > x1 or y < y0 or y > y1:
            return False
        for poly in self.polys:
            if self._in_ring(x, y, poly[0]) and not any(self._in_ring(x, y, hole) for hole in poly[1:]):
                return True
        return False


# --------------------------------------------------------------- build ------

def build_model(inputs: Path):
    dtat_stations = load(inputs, "dtat-stations")
    alignments = {f["properties"]["RT_NAME"]: f for f in load(inputs, "dtat-alignments")}
    areas = {f["properties"]["AREA_NAME"]: f for f in load(inputs, "dtat-areas")}
    hfn = load(inputs, "high-frequency-network")
    permits_raw = load(inputs, "dtat-permits-residential")
    official = load(inputs, "transitway-stations-existing") + load(inputs, "transitway-stations-planned")
    counties = load(inputs, "counties")

    years = list(range(FIRST_YEAR, LAST_YEAR + 1))
    area_index = {name: Area(f["geometry"]) for name, f in areas.items() if f.get("geometry")}
    permits = []
    region_by_year = defaultdict(float)
    for f in permits_raw:
        p = f["properties"]
        try:
            y = int(p.get("YEAR"))
        except (TypeError, ValueError):
            continue
        units = float(p.get("UNITS") or 0)
        region_by_year[y] += units
        if not f.get("geometry"):
            continue
        lon, lat = f["geometry"]["coordinates"][:2]
        # A permit belongs to a transitway when it sits inside that line's half-mile
        # corridor area, in every year. The layer's own line flags start only in the
        # year Development Trends Along Transit began tracking each line, which would
        # read the years before as zero. The High Frequency Network keeps the layer's
        # flag: its area in the layer also covers the light rail and BRT corridors.
        flags = [l["id"] for l in LINES if l["dtat"] in area_index and area_index[l["dtat"]].contains(lon, lat)]
        if p.get(HF_BUS["flag"]) == "Yes":
            flags.append(HF_BUS["id"])
        if not flags:
            continue
        permits.append({
            "lon": round(lon, 5), "lat": round(lat, 5), "year": y, "units": int(round(units)),
            "tenure": TENURE.get(p.get("TENURE"), "unknown"), "type": HOUSING_TYPE.get(p.get("HOUSING_TYPE_DESC"), "other"),
            "lines": flags, "city": city_name(p.get("CTU_NAME")),
            "name": (p.get("NAME") or "").strip(),
        })

    lines = []
    for spec in LINES:
        line = dict(spec)
        line["modeLabel"] = MODES[line["mode"]]
        al = alignments.get(spec["dtat"])
        ap = al["properties"] if al else {}
        line["status"] = "planned" if (ap.get("RT_STATUS") == "Planned") else "in-service"
        line["lengthMi"] = round(float(ap.get("LENGTH_MI") or 0), 1) or None
        line["geometry"] = simplify_geometry(al["geometry"]) if al else None
        ar = areas.get(spec["dtat"])
        line["area"] = simplify_geometry(ar["geometry"], 0.00015) if ar else None
        line["areaAcres"] = round(float(ar["properties"].get("AREA_ACRES") or 0)) if ar else None
        stops = build_stations(spec, dtat_stations, official)
        opened = [s["opened"] for s in stops if s["opened"] and (s["status"] in (None, "Existing"))]
        line["opened"] = max(set(opened), key=opened.count) if opened else None
        if line["opened"] and line["opened"] <= 2025:
            line["status"] = "in-service"
        planned_phase = [s["status"] for s in stops if s["status"] and s["status"] != "Existing"]
        line["phase"] = max(set(planned_phase), key=planned_phase.count) if (planned_phase and line["status"] == "planned") else None
        if line["status"] == "planned":
            line["opened"] = None
        line["stations"] = stops
        line["cities"] = []
        for s_ in stops:  # in riding order
            if s_["city"] and s_["city"] not in line["cities"]:
                line["cities"].append(s_["city"])
        lines.append(line)

    hf = dict(HF_BUS)
    hf["modeLabel"] = MODES["hfbus"]
    hf["status"] = "in-service"
    hf["opened"] = None
    hf["phase"] = None
    hf["stations"] = []
    hf["routes"] = sorted({int(f["properties"]["LINE_ID"]) for f in hfn if int(f["properties"]["LINE_ID"]) < 900})
    hf["geometry"] = {"type": "MultiLineString", "coordinates": []}
    for f in hfn:
        if int(f["properties"]["LINE_ID"]) >= 900 or int(f["properties"].get("DIRECTION") or 0) != 0:
            continue
        g = simplify_geometry(f["geometry"])
        hf["geometry"]["coordinates"].extend(g["coordinates"] if g["type"] == "MultiLineString" else [g["coordinates"]])
    ar = areas.get(HF_BUS["dtat"])
    hf["area"] = None  # the all-routes area overlaps every line; drawn only as the network
    hf["areaAcres"] = round(float(ar["properties"].get("AREA_ACRES") or 0)) if ar else None
    hf["lengthMi"] = None
    hf["cities"] = sorted({p["city"] for p in permits if hf["id"] in p["lines"] and p["city"]})
    lines.append(hf)

    by_id = {l["id"]: l for l in lines}
    # aggregate per line and per station
    for line in lines:
        line["byYear"] = {y: 0 for y in years}
        line["tenure"] = defaultdict(int)
        line["types"] = defaultdict(int)
        for s in line["stations"]:
            s["byYear"] = {y: 0 for y in years}
            s["tenure"] = defaultdict(int)
            s["types"] = defaultdict(int)
            s["permits"] = 0
    for p in permits:
        for lid in p["lines"]:
            line = by_id[lid]
            line["byYear"][p["year"]] += p["units"]
            line["tenure"][p["tenure"]] += p["units"]
            line["types"][p["type"]] += p["units"]
            if line["stations"]:
                st = min(line["stations"], key=lambda s: miles((p["lon"], p["lat"]), (s["lon"], s["lat"])))
                st["byYear"][p["year"]] += p["units"]
                st["tenure"][p["tenure"]] += p["units"]
                st["types"][p["type"]] += p["units"]
                st["permits"] += 1
                p.setdefault("stations", {})[lid] = st["id"]
    for line in lines:
        line["total"] = sum(line["byYear"].values())
        o = line.get("opened")
        if o and FIRST_YEAR < o <= LAST_YEAR:
            before = [line["byYear"][y] for y in years if y < o]
            after = [line["byYear"][y] for y in years if y >= o]
            line["beforeAfter"] = {"split": o, "beforeYears": len(before), "afterYears": len(after),
                                   "beforeAvg": round(sum(before) / len(before)), "afterAvg": round(sum(after) / len(after)),
                                   "before": sum(before), "after": sum(after)}
        else:
            line["beforeAfter"] = None
        for s in line["stations"]:
            s["total"] = sum(s["byYear"].values())
            s["tenure"] = dict(s["tenure"]); s["types"] = dict(s["types"])
        line["tenure"] = dict(line["tenure"]); line["types"] = dict(line["types"])

    region = {
        "byYear": {y: round(region_by_year[y]) for y in years},
        "total": round(sum(region_by_year[y] for y in years)),
        "corridorUnits": sum(p["units"] for p in permits),
        "corridorPermits": len(permits),
    }
    county_geoms = [{"name": f["properties"].get("BASENAME") or f["properties"].get("NAME") or "", "geometry": simplify_geometry(f["geometry"], 0.0004)} for f in counties if f.get("geometry")]
    cities = []
    for f in load(inputs, "cities-townships"):
        if f.get("geometry"):
            cities.append({"name": city_name(f["properties"].get("CTU_NAME")),
                           "type": f["properties"].get("CTU_TYPE") or "", "geometry": simplify_geometry(f["geometry"], 0.0004)})
    return {"years": years, "lines": lines, "permits": permits, "region": region, "counties": county_geoms, "cities": cities,
            "bbox": bbox_of([l["geometry"] for l in lines if l["geometry"]])}
