#!/usr/bin/env python3
"""Displacement Dashboard: the annual update.

Purpose: rebuild the whole dashboard (data files, every line and station page,
the story, the one-pager data, downloads and the search index) from the
Metropolitan Council's own layers in one run.

    python3 update_dashboard.py --fetch          # pull the Council's ArcGIS layers, then build
    python3 update_dashboard.py                  # build from the files already in inputs/
    python3 update_dashboard.py --site ../site   # write somewhere else

Inputs: GeoJSON in inputs/ (exported from ArcGIS Pro or fetched from
arcgis.metc.state.mn.us), and, once the Analysis team delivers, its tables in
inputs/analysis/ (see schema/analysis-v1.json). Output: a static site any web
server or Azure storage can host. Standard library only.

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

import argparse
import csv
import datetime
import html
import io
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

import dashboard_data as D  # noqa: E402
import dashboard_html as H  # noqa: E402

E = html.escape
n = H.n

REPO_SITE = HERE.parent.parent.parent / "public" / "metropolitancouncil"
# The address the embed code points at. At handoff it becomes the Council's own
# domain (Addendum 1, R13: every view can be linked or embedded).
PUBLIC_ORIGIN = "https://www.stoa.works"
DTAT_REPORT = "docs/development-trends-along-transit-2025.pdf"
HPP_REPORT = "docs/imagine-2050-housing-policy-plan.pdf"

# Figures quoted from the Development Trends Along Transit 2025 report (Metro
# Transit TOD Office), each with the report page it comes from. Update these
# with each year's report.
DTAT_FACTS = {
    "valueBillions": "21.7",
    "shareOfRegion": "39%",
    "landShare": "4%",
    "plannedUnits": "44,400",
    "plannedValueBillions": "11.3",
    "page": 1,
    # Table 1, homes permitted near high frequency transit 2009 to 2024, as the
    # report counts them (each line from the year it began tracking that line).
    "corridorUnits": "68,970",
    "corridorShare": "42%",
}
# The report's printed page N is page N + 3 of its PDF (cover and contents come first).
DTAT_PDF_OFFSET = 3
# Per-line figures from the same report (pages 33 to 58): permitted development
# value and affordable housing production 2014 to 2024 within a half mile.
DTAT_LINE_FACTS = {
    "blue-line": {"page": 34, "value": "$8,169,440,000", "aff30": (770, "4%"), "aff60": (2300, "12%")},
    "green-line": {"page": 36, "value": "$9,905,470,000", "aff30": (890, "3%"), "aff60": (3160, "12%")},
    "green-line-extension": {"page": 40, "value": "$3,274,200,000", "aff30": (240, "2%"), "aff60": (1890, "19%")},
    "orange-line": {"page": 42, "value": "$4,993,300,000", "aff30": (230, "2%"), "aff60": (1470, "11%")},
    "gold-line": {"page": 44, "value": "$968,270,000", "aff30": (296, "11%"), "aff60": (1875, "69%")},
    "a-line": {"page": 46, "value": "$1,191,170,000", "aff30": (230, "6%"), "aff60": (985, "25%")},
    "b-line": {"page": 48, "value": "$1,882,500,000", "aff30": (200, "6%"), "aff60": (890, "29%")},
    "c-line": {"page": 50, "value": "$4,636,470,000", "aff30": (600, "6%"), "aff60": (1880, "18%")},
    "d-line": {"page": 52, "value": "$4,847,620,000", "aff30": (485, "5%"), "aff60": (1765, "18%")},
    "e-line": {"page": 54, "value": "$1,728,760,000", "aff30": (40, "1%"), "aff60": (360, "5%")},
}

ANALYSIS_EXAMPLE = {
    "source": "RFP Appendix C: University of Utah, Department of City and Metropolitan Planning, for the Utah Transit Authority",
    "scope": "20 TOD station areas on Utah's light rail system",
    "years": "2021 to 2022",
    "out": {"households": 899, "shares": [["European (White)", 68.7], ["Hispanic", 14.3], ["Other or unknown", 16.9]]},
    "in": {"households": 555, "shares": [["European (White)", 70.5], ["Hispanic", 12.1], ["Other or unknown", 17.5]]},
    "income": {
        "periods": ["2015 to 2016", "2016 to 2017", "2017 to 2018", "2018 to 2019", "2019 to 2020", "2020 to 2021", "2021 to 2022"],
        "movingOutBefore": [27, 38, 38, 61, 47, 33, 44],
        "movingOutAfter": [76, 73, 75, 74, 81, 77, 65],
        "movingInBefore": [55, 69, 67, 68, 57, 68, 56],
        "movingInAfter": [46, 47, 60, 54, 37, 50, 33],
    },
}


# ------------------------------------------------------------------ shell ---

def chrome_blocks(site: Path):
    """The shared header and footer, taken from templates/ when frozen there,
    otherwise from the current home page, otherwise empty markers."""
    hdr = HERE / "templates" / "chrome-header.html"
    ftr = HERE / "templates" / "chrome-footer.html"
    if hdr.exists() and ftr.exists():
        return hdr.read_text(), ftr.read_text()
    home = site / "index.html"
    if home.exists():
        s = home.read_text()
        h = re.search(r"<!-- stoa:chrome:header -->[\s\S]*?<!-- /stoa:chrome:header -->", s)
        f = re.search(r"<!-- stoa:chrome:footer -->[\s\S]*?<!-- /stoa:chrome:footer -->", s)
        if h and f:
            return h.group(0), f.group(0)
    return "<!-- stoa:chrome:header --><!-- /stoa:chrome:header -->", "<!-- stoa:chrome:footer --><!-- /stoa:chrome:footer -->"


CRUMB_TRAIL = {}  # url -> (label, parent url), filled in main() for lines and stations


def localize_header(header, base, url, crumb):
    """Mark this page's nav door current and draw its breadcrumb, so the
    shared header copied from the home page reads true on every page."""
    header = header.replace(' aria-current="page"', "")
    header = re.sub(r"\n?\s*<nav class=\"breadcrumb\"[\s\S]*?</nav>", "", header)
    doors = re.findall(r'<a class="nav-link"[^>]*href="([^"]+)"', header)
    best = None
    for href in doors:
        if href == url or (href != base and url.startswith(href)):
            if best is None or len(href) > len(best):
                best = href
    if best:
        header = header.replace(f'<a class="nav-link" data-title-style="title" href="{best}">', f'<a class="nav-link" data-title-style="title" href="{best}" aria-current="page">', 1)
    if crumb:
        trail = []
        parent = crumb[1]
        seen = set()
        while parent and parent not in seen and parent != base:
            seen.add(parent)
            label, nxt = CRUMB_TRAIL.get(parent, (None, None))
            if label is None:
                door = re.search(rf'<a class="nav-link"[^>]*href="{re.escape(parent)}"[^>]*>([^<]+)</a>', header)
                label, nxt = (door.group(1) if door else parent), base
            trail.insert(0, (parent, label))
            parent = nxt
        items = f'<li><a data-title-style="title" href="{base}">Region</a></li>' + "".join(f'<li><a data-title-style="title" href="{h}">{E(l)}</a></li>' for h, l in trail)
        bc = (f'\n  <nav class="breadcrumb" data-stoa-c="breadcrumb" aria-label="Breadcrumb"><ol>{items}'
              f'<li><span{verbatim_name(crumb[0]) or ' data-title-style="title"'} aria-current="page">{E(crumb[0])}</span></li></ol></nav>')
        header = header.replace("  </header>", "  </header>" + bc, 1)
    return header


def page(base, title, description, main, *, chrome, body_class="", crumb=None, scripts=(), head_extra="", current=None, rel="", title_attrs="", embed=False):
    header, footer = chrome
    url = base + (rel[:-len("index.html")] if rel.endswith("index.html") else rel)
    # An embeddable view opened with ?embed drops the site header, breadcrumb and
    # footer for a partner page's frame, and keeps one link back to the full page.
    embed_head = '\n<script>if (/[?&]embed(=|&|$)/.test(location.search)) document.documentElement.classList.add("is-embed");</script>' if embed else ""
    embed_bar = f'\n<p class="embed-return"><a href="{url}">Open the full Displacement Dashboard</a></p>' if embed else ""
    header = localize_header(header, base, url, crumb)
    crumb_meta = ""
    if crumb:
        crumb_meta = f'\n<meta name="stoa-crumb" content="{H.attr(crumb[0])}">\n<meta name="stoa-crumb-parent" content="{H.attr(crumb[1])}">'
    script_tags = "".join(f'\n<script src="{base}assets/{s}" defer></script>' if not s.endswith(".mjs") else f'\n<script type="module" src="{base}assets/{s}"></script>' for s in scripts)
    return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title{title_attrs}>{E(title)}</title>
<meta name="description" content="{H.attr(description)}">
<meta name="robots" content="noindex, nofollow">{crumb_meta}
<meta name="theme-color" content="#002b5c">
<link rel="icon" href="{base}assets/img/favicon-32.png" sizes="32x32" type="image/png">
<link rel="icon" href="{base}assets/img/favicon-64.png" sizes="64x64" type="image/png">
<link rel="apple-touch-icon" href="{base}assets/img/apple-touch-icon.png">
<link rel="preload" href="{base}assets/fonts/asap-var.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="{base}assets/fonts/asap-condensed-700.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="{base}assets/theme.css">{head_extra}{embed_head}
</head>
<body class="{body_class}" data-base="{base}">
{header}
<main id="main" tabindex="-1">{embed_bar}
{main}
</main>
{footer}
<script src="{base}assets/nav.js" defer></script>
<script src="{base}assets/search-core.js" defer></script>
<script src="{base}data/search-light.js" defer></script>
<script src="{base}assets/omnibox.js" defer></script>
<script src="{base}assets/ui.js" defer></script>{script_tags}
</body>
</html>
"""


def write(site: Path, rel: str, text: str):
    out = site / rel
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(text)


def embed_block(base, path, view_title, key):
    """The one line of code a city, partner or Council page uses to show this view."""
    code = (f'<iframe src="{PUBLIC_ORIGIN}{base}{path}?embed" title="{H.attr(view_title)}" '
            'width="100%" height="900" style="border:0" loading="lazy"></iframe>')
    tid = f"embed-code-{key}"
    return f"""<section class="embed-view" aria-labelledby="embed-{key}">
  <h2 id="embed-{key}"><span class="station-stop" aria-hidden="true"></span>Embed this view</h2>
  <p data-source-copy="embed-intro">A city, partner or Council page can show this view with the one line of code below. The embedded view keeps the map's keyboard path and its tables, and its links open the full dashboard in a new tab.</p>
  <label class="embed-label" for="{tid}">Embed code</label>
  <textarea id="{tid}" class="embed-code" rows="3" readonly spellcheck="false">{E(code)}</textarea>
  <div class="embed-actions"><button type="button" class="button" data-copy-target="{tid}">Copy the code</button><a class="text-link" href="{base}{path}?embed">Preview the embedded view</a><span class="embed-status" role="status" aria-live="polite" data-copy-status></span></div>
</section>"""


# --------------------------------------------------------------- figures ----

def source_line(text):
    return f'<p class="source-line">{text}</p>'


DTAT_SOURCE = "Metropolitan Council, Development Trends Along Transit permit data (Building Permit Survey), 2009 to 2024."


def line_facts(line):
    bits = [line["modeLabel"], H.status_text(line)]
    if line.get("lengthMi"):
        bits.append(f'{line["lengthMi"]:g} miles')
    if line["stations"]:
        bits.append(f'{len(line["stations"])} stations')
    return "".join(f"<li>{E(b)}</li>" for b in bits)


def near(line):
    """The reach that counts a permit for a line in Development Trends Along
    Transit: a half mile of a METRO station, a quarter mile of a High
    Frequency local route."""
    return "within a quarter mile" if line["id"] == "high-frequency-bus" else "within a half mile"


def before_after(line, region, years):
    ba = line.get("beforeAfter")
    if not ba:
        return ""
    split = ba["split"]
    r_before = [region["byYear"][y] for y in years if y < split]
    r_after = [region["byYear"][y] for y in years if y >= split]
    rb, ra = sum(r_before) / len(r_before), sum(r_after) / len(r_after)
    return (
        f'<div class="before-after" style="--line:{line["color"]};--line-mark:{H.chart_color(line["color"])}">'
        f'<h2 class="ba-title">Before and since service began in {split}</h2>'
        f'<dl class="ba-figures">'
        f'<div><dt>Per year before {split}</dt><dd>{n(ba["beforeAvg"])}</dd></div>'
        f'<div><dt>Per year since {split}</dt><dd>{n(ba["afterAvg"])}</dd></div>'
        f'</dl>'
        f'<p class="ba-note" data-source-copy="ba-note">Average multifamily homes permitted per year {near(line)}. Across the whole region, permits went from {n(rb)} a year before {split} to {n(ra)} a year since, '
        f'so the Displacement Analysis compares each corridor with control corridors to tell the two apart.</p></div>'
    )


def money_short(text):
    """'$9,905,470,000' -> '$9.9 billion'; '$968,270,000' -> '$968 million'."""
    v = int("".join(ch for ch in text if ch.isdigit()))
    if v >= 1_000_000_000:
        return "$" + f"{v / 1e9:.1f}".rstrip("0").rstrip(".") + " billion"
    return f"${round(v / 1e6):,} million"


def join_and(items):
    items = [i for i in items if i]
    if len(items) <= 1:
        return "".join(items)
    if len(items) == 2:
        return f"{items[0]} and {items[1]}"
    return ", ".join(items[:-1]) + ", and " + items[-1]


def dtat_line_block(line, base):
    f = DTAT_LINE_FACTS.get(line["id"])
    if not f:
        return ""
    return (
        f'<section class="report-figures" aria-labelledby="report-{line["id"]}">'
        f'<h2 id="report-{line["id"]}"><span class="station-stop" aria-hidden="true"></span>From the 2025 Development Trends Along Transit report</h2>'
        f'<dl class="report-grid">'
        f'<div><dt>Development value permitted {near(line)}, 2009 to 2024</dt><dd>{money_short(f["value"])}</dd></div>'
        f'<div><dt>Homes affordable up to 30% of area median income, 2014 to 2024</dt><dd>{n(f["aff30"][0])}</dd><dd class="dd-note">{f["aff30"][1]} of all new homes</dd></div>'
        f'<div><dt>Homes affordable up to 60% of area median income, 2014 to 2024</dt><dd>{n(f["aff60"][0])}</dd><dd class="dd-note">{f["aff60"][1]} of all new homes</dd></div>'
        f'</dl>'
        f'<p class="source-line">Source: <a href="{base}{DTAT_REPORT}#page={f["page"] + DTAT_PDF_OFFSET}">Development Trends Along Transit, 2025 Report</a>, page {f["page"]}.</p>'
        f'</section>'
    )


# ------------------------------------------------------------------ pages ---

def home_main(model, base):
    lines = model["lines"]
    region = model["region"]
    share = region["corridorUnits"] / region["total"] if region["total"] else 0
    badges = "".join(H.line_badge(l, base) for l in lines)
    ranked = H.ranked_lines(lines, base)
    return f"""
<section class="stage" aria-labelledby="stage-title" data-dashboard>
  <div class="stage-intro">
    <h1 id="stage-title">Change along transit, one line at a time</h1>
    <p class="lede" data-source-copy="home-lede">Pick a line to see the homes permitted within a half mile of each station since 2009. Household movement from the Displacement Analysis joins each station when the Analysis team delivers it.</p>
  </div>
  <details class="filters-wrap" data-filters-wrap open>
  <summary class="filters-summary">Filter the map</summary>
  <form class="filters" data-filters aria-label="Filter the map" action="{base}lines/" method="get">
    <fieldset class="filter-group">
      <legend>Transit mode</legend>
      <label class="chip"><input type="checkbox" name="mode" value="lrt" checked><span>Light rail</span></label>
      <label class="chip"><input type="checkbox" name="mode" value="brt" checked><span>Bus rapid transit</span></label>
      <label class="chip"><input type="checkbox" name="mode" value="abrt" checked><span>Arterial BRT</span></label>
      <label class="chip"><input type="checkbox" name="mode" value="hfbus" checked><span>High Frequency bus</span></label>
    </fieldset>
    <fieldset class="filter-group years-filter">
      <legend>Years</legend>
      <label class="year-input"><span class="visually-hidden">From</span><select name="from" data-year-from>{"".join(f'<option value="{y}"{" selected" if y == model["years"][0] else ""}>{y}</option>' for y in model["years"])}</select></label>
      <span class="year-to" aria-hidden="true">to</span>
      <label class="year-input"><span class="visually-hidden">To</span><select name="to" data-year-to>{"".join(f'<option value="{y}"{" selected" if y == model["years"][-1] else ""}>{y}</option>' for y in model["years"])}</select></label>
    </fieldset>
    <fieldset class="filter-group">
      <legend>Show</legend>
      <label class="chip"><input type="checkbox" name="status" value="in-service" checked><span>In service</span></label>
      <label class="chip"><input type="checkbox" name="status" value="planned" checked><span>Planned</span></label>
    </fieldset>
    <fieldset class="filter-group basemap-filter">
      <legend>Basemap</legend>
      <label class="chip chip-radio"><input type="radio" name="basemap" value="streets" checked><span>Streets</span></label>
      <label class="chip chip-radio"><input type="radio" name="basemap" value="plain"><span>Plain</span></label>
    </fieldset>
    <noscript><button class="button" type="submit">Browse all lines</button></noscript>
  </form>
  </details>
  <script>(function () {{ var d = document.querySelector("[data-filters-wrap]"); if (!d || !window.matchMedia) return; var mq = window.matchMedia("(max-width: 767px)"); function sync() {{ d.open = !mq.matches; }} sync(); if (mq.addEventListener) mq.addEventListener("change", sync); }})();</script>
  <div class="stage-grid">
    <div class="map-frame">
      <div id="map" class="map" role="region" aria-label="Map of METRO lines, High Frequency bus routes and the homes permitted near them" data-visual-id="region-map" data-visual-kind="map"></div>
      <noscript><p class="map-noscript">The map needs JavaScript. Every line and station is listed on <a href="{base}lines/">All lines</a>.</p></noscript>
      <div class="map-legend" aria-hidden="true" data-map-legend>
        <span class="lg lg-area">Half mile around stations</span>
        <span class="lg lg-dot">Permitted homes, sized by count</span>
        <span class="lg lg-planned">Planned line</span>
      </div>
    </div>
    <aside class="panel" data-panel aria-live="off" aria-labelledby="panel-title">
      <div class="panel-region" data-panel-region>
        <p class="kicker">All lines and High Frequency bus</p>
        <h2 class="panel-title" id="panel-title"><span class="hero-figure" data-region-total>{n(region["corridorUnits"])}</span><span class="hero-label">multifamily homes permitted near high-frequency transit, {model["years"][0]} to {model["years"][-1]}</span></h2>
        <p class="panel-sub" data-region-share>That is {round(share * 100)} percent of the region's multifamily homes in those years, with each line counted before and after it opened.</p>
        {ranked}
        {source_line("Source: " + DTAT_SOURCE)}
      </div>
      <div class="panel-line" data-panel-line hidden></div>
    </aside>
  </div>
  <div class="strip-dock" data-strip-dock>
    <div class="strip-prompt" data-strip-prompt>
      <h2 class="strip-title"><span class="station-stop" aria-hidden="true"></span>Choose a line to ride its stations</h2>
      <div class="badge-row">{badges}</div>
    </div>
  </div>
</section>

<section class="band facts-band" aria-labelledby="facts-title">
  <div class="band-inner">
    <h2 id="facts-title"><span class="station-stop" aria-hidden="true"></span>The region is building along its transit</h2>
    <ul class="fact-row" role="list">
      <li class="fact"><span class="fact-figure">${DTAT_FACTS["valueBillions"]} billion</span><span class="fact-label" data-verbatim data-source-copy="dtat-2025-exec-summary">in development has been permitted along high frequency transit between 2009 and 2024</span></li>
      <li class="fact"><span class="fact-figure">{DTAT_FACTS["shareOfRegion"]}</span><span class="fact-label" data-verbatim data-source-copy="dtat-2025-exec-summary">of the development that has been permitted for the region as a whole, on just {DTAT_FACTS["landShare"]} of the region's land area</span></li>
      <li class="fact"><span class="fact-figure">{DTAT_FACTS["plannedUnits"]}</span><span class="fact-label" data-verbatim data-source-copy="dtat-2025-exec-summary">additional multifamily units along high frequency transit, in the region's planned developments</span></li>
    </ul>
    <p class="source-line">Source: <a href="{base}{DTAT_REPORT}">Development Trends Along Transit, 2025 Report</a>, Metro Transit TOD Office.</p>
  </div>
</section>

<section class="band voice-band" aria-labelledby="voice-title">
  <div class="band-inner voice-grid">
    <div class="portal-line" aria-hidden="false">
      <figure class="portal portal-lg" data-photo-story-id="home-voice-bus-stop" data-visual-id="home-voice-bus-stop">
        <img src="{base}assets/img/photos/bus-stop-resident-600.jpg" srcset="{base}assets/img/photos/bus-stop-resident-600.jpg 600w, {base}assets/img/photos/bus-stop-resident-1080.jpg 1080w" sizes="(max-width: 700px) 64vw, 360px" width="600" height="600" alt="A woman waits at a neighborhood bus stop, houses and gardens behind her" loading="lazy" decoding="async" data-photo-asset="public/metropolitancouncil/assets/img/photos/bus-stop-resident-1080.jpg" data-crop-kind="photo">
      </figure>
      <figure class="portal portal-sm" data-photo-story-id="home-voice-global-market" data-visual-id="home-voice-global-market">
        <img src="{base}assets/img/photos/global-market-neighbors-600.jpg" srcset="{base}assets/img/photos/global-market-neighbors-600.jpg 600w, {base}assets/img/photos/global-market-neighbors-1080.jpg 1080w" sizes="(max-width: 700px) 40vw, 220px" width="600" height="600" alt="Two women smiling together at Midtown Global Market on Lake Street" loading="lazy" decoding="async" data-photo-asset="public/metropolitancouncil/assets/img/photos/global-market-neighbors-1080.jpg" data-crop-kind="photo">
      </figure>
    </div>
    <div class="voice-copy">
      <h2 id="voice-title"><span class="station-stop" aria-hidden="true"></span>Displacement, as residents define it</h2>
      <blockquote class="pull-quote" data-verbatim data-source-copy="i2050-anti-displacement-framework"><p>You tore up my neighborhood where I grew up in, and I don't recognize it anymore.</p><footer>Metropolitan Center for Independent Living participant, quoted in the Council's Anti-displacement Framework</footer></blockquote>
      <p data-verbatim data-source-copy="i2050-anti-displacement-framework">Though displacement is, ultimately, defined by residents, it can mean a physical and involuntary, often violent, loss of one's home, community, or access to resources. It can be an economic, social, or cultural change, removal, or the loss of sense of belonging in one's community.</p>
      <p><a class="text-link" href="{base}story/">Read the story of the data</a></p>
    </div>
  </div>
</section>

<section class="band analysis-band" aria-labelledby="analysis-title">
  <div class="band-inner">
    <h2 id="analysis-title"><span class="station-stop" aria-hidden="true"></span>What the Displacement Analysis adds</h2>
    <div class="analysis-grid">
      <div>
        <p data-source-copy="home-analysis">The Analysis team tracks households moving into and out of each station area and corridor every year from 2006 to 2025, across the seven-county region, using aggregated and de-identified Data Axle records. It compares transit corridors with similar control corridors to separate displacement from ordinary moves.</p>
        <ul class="question-list" role="list">
          <li data-verbatim data-source-copy="rfp-research-questions">What is the extent of displacement occurring near transit corridors?</li>
          <li data-verbatim data-source-copy="rfp-research-questions">During which project phase(s) is displacement occurring, and how do trends differ across phases?</li>
          <li data-verbatim data-source-copy="rfp-research-questions">How can we distinguish between forced displacement and movement to opportunity?</li>
        </ul>
      </div>
      {example_figure(base, compact=True)}
    </div>
  </div>
</section>
{embed_block(base, "", "Region map, Displacement Dashboard, Metropolitan Council", "region")}
"""


def example_figure(base, compact=False):
    ex = ANALYSIS_EXAMPLE

    def bar(label, data, key):
        segs = "".join(
            f'<span class="seg seg-g{i}" style="--w:{share / 100:.4f}" role="img" aria-label="{H.attr(name)}: {share} percent">{share:g}%</span>'
            for i, (name, share) in enumerate(data["shares"])
        )
        return f'<div class="ex-row"><span class="ex-label">{label}<span class="ex-count">{n(data["households"])} households</span></span><div class="seg-bar">{segs}</div></div>'

    legend = "".join(f'<li><span class="seg-key seg-g{i}" aria-hidden="true"></span>{E(name)}</li>' for i, (name, _) in enumerate(ex["out"]["shares"]))
    rows = "".join(f'<tr><th scope="row">{E(name)}</th><td>{o}%</td><td>{i}%</td></tr>' for (name, o), (_, i) in zip(ex["out"]["shares"], ex["in"]["shares"]))
    return (
        f'<figure class="example-figure chart-fig" id="how-a-finding-reads" aria-labelledby="example-title" data-visual-id="analysis-example" data-visual-kind="data-graphic">'
        f'<figcaption class="chart-head"><span class="kicker">Example from the RFP, not Twin Cities data</span>'
        f'<span class="chart-title" id="example-title">Households moving out and in, by race and ethnicity, {ex["scope"]}, {ex["years"]}</span></figcaption>'
        f'<button class="table-toggle" type="button" aria-controls="example-table" aria-expanded="false">Show as table</button>'
        f'{bar("Moving out", ex["out"], "out")}{bar("Moving in", ex["in"], "in")}'
        f'<ul class="seg-legend" role="list">{legend}</ul>'
        f'<table class="data-table" id="example-table" hidden><caption>Share of households moving out and in, {ex["scope"]}, {ex["years"]}</caption>'
        f'<thead><tr><th scope="col">Group</th><th scope="col">Moving out ({n(ex["out"]["households"])})</th><th scope="col">Moving in ({n(ex["in"]["households"])})</th></tr></thead><tbody>{rows}</tbody></table>'
        f'<p class="chart-note" data-source-copy="example-source">Source: {E(ex["source"])}. Twin Cities results replace this example station by station.</p>'
        f'</figure>'
    )


def lines_index_main(model, base):
    groups = []
    for status, title in (("in-service", "In service"), ("planned", "Planned")):
        cards = []
        for l in model["lines"]:
            if l["status"] != status:
                continue
            ends = f'{E(l["stations"][0]["name"])} to {E(l["stations"][-1]["name"])}' if l["stations"] else "Routes " + ", ".join(str(r) for r in l.get("routes", []))
            cards.append(
                f'<li class="line-row" style="--line:{l["color"]};--line-mark:{H.chart_color(l["color"])}">'
                f'{H.line_badge(l, base)}'
                f'<p class="line-row-ends">{ends}</p>'
                f'<p class="line-row-meta">{E(l["modeLabel"])} · {E(H.status_text(l))}</p>'
                f'<p class="line-row-figure"><span>{n(l["total"])}</span> multifamily homes permitted {near(l)}, 2009 to 2024</p></li>'
            )
        groups.append(f'<section class="line-group" aria-labelledby="g-{status}"><h2 id="g-{status}"><span class="station-stop" aria-hidden="true"></span>{title}</h2><ul class="line-rows" role="list">{"".join(cards)}</ul></section>')
    return f"""
<section class="page-head">
  <h1>Lines and Stations</h1>
  <p class="lede">Every corridor the TOD Office tracks in Development Trends Along Transit: METRO light rail and bus rapid transit lines in service and planned, and the High Frequency Network of local buses. Open a line to ride it station by station.</p>
</section>
{H.band(base, "lines-crossing", "station-crossing", 1000, 1900, "Riders cross the street at a Green Line station as a train pulls in", "0.05 0.15 0.9 0.8")}
<div class="line-groups">{"".join(groups)}</div>
"""


def line_main(line, model, base):
    years = model["years"]
    ends = ""
    if line["stations"]:
        ends = f'{E(line["stations"][0]["name"])} to {E(line["stations"][-1]["name"])}'
    city_list = line.get("cities", [])
    if len(city_list) > 5:
        through = f' through {E(", ".join(city_list[:4]))} and {len(city_list) - 4} other cities'
    elif city_list:
        through = f" through {E(join_and(city_list))}"
    else:
        through = ""
    intro_bits = []
    if line["status"] == "planned":
        intro_bits.append(f'A planned {E(line["modeLabel"].lower())} line from {ends}{through}, now in {(line.get("phase") or "planning").lower()}. Homes permitted along its future corridor show what is already changing before service.')
    elif line["id"] == "high-frequency-bus":
        intro_bits.append(f'Local routes {", ".join(str(r) for r in line.get("routes", []))} run every 15 minutes or better on weekdays and Saturdays, the network Development Trends Along Transit tracks beside the METRO lines.')
    else:
        intro_bits.append(f'{E(line["modeLabel"])} from {ends}{through}, {E(H.status_text(line).lower())}.')
    series = line["byYear"]
    color = H.chart_color(line["color"])
    chart = H.year_chart(series, years, f"years-{line['id']}", f"Multifamily homes permitted each year {near(line)} of the {line['name']}", color,
                         opened=line.get("opened"), note="Each bar counts homes on building permits issued that year, from the Council's Building Permit Survey.")
    strip_html = H.strip(line, base) if line["stations"] else ""
    stations_list = ""
    if line["stations"]:
        items = "".join(f'<li><a href="{base}lines/{line["id"]}/{s["id"]}/">{E(s["name"])}</a> <span class="muted">{E(s["city"] or "")}</span></li>' for s in line["stations"])
        stations_list = f'<section class="station-list" aria-labelledby="st-{line["id"]}"><h2 id="st-{line["id"]}"><span class="station-stop" aria-hidden="true"></span>Stations, in order</h2><ol class="stations-ol">{items}</ol></section>'
    return f"""
<section class="line-head{' is-planned' if line['status'] == 'planned' else ''}" data-page-heading-family="line" data-page-heading-family-reason="Line pages open with the line's own color band above the title, the way a METRO route sign does; the other pages open with the title." style="--line:{line['color']};--line-mark:{color};--line-ink:{H.text_on(line['color'])}" data-line-page="{line['id']}">
  <h1>{E(line['name'])}</h1>
  <ul class="line-facts" role="list">{line_facts(line)}</ul>
  <p class="lede" data-source-copy="line-lede">{" ".join(intro_bits)}</p>
</section>
<section class="corridor" aria-label="Corridor map and figures" style="--line:{line['color']};--line-mark:{color}">
  <div class="map-frame map-frame-corridor">
    <div id="map" class="map" role="region" aria-label="Map of the {H.attr(line['name'])} corridor and the homes permitted near it" data-map-line="{line['id']}" data-visual-id="corridor-map" data-visual-kind="map"></div>
    <noscript><p class="map-noscript">The map needs JavaScript. The stations are listed below.</p></noscript>
  </div>
  <div class="corridor-figures">
    <p class="kicker">{near(line).capitalize()}, 2009 to 2024</p>
    <p class="hero-block"><span class="hero-figure">{n(line['total'])}</span><span class="hero-label">multifamily homes permitted</span></p>
    {before_after(line, model['region'], years)}
    {H.tenure_bar(line['tenure'], f"tenure-{line['id']}")}
    {source_line("Source: " + DTAT_SOURCE)}
  </div>
</section>
{strip_html}
<section class="chart-section">{chart}</section>
{dtat_line_block(line, base)}
{H.analysis_pending("the " + line['name'], base)}
{stations_list}
{embed_block(base, f"lines/{line['id']}/", f"{line['name']}, Displacement Dashboard, Metropolitan Council", line['id'])}
"""


def nearby_other_lines(line, st, model, base):
    out = []
    for other in model["lines"]:
        if other["id"] == line["id"]:
            continue
        for s2 in other["stations"]:
            if D.miles((st["lon"], st["lat"]), (s2["lon"], s2["lat"])) <= 0.25:
                out.append((other, s2))
                break
    if not out:
        return ""
    links = "".join(f'<li>{H.line_badge(o, base, tag="span")} <a href="{base}lines/{o["id"]}/{s2["id"]}/">{E(s2["name"])}</a></li>' for o, s2 in out)
    return f'<section class="also-served" aria-labelledby="also-{st["id"]}"><h2 id="also-{st["id"]}"><span class="station-stop" aria-hidden="true"></span>Also served here</h2><ul class="also-list" role="list">{links}</ul></section>'


def verbatim_name(name):
    """Station names such as Ramp A/7th St Transit Center keep Metro Transit's casing."""
    if re.search(r"\b[A-Z]\b", name):
        return ' data-title-style="verbatim" data-title-style-reason="Metro Transit\'s official station name; the single capital letter names a ramp or platform"'
    return ""


def station_main(line, st, idx, model, base):
    years = model["years"]
    color = H.chart_color(line["color"])
    prev_s = line["stations"][idx - 1] if idx > 0 else None
    next_s = line["stations"][idx + 1] if idx + 1 < len(line["stations"]) else None
    ride = '<nav class="ride" aria-label="Along the line">'
    ride += f'<a class="ride-prev" href="{base}lines/{line["id"]}/{prev_s["id"]}/"{verbatim_name(prev_s["name"])}><span class="ride-dir">Previous stop</span><span class="ride-name">{E(prev_s["name"])}</span></a>' if prev_s else '<span class="ride-end">First stop</span>'
    ride += f'<a class="ride-next" href="{base}lines/{line["id"]}/{next_s["id"]}/"{verbatim_name(next_s["name"])}><span class="ride-dir">Next stop</span><span class="ride-name">{E(next_s["name"])}</span></a>' if next_s else '<span class="ride-end">Last stop</span>'
    ride += "</nav>"
    opened = st.get("opened") or line.get("opened")
    status = "In service since " + str(opened) if (opened and line["status"] != "planned") else H.status_text(line)
    chart = H.year_chart(st["byYear"], years, f"years-{line['id']}-{st['id']}", f"Multifamily homes permitted each year nearest {st['name']}", color,
                         opened=opened if line["status"] != "planned" else None,
                         note=f"Counts every permit inside the {E(line['name'])} corridor whose nearest {E(line['name'])} station is {E(st['name'])}.")
    types = st.get("types", {})
    type_labels = {"mf": "Apartment buildings (5 or more homes)", "th": "Townhomes", "dtq": "Duplexes to fourplexes", "adu": "Accessory dwelling units", "other": "Other"}
    type_rows = "".join(f'<li><span>{E(type_labels.get(k, k))}</span><span class="num">{n(v)}</span></li>' for k, v in sorted(types.items(), key=lambda kv: -kv[1]) if v)
    types_html = f'<div class="type-list"><h2>By building type</h2><ul role="list">{type_rows}</ul></div>' if type_rows else ""
    if st["total"] == 0:
        figures = f'<p class="hero-block"><span class="hero-figure">0</span><span class="hero-label">multifamily homes permitted nearest this station, 2009 to 2024</span></p>'
    else:
        figures = (f'<p class="hero-block"><span class="hero-figure">{n(st["total"])}</span><span class="hero-label">multifamily homes permitted nearest this station, 2009 to 2024</span></p>'
                   f'{H.tenure_bar(st["tenure"], f"tenure-{line["id"]}-{st["id"]}")}{types_html}')
    return f"""
<section class="station-head" style="--line:{line['color']};--line-mark:{color}" data-station-page="{line['id']}/{st['id']}" data-lon="{st['lon']}" data-lat="{st['lat']}">
  <p class="kicker">{H.line_badge(line, base)} <span class="kicker-text">station{(" · " + E(st["city"])) if st["city"] else ""}</span></p>
  <h1{verbatim_name(st['name'])}>{E(st['name'])}</h1>
  <ul class="line-facts" role="list"><li>{E(line['modeLabel'])}</li><li>{E(status)}</li><li>Stop {idx + 1} of {len(line['stations'])}</li></ul>
  {ride}
</section>
<section class="corridor station-corridor" aria-label="Station area map and figures" style="--line:{line['color']};--line-mark:{color}">
  <div class="map-frame map-frame-station">
    <div id="map" class="map" role="region" aria-label="Map of the area around {H.attr(st['name'])} and the homes permitted there" data-map-line="{line['id']}" data-map-station="{st['id']}" data-visual-id="station-map" data-visual-kind="map"></div>
    <noscript><p class="map-noscript">The map needs JavaScript. The figures beside it cover the same area.</p></noscript>
  </div>
  <div class="corridor-figures">
    <p class="kicker">Nearest {E(st['name'])}, 2009 to 2024</p>
    {figures}
    {source_line("Source: " + DTAT_SOURCE)}
  </div>
</section>
{H.strip(line, base, current_id=st['id'], title=f"Where {st['name']} sits on the {line['name']}", compact=True)}
<section class="chart-section">{chart}</section>
{nearby_other_lines(line, st, model, base)}
{H.analysis_pending(st['name'], base)}
{embed_block(base, f"lines/{line['id']}/{st['id']}/", f"{st['name']} on the {line['name']}, Displacement Dashboard, Metropolitan Council", f"{line['id']}-{st['id']}")}
"""


# --------------------------------------------------------- data outputs ----

def write_data(model, site: Path, base: str):
    data = site / "data"
    (data / "geo").mkdir(parents=True, exist_ok=True)
    years = model["years"]
    lines_out = []
    for l in model["lines"]:
        lines_out.append({
            "id": l["id"], "name": l["name"], "mode": l["mode"], "modeLabel": l["modeLabel"], "color": l["color"],
            "markColor": H.chart_color(l["color"]), "ink": H.text_on(l["color"]), "status": l["status"], "statusText": H.status_text(l),
            "opened": l.get("opened"), "phase": l.get("phase"), "lengthMi": l.get("lengthMi"), "total": l["total"],
            "byYear": [l["byYear"][y] for y in years], "beforeAfter": l.get("beforeAfter"), "tenure": l["tenure"],
            "cities": l.get("cities", []), "routes": l.get("routes", []), "url": f"{base}lines/{l['id']}/",
            "stations": [{"id": s["id"], "name": s["name"], "lon": s["lon"], "lat": s["lat"], "city": s["city"], "total": s["total"],
                          "byYear": [s["byYear"][y] for y in years], "url": f"{base}lines/{l['id']}/{s['id']}/"} for s in l["stations"]],
        })
    dashboard = {"generated": datetime.date.today().isoformat(), "years": years, "region": model["region"], "lines": lines_out, "bbox": model["bbox"]}
    (data / "dashboard.json").write_text(json.dumps(dashboard, separators=(",", ":")))

    def fc(features):
        return json.dumps({"type": "FeatureCollection", "features": features}, separators=(",", ":"))

    (data / "geo" / "lines.geojson").write_text(fc([
        {"type": "Feature", "properties": {"id": l["id"], "name": l["name"], "color": l["color"], "status": l["status"], "mode": l["mode"]}, "geometry": l["geometry"]}
        for l in model["lines"] if l["geometry"]]))
    (data / "geo" / "areas.geojson").write_text(fc([
        {"type": "Feature", "properties": {"id": l["id"], "status": l["status"], "mode": l["mode"]}, "geometry": l["area"]}
        for l in model["lines"] if l.get("area")]))
    (data / "geo" / "stations.geojson").write_text(fc([
        {"type": "Feature", "properties": {"line": l["id"], "id": s["id"], "name": s["name"], "status": l["status"], "mode": l["mode"], "total": s["total"]},
         "geometry": {"type": "Point", "coordinates": [s["lon"], s["lat"]]}}
        for l in model["lines"] for s in l["stations"]]))
    (data / "geo" / "permits.geojson").write_text(fc([
        {"type": "Feature", "properties": {"y": p["year"], "u": p["units"], "t": p["tenure"], "h": p["type"], "l": "|" + "|".join(p["lines"]) + "|", "s": "|" + "|".join(f"{k}/{v}" for k, v in p.get("stations", {}).items()) + "|"},
         "geometry": {"type": "Point", "coordinates": [p["lon"], p["lat"]]}}
        for p in model["permits"]]))
    (data / "geo" / "counties.geojson").write_text(fc([
        {"type": "Feature", "properties": {"name": c["name"]}, "geometry": c["geometry"]} for c in model["counties"]]))
    (data / "geo" / "cities.geojson").write_text(fc([
        {"type": "Feature", "properties": {"name": c["name"], "type": c["type"]}, "geometry": c["geometry"]} for c in model["cities"]]))
    return dashboard


def write_downloads(model, site: Path):
    dl = site / "downloads"
    dl.mkdir(parents=True, exist_ok=True)
    years = model["years"]
    buf = io.StringIO()
    w = csv.writer(buf)
    w.writerow(["line", "station", "city", "station_order"] + [str(y) for y in years] + ["total"])
    for l in model["lines"]:
        for i, s in enumerate(l["stations"], start=1):
            w.writerow([l["name"], s["name"], s["city"], i] + [s["byYear"][y] for y in years] + [s["total"]])
    (dl / "homes-permitted-by-station.csv").write_text(buf.getvalue())
    buf = io.StringIO()
    w = csv.writer(buf)
    w.writerow(["line", "mode", "status", "opened"] + [str(y) for y in years] + ["total"])
    for l in model["lines"]:
        w.writerow([l["name"], l["modeLabel"], l["status"], l.get("opened") or ""] + [l["byYear"][y] for y in years] + [l["total"]])
    (dl / "homes-permitted-by-line.csv").write_text(buf.getvalue())
    buf = io.StringIO()
    w = csv.writer(buf)
    w.writerow(["year", "units", "tenure", "housing_type", "lines", "nearest_stations", "city", "lon", "lat"])
    for p in model["permits"]:
        w.writerow([p["year"], p["units"], p["tenure"], p["type"], "|".join(p["lines"]), "|".join(f"{k}/{v}" for k, v in p.get("stations", {}).items()), p["city"], p["lon"], p["lat"]])
    (dl / "permits-in-corridors.csv").write_text(buf.getvalue())


def doc_pages(pdf: Path):
    """Page-by-page text of a hosted PDF for the full-text search index."""
    try:
        out = subprocess.run(["pdftotext", "-layout", str(pdf), "-"], capture_output=True, text=True, check=True).stdout
    except (OSError, subprocess.CalledProcessError):
        return []
    return [re.sub(r"\s+", " ", p).strip() for p in out.split("\f")]


def write_search(model, site: Path, base: str, pages):
    light, full = [], []
    rid = 0
    for l in model["lines"]:
        rid += 1
        body = f'{l["modeLabel"]} {H.status_text(l)} ' + " ".join(s["name"] for s in l["stations"]) + " " + " ".join(l.get("cities", []))
        rec = {"id": rid, "title": l["name"], "body": body, "type": "Line", "tags": [l["modeLabel"], *l.get("cities", [])], "url": f"{base}lines/{l['id']}/"}
        light.append(rec); full.append(rec)
        for s in l["stations"]:
            rid += 1
            rec = {"id": rid, "title": f'{s["name"]}', "body": f'{l["name"]} station {s["city"]}', "type": "Station", "tags": [l["name"], s["city"]], "url": f"{base}lines/{l['id']}/{s['id']}/"}
            light.append(rec); full.append(rec)
    cities = {}
    for l in model["lines"]:
        for s in l["stations"]:
            if s["city"]:
                cities.setdefault(s["city"], []).append((l, s))
    for city, pairs in sorted(cities.items()):
        rid += 1
        first_line, first_station = pairs[0]
        names = sorted({l["name"] for l, s in pairs})
        rec = {"id": rid, "title": city, "body": "City served by " + ", ".join(names), "type": "City", "tags": names, "url": f"{base}lines/{first_line['id']}/{first_station['id']}/"}
        light.append(rec); full.append(rec)
    for title, url, body in pages:
        rid += 1
        rec = {"id": rid, "title": title, "body": body, "type": "Page", "url": url}
        light.append(rec); full.append(rec)
    for title, rel in (("Development Trends Along Transit, 2025 Report", DTAT_REPORT), ("Imagine 2050 Housing Policy Plan", HPP_REPORT)):
        texts = doc_pages(site / rel)
        rid += 1
        light.append({"id": rid, "title": title, "body": (texts[0][:400] if texts else ""), "type": "Document", "url": f"{base}{rel}"})
        for i, t in enumerate(texts, start=1):
            if len(t) < 40:
                continue
            rid += 1
            full.append({"id": rid, "title": f"{title}, page {i}", "body": t, "type": "Document", "url": f"{base}{rel}#page={i}"})
    synonyms = {
        "lrt": ["light rail"], "rail": ["light rail"], "train": ["light rail"], "brt": ["bus rapid transit"],
        "bus": ["bus rapid transit", "high frequency"], "frequent": ["high frequency"],
        "minneapolis": ["mpls"], "mpls": ["minneapolis"], "st": ["saint"], "saint": ["st"],
        "housing": ["homes", "multifamily"], "homes": ["housing", "multifamily"], "apartments": ["multifamily"],
        "gentrification": ["displacement"], "displacement": ["gentrification", "moving"], "update": ["annual update"],
        "contact": ["get in touch", "questions"], "touch": ["contact"], "download": ["data", "csv"],
        "affordable": ["area median income", "ami"], "ami": ["area median income"],
    }
    (site / "data" / "search-light.js").write_text("/* Displacement Dashboard search index (light): generated by update_dashboard.py */\nwindow.DD_SEARCH=" + json.dumps({"corpus": light, "synonyms": synonyms}, separators=(",", ":")) + ";\n")
    (site / "data" / "search-full.json").write_text(json.dumps({"corpus": full, "synonyms": synonyms}, separators=(",", ":")))


# ----------------------------------------------------------------- main ----

def main(argv=None):
    ap = argparse.ArgumentParser(description="Rebuild the Displacement Dashboard from the Council's layers.")
    ap.add_argument("--inputs", default=str(HERE / "inputs"), help="folder of GeoJSON inputs (default: inputs/)")
    ap.add_argument("--site", default=str(REPO_SITE), help="site folder to write")
    ap.add_argument("--base", default="/metropolitancouncil/", help="URL path the site is served from")
    ap.add_argument("--fetch", action="store_true", help="download the layers from the Council's ArcGIS services first")
    args = ap.parse_args(argv)
    inputs, site, base = Path(args.inputs), Path(args.site), args.base if args.base.endswith("/") else args.base + "/"
    if args.fetch:
        print("Fetching layers from arcgis.metc.state.mn.us")
        D.fetch_inputs(inputs)
    model = D.build_model(inputs)
    chrome = chrome_blocks(site)
    import site_pages as P  # noqa: E402  (the hand-written pages: story, about, update, one-pager)
    write_data(model, site, base)
    write_downloads(model, site)
    model["report"] = DTAT_FACTS  # after write_data, so the figures stay out of dashboard.json
    for line in model["lines"]:
        CRUMB_TRAIL[f"{base}lines/{line['id']}/"] = (line["name"], f"{base}lines/")
    pages_for_search = P.write_site_pages(model, site, base, chrome, page, write, home_main, lines_index_main, example_figure)
    for line in model["lines"]:
        CRUMB_TRAIL[f"{base}lines/{line['id']}/"] = (line["name"], f"{base}lines/")
        write(site, f"lines/{line['id']}/index.html", page(base, f"{line['name']} · Displacement Dashboard", f"Homes permitted {near(line)} of the {line['name']}, {'station by station' if line['stations'] else 'year by year'}, 2009 to 2024.",
                                                          line_main(line, model, base), chrome=chrome, body_class="page-line", crumb=(line["name"], f"{base}lines/"),
                                                          scripts=("line-strip.js", "corridor.mjs"), rel=f"lines/{line['id']}/index.html", head_extra=f'\n<link rel="stylesheet" href="{base}assets/vendor/maplibre-gl-6.15.0/maplibre-gl.css">', embed=True))
        for i, st in enumerate(line["stations"]):
            write(site, f"lines/{line['id']}/{st['id']}/index.html", page(base, f"{st['name']} · {line['name']} · Displacement Dashboard",
                                                                         f"Homes permitted nearest {st['name']} on the {line['name']}, 2009 to 2024.",
                                                                         station_main(line, st, i, model, base), chrome=chrome, body_class="page-station",
                                                                         crumb=None if verbatim_name(st["name"]) else (st["name"], f"{base}lines/{line['id']}/"), scripts=("line-strip.js", "corridor.mjs"), rel=f"lines/{line['id']}/{st['id']}/index.html",
                                                                         head_extra=f'\n<link rel="stylesheet" href="{base}assets/vendor/maplibre-gl-6.15.0/maplibre-gl.css">',
                                                                         title_attrs=verbatim_name(st["name"]), embed=True))
    write_search(model, site, base, pages_for_search)
    n_st = sum(len(l["stations"]) for l in model["lines"])
    print(f"Built {len(model['lines'])} lines, {n_st} stations, {len(model['permits'])} corridor permits into {site}")


if __name__ == "__main__":
    main()
