#!/usr/bin/env node
/**
 * Most common street names in the United States, counted from the Census
 * Bureau's TIGER/Line 2025 county files.
 *
 * Reproduces every number in https://fakenamely.com/blog/most-common-street-names
 *
 * Requires Node 18+ and the `unzip` and `curl` commands. About 1.6 GB of downloads
 * (3,235 FEATNAMES files and 3,227 ADDR files), cached in --cache so a second
 * run reads from disk. A full run takes 10 to 20 minutes on a laptop.
 *
 *   node most-common-street-names.mjs --cache ./tiger-2025 --out ./out
 *
 * What counts as a street (see the post's method box):
 *   - an edge with MTFCC S1200 (secondary road) or S1400 (local street);
 *   - its name as recorded in FEATNAMES, primary or alternate;
 *   - not a route designation: a name whose prefix type is State Rte, US Hwy,
 *     Co Rd and the like, or whose base name is a bare number ("Rd 26"), is
 *     dropped, because "State Rte 9" is a route number, not a street name;
 *   - spelled ordinals are folded into digits, so "Second" and "2nd" are one
 *     name.
 *   - a directional written inside the name ("S Main", with no separate
 *     prefix direction) is moved out, so "S Main St" is Main however it is
 *     stored.
 * One street = one LINEARID, the Census identifier for a named linear feature.
 * ZIP codes come from the ADDR file of the same county (address ranges by edge).
 *
 * Two measures per name. "Streets" counts LINEARIDs, which the Census splits
 * more finely than a person would (one long Main St can be several). "ZIP
 * codes" counts the ZIP codes whose address ranges include at least one street
 * of that name, which is the closer answer to "how many places have one".
 *
 * Outputs:
 *   top-by-zip.csv     the 300 base names with the most streets, ranked by ZIP codes
 *   exact-by-zip.csv   the 150 name + type pairs ("Main St") with the most streets, by ZIP codes
 *   names.csv          every base name with at least 25 streets, by streets
 *   exact-names.csv    the top 1,000 name + type pairs, by streets
 *   states.csv         the top ten base names in each state, by ZIP codes
 *   types.csv          street types (St, Rd, Dr…) and their share of streets
 *   families.json      people commemorated under several spellings (MLK…)
 *   first-second.json  ZIP codes with a 2nd but no 1st, and what they have instead
 *   top-names.json     detail for the top 300: types, full names, counts
 *   summary.json       totals and the rules applied
 */
import { execFileSync } from "node:child_process";
import { closeSync, existsSync, mkdirSync, openSync, readSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";

const TIGER = "https://www2.census.gov/geo/tiger/TIGER2025";
const TIGER_FTP = "ftp://ftp2.census.gov/geo/tiger/TIGER2025";
const ROAD_MTFCC = new Set(["S1200", "S1400"]);
const MIN_STREETS_IN_CSV = 25;
const TOP_DETAIL = 300;
const TOP_EXACT_DETAIL = 150;
const STATE_TOP = 10;
const CONCURRENCY = 8;

// Prefix types that mark a route designation rather than a street name: every
// road-class prefix type seen in a national sample of 270 counties on
// 2 October 2026 whose names are route or grid numbers ("Co Rd 38", "FM 1458",
// "Twp Rd 200 N", "BIA Rd 70"). Prefix types that carry real names are kept:
// Ave A, Calle (Cll) Futura, Via Immaculata, Rue Maison, Camino (Cam) del Norte.
const ROUTE_PRETYPES = new Set([
  "Co Rd", "State Rte", "State Hwy", "US Hwy", "State Rd", "Co Hwy", "Rd", "FM", "RM", "Hwy",
  "Twp Hwy", "Twp Rd", "Parish Rd", "Co Rte", "Forest Rte", "Rte", "Indian Svc Rte", "US Rte",
  "State Loop", "BIA Rd", "BIA Rte", "I-", "Trl", "Ranch Rd", "Indian Rte", "State Spur",
  "Co Trunk Hwy", "St Trunk Hwy", "Co St Aid Hwy", "FS Rd", "Loop", "Fire Rd", "Forest Rd",
  "Forest Hwy", "Town Hwy", "Town Rd", "BLM Rd", "Delta Rd", "Fire Ln", "Logging Rd",
  "Farm Rd", "Resvn Hwy", "Svc Rd", "Fire Cntrl Rd", "Fire Dist Rd", "Co Ln", "Expy",
]);

const ORDINAL_WORDS = [
  "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth",
  "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth",
  "eighteenth", "nineteenth", "twentieth",
];
const ordinalDigits = (n) => {
  const s = ["th", "st", "nd", "rd"];
  const v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
};
const ORDINAL_FOLD = new Map(ORDINAL_WORDS.map((w, i) => [w, ordinalDigits(i + 1)]));

// Names always given ZIP detail, whatever their rank: the First/Second question
// needs to know which of these share a ZIP code.
const ALWAYS_DETAIL = ["1st", "2nd", "3rd", "main", "front", "broadway", "center", "market", "water", "high", "church", "mill"];

// People commemorated under several spellings. Matched against the base name.
const FAMILIES = {
  "Martin Luther King Jr": /^(dr\.? )?(rev\.? )?(martin luther king|martin l\.? king|m\.? ?l\.? king|mlk)( jr\.?)?$/i,
  "Cesar Chavez": /^c[eé]sar (e\.? )?ch[aá]vez$/i,
  Kennedy: /^(john f\.? |jf )?kennedy$/i,
  Washington: /^(george )?washington$/i,
  Lincoln: /^(abraham )?lincoln$/i,
  Jefferson: /^(thomas )?jefferson$/i,
  Jackson: /^(andrew )?jackson$/i,
};

const STATE_FIPS = {
  "01": "AL", "02": "AK", "04": "AZ", "05": "AR", "06": "CA", "08": "CO", "09": "CT", "10": "DE", "11": "DC",
  "12": "FL", "13": "GA", "15": "HI", "16": "ID", "17": "IL", "18": "IN", "19": "IA", "20": "KS", "21": "KY",
  "22": "LA", "23": "ME", "24": "MD", "25": "MA", "26": "MI", "27": "MN", "28": "MS", "29": "MO", "30": "MT",
  "31": "NE", "32": "NV", "33": "NH", "34": "NJ", "35": "NM", "36": "NY", "37": "NC", "38": "ND", "39": "OH",
  "40": "OK", "41": "OR", "42": "PA", "44": "RI", "45": "SC", "46": "SD", "47": "TN", "48": "TX", "49": "UT",
  "50": "VT", "51": "VA", "53": "WA", "54": "WV", "55": "WI", "56": "WY", "60": "AS", "66": "GU", "69": "MP",
  "72": "PR", "78": "VI",
};

const args = Object.fromEntries(
  process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith("--") ? [...acc, [a.slice(2), all[i + 1]]] : acc), []),
);
const CACHE = args.cache ?? "tiger-2025";
const OUT = args.out ?? "out";
mkdirSync(CACHE, { recursive: true });
mkdirSync(OUT, { recursive: true });

/* ---------- download ---------- */

const listDir = async (layer, suffix) => {
  const res = await fetch(`${TIGER}/${layer}/`);
  if (!res.ok) throw new Error(`${layer} listing: HTTP ${res.status}`);
  const html = await res.text();
  const re = new RegExp(`tl_2025_(\\d{5})_${suffix}\\.zip`, "g");
  return [...new Set([...html.matchAll(re)].map((m) => m[1]))].sort();
};

const isZip = (file) => {
  if (!existsSync(file) || statSync(file).size < 4) return false;
  const head = Buffer.alloc(4);
  const fd = openSync(file, "r");
  readSync(fd, head, 0, 4, 0);
  closeSync(fd);
  return head.readUInt32LE(0) === 0x04034b50; // "PK\x03\x04"
};

// www2.census.gov sits behind a firewall that answers a handful of these files
// (nine of 6,462 on 2 October 2026, the same nine on every retry) with a
// 247-byte "Request Rejected" HTML page and status 200. The same files download
// cleanly from the FTP mirror, so a response that is not a zip falls back to it.
const download = async (layer, suffix, fips) => {
  const name = `tl_2025_${fips}_${suffix}.zip`;
  const file = join(CACHE, name);
  if (isZip(file)) return file;
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const res = await fetch(`${TIGER}/${layer}/${name}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      writeFileSync(file, Buffer.from(await res.arrayBuffer()));
      if (isZip(file)) return file;
      break; // a rejection page, not a transient error: go to the mirror
    } catch (e) {
      if (attempt === 3) break;
      await new Promise((r) => setTimeout(r, 2000 * attempt));
    }
  }
  execFileSync("curl", ["-s", "--retry", "3", "-o", file, `${TIGER_FTP}/${layer}/${name}`]);
  if (!isZip(file)) throw new Error(`${name}: not a zip from either host`);
  return file;
};

const pool = async (items, worker) => {
  let next = 0;
  const run = async () => {
    while (next < items.length) {
      const i = next++;
      await worker(items[i], i);
    }
  };
  await Promise.all(Array.from({ length: CONCURRENCY }, run));
};

/* ---------- dBASE reader (only the fields asked for) ---------- */

const readDbf = (zipFile, wanted) => {
  const dbfName = zipFile.replace(/^.*\//, "").replace(/\.zip$/, ".dbf");
  const buf = execFileSync("unzip", ["-p", zipFile, dbfName], { maxBuffer: 2 ** 31 - 1 });
  const nRec = buf.readUInt32LE(4);
  const hLen = buf.readUInt16LE(8);
  const rLen = buf.readUInt16LE(10);
  const cols = [];
  let off = 1;
  for (let o = 32; buf[o] !== 0x0d; o += 32) {
    const name = buf.toString("latin1", o, o + 11).replace(/\0.*$/, "");
    const len = buf[o + 16];
    if (wanted.includes(name)) cols.push({ name, off, len });
    off += len;
  }
  const missing = wanted.filter((w) => !cols.some((c) => c.name === w));
  if (missing.length > 0) throw new Error(`${dbfName}: missing fields ${missing.join(", ")}`);
  const rows = [];
  for (let i = 0; i < nRec; i++) {
    const base = hLen + i * rLen;
    if (buf[base] === 0x2a) continue; // deleted record
    const rec = {};
    for (const c of cols) rec[c.name] = buf.toString("utf8", base + c.off, base + c.off + c.len).trim();
    rows.push(rec);
  }
  return rows;
};

/* ---------- normalisation ---------- */

const FEAT_FIELDS = ["TLID", "NAME", "PRETYPABRV", "SUFTYPABRV", "LINEARID", "MTFCC", "PAFLAG", "FULLNAME"];
const ADDR_FIELDS = ["TLID", "ZIP"];

const EMBEDDED_DIRECTIONAL = /^(N|S|E|W|NE|NW|SE|SW) (?=\S)/;

/** Base name key, or null when the row is not a street name by the rules above. */
const baseName = (r) => {
  if (!ROAD_MTFCC.has(r.MTFCC)) return null;
  if (!r.NAME) return null;
  if (r.PRETYPABRV && ROUTE_PRETYPES.has(r.PRETYPABRV)) return null;
  // About 14,000 rows carry the directional inside NAME ("S Main", with no
  // PREDIR), although FULLNAME reads "S Main St" exactly like a row whose S
  // sits in PREDIR. Only the abbreviated forms are stripped: "West End" and
  // "East Lake" are names, "S Main" is Main.
  const name = r.NAME.replace(/\s+/g, " ").replace(EMBEDDED_DIRECTIONAL, "");
  if (/^\d+[A-Za-z]?$/.test(name) && !/^\d+(st|nd|rd|th)$/i.test(name)) return null;
  const folded = ORDINAL_FOLD.get(name.toLowerCase());
  return folded ?? name;
};

const keyOf = (name) => name.toLowerCase();


/** Street type as written after the name ("St"), or the prefix type ("Avenue A"). */
const typeOf = (r) => r.SUFTYPABRV || (r.PRETYPABRV ? `${r.PRETYPABRV} (prefix)` : "(none)");

const bump = (map, key, n = 1) => map.set(key, (map.get(key) ?? 0) + n);
const sortDesc = (map) => [...map].sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])));

/* ---------- pass 1: every street, once ---------- */

const passOne = (featCounties) => {
  const t = {
    seen: new Set(), spellings: new Map(), streets: new Map(), counties: new Map(),
    byState: new Map(), types: new Map(), exact: new Map(), pretypes: new Map(),
    families: new Map(Object.keys(FAMILIES).map((f) => [f, { streets: 0, states: new Set(), spellings: new Map() }])),
    embedded: new Map(), // key -> streets whose NAME carried the directional ("S Main")
    rowsRead: 0, rowsKept: 0, spelledOrdinals: 0, total: 0,
  };
  for (const [i, fips] of featCounties.entries()) {
    const st = STATE_FIPS[fips.slice(0, 2)] ?? fips.slice(0, 2);
    const stateMap = t.byState.get(st) ?? new Map();
    t.byState.set(st, stateMap);
    const countyKeys = new Set();
    for (const r of readDbf(join(CACHE, `tl_2025_${fips}_featnames.zip`), FEAT_FIELDS)) {
      t.rowsRead++;
      if (ROAD_MTFCC.has(r.MTFCC) && r.PRETYPABRV) bump(t.pretypes, r.PRETYPABRV);
      const name = baseName(r);
      if (!name) continue;
      t.rowsKept++;
      const key = keyOf(name);
      countyKeys.add(key);
      const sp = t.spellings.get(key) ?? new Map();
      t.spellings.set(key, sp);
      bump(sp, name);
      const lin = Number(r.LINEARID);
      if (t.seen.has(lin)) continue;
      t.seen.add(lin);
      t.total++;
      if (ORDINAL_FOLD.has(r.NAME.toLowerCase())) t.spelledOrdinals++;
      if (EMBEDDED_DIRECTIONAL.test(r.NAME)) bump(t.embedded, key);
      bump(t.streets, key);
      bump(stateMap, key);
      bump(t.types, typeOf(r));
      bump(t.exact, `${key}|${typeOf(r)}`);
      for (const [family, re] of Object.entries(FAMILIES)) {
        if (!re.test(name)) continue;
        const f = t.families.get(family);
        f.streets++;
        f.states.add(st);
        bump(f.spellings, name);
      }
    }
    for (const k of countyKeys) bump(t.counties, k);
    if ((i + 1) % 250 === 0) console.log(`  pass 1: ${i + 1}/${featCounties.length} counties, ${t.total} streets`);
  }
  t.display = new Map([...t.spellings].map(([k, sp]) => [k, sortDesc(sp)[0][0]]));
  return t;
};

/* ---------- pass 2: ZIP codes for the names that need them ---------- */

const zipsByTlid = (fips, addrCounties, allZips) => {
  const tlZip = new Map();
  if (!addrCounties.has(fips)) return tlZip;
  for (const r of readDbf(join(CACHE, `tl_2025_${fips}_addr.zip`), ADDR_FIELDS)) {
    if (!r.ZIP) continue;
    allZips.add(r.ZIP);
    const s = tlZip.get(r.TLID) ?? new Set();
    s.add(r.ZIP);
    tlZip.set(r.TLID, s);
  }
  return tlZip;
};

const passTwo = (featCounties, addrCounties, detailKeys, exactKeys) => {
  const zips = new Map([...detailKeys].map((k) => [k, new Set()]));
  const exactZips = new Map([...exactKeys].map((k) => [k, new Set()]));
  const stateZipSeen = new Set(); // "state|zip|key", every name
  const stateZips = new Map(); // state -> Map(key -> ZIP codes)
  const familyZips = new Map(Object.keys(FAMILIES).map((f) => [f, { zips: new Set(), states: new Set() }]));
  const fullNames = new Map([...detailKeys].map((k) => [k, new Map()]));
  const allZips = new Set();
  const seen = new Set();
  for (const [i, fips] of featCounties.entries()) {
    const tlZip = zipsByTlid(fips, addrCounties, allZips);
    const st = STATE_FIPS[fips.slice(0, 2)] ?? fips.slice(0, 2);
    const perState = stateZips.get(st) ?? new Map();
    stateZips.set(st, perState);
    for (const r of readDbf(join(CACHE, `tl_2025_${fips}_featnames.zip`), FEAT_FIELDS)) {
      const name = baseName(r);
      if (!name) continue;
      const key = keyOf(name);
      for (const z of tlZip.get(r.TLID) ?? []) {
        const id = `${st}|${z}|${key}`;
        if (stateZipSeen.has(id)) continue;
        stateZipSeen.add(id);
        bump(perState, key);
      }
      for (const [family, re] of Object.entries(FAMILIES)) {
        if (!re.test(name)) continue;
        const f = familyZips.get(family);
        for (const z of tlZip.get(r.TLID) ?? []) f.zips.add(z);
        if ((tlZip.get(r.TLID)?.size ?? 0) > 0) f.states.add(st);
      }
      const exactKey = `${key}|${typeOf(r)}`;
      for (const z of exactZips.has(exactKey) ? tlZip.get(r.TLID) ?? [] : []) exactZips.get(exactKey).add(z);
      if (!detailKeys.has(key)) continue;
      for (const z of tlZip.get(r.TLID) ?? []) zips.get(key).add(z);
      const lin = Number(r.LINEARID);
      if (seen.has(lin)) continue;
      seen.add(lin);
      bump(fullNames.get(key), r.FULLNAME);
    }
    if ((i + 1) % 500 === 0) console.log(`  pass 2: ${i + 1}/${featCounties.length} counties`);
  }
  return { zips, exactZips, fullNames, allZips, stateZips, familyZips };
};

/** Of the ZIP codes with a 2nd street, how many lack a 1st, and what do those have instead? */
const firstSecond = (zips) => {
  const second = zips.get("2nd");
  const first = zips.get("1st");
  const withoutFirst = [...second].filter((z) => !first.has(z));
  const share = (key) => withoutFirst.filter((z) => zips.get(key).has(z)).length;
  const alternatives = ["main", "front", "broadway", "center", "market", "water", "high", "church", "mill"];
  const anyAlt = withoutFirst.filter((z) => alternatives.some((k) => zips.get(k).has(z))).length;
  const withBoth = [...second].filter((z) => first.has(z));
  return {
    zipsWith1stAnd2nd: withBoth.length,
    ofThoseWithBothMain: withBoth.filter((z) => zips.get("main").has(z)).length,
    zipsWith2nd: second.size,
    zipsWith1st: first.size,
    zipsWith2ndButNo1st: withoutFirst.length,
    zipsWith1stButNo2nd: [...first].filter((z) => !second.has(z)).length,
    ofThoseWithout1st: Object.fromEntries(alternatives.map((k) => [k, share(k)])),
    ofThoseWithout1stAnyOfThese: anyAlt,
  };
};

/* ---------- write ---------- */

const csvCell = (v) => (/[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v));
const csv = (header, rows) => [header, ...rows].map((r) => r.map(csvCell).join(",")).join("\n") + "\n";
const out = (file, body) => writeFileSync(join(OUT, file), body);

const writeOutputs = (p1, p2, ranked, featCounties, addrCounties) => {
  const { display, counties, streets } = p1;
  const zipCount = (k) => (p2.zips.has(k) ? p2.zips.get(k).size : "");
  out("names.csv", csv(
    ["rank", "base_name", "streets", "counties", "zip_codes"],
    ranked.filter(([, n]) => n >= MIN_STREETS_IN_CSV).map(([k, n], i) => [i + 1, display.get(k), n, counties.get(k) ?? 0, zipCount(k)]),
  ));
  const exactLabel = (k) => {
    const [key, type] = k.split("|");
    return `${display.get(key)} ${type}`.replace(/ \(none\)$/, "");
  };
  out("exact-names.csv", csv(
    ["rank", "street_name", "streets", "zip_codes"],
    sortDesc(p1.exact).slice(0, 1000).map(([k, n], i) => [i + 1, exactLabel(k), n, p2.exactZips.get(k)?.size ?? ""]),
  ));
  const byZip = (entries) => entries.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
  out("top-by-zip.csv", csv(
    ["rank", "base_name", "zip_codes", "streets", "counties"],
    byZip([...p2.zips].map(([k, z]) => [k, z.size])).map(([k, z], i) => [i + 1, display.get(k), z, streets.get(k), counties.get(k) ?? 0]),
  ));
  out("exact-by-zip.csv", csv(
    ["rank", "street_name", "zip_codes", "streets"],
    byZip([...p2.exactZips].map(([k, z]) => [k, z.size])).map(([k, z], i) => [i + 1, exactLabel(k), z, p1.exact.get(k)]),
  ));
  const stateRows = [...p2.stateZips].sort().flatMap(([st, m]) => {
    const streetsHere = p1.byState.get(st) ?? new Map();
    return sortDesc(m).slice(0, STATE_TOP).map(([k, z], i) => [st, i + 1, display.get(k), z, streetsHere.get(k) ?? 0]);
  });
  out("states.csv", csv(["state", "rank", "base_name", "zip_codes", "streets"], stateRows));
  out("types.csv", csv(["street_type", "streets", "share"], sortDesc(p1.types).slice(0, 60).map(([t, n]) => [t, n, (n / p1.total).toFixed(4)])));
  const families = Object.fromEntries([...p1.families].map(([f, v]) => [f, {
    streets: v.streets, zipCodes: p2.familyZips.get(f).zips.size,
    states: [...p2.familyZips.get(f).states].sort(),
    spellings: Object.fromEntries(sortDesc(v.spellings).slice(0, 12)),
  }]));
  out("families.json", JSON.stringify(families, null, 2));
  out("first-second.json", JSON.stringify(firstSecond(p2.zips), null, 2));
  const typesByKey = new Map();
  for (const [e, c] of p1.exact) {
    const [key, type] = e.split("|");
    if (!p2.zips.has(key)) continue;
    const m = typesByKey.get(key) ?? new Map();
    typesByKey.set(key, m.set(type, c));
  }
  const detail = ranked.slice(0, TOP_DETAIL).map(([k, n], i) => ({
    rank: i + 1, name: display.get(k), streets: n, counties: counties.get(k) ?? 0, zipCodes: zipCount(k),
    streetsWithDirectionalInName: p1.embedded.get(k) ?? 0,
    types: Object.fromEntries(sortDesc(typesByKey.get(k) ?? new Map()).slice(0, 8)),
    topFullNames: Object.fromEntries(sortDesc(p2.fullNames.get(k)).slice(0, 8)),
  }));
  out("top-names.json", JSON.stringify(detail, null, 2));
  const summary = {
    source: `${TIGER}/FEATNAMES and ${TIGER}/ADDR`,
    generatedAt: new Date().toISOString(),
    countyFiles: featCounties.length, addrFiles: addrCounties.size,
    featnameRowsRead: p1.rowsRead, featnameRowsKept: p1.rowsKept,
    streets: p1.total, distinctBaseNames: streets.size,
    zipCodesWithAddressRanges: p2.allZips.size,
    streetsCountedFromSpelledOrdinals: p1.spelledOrdinals,
    rules: { mtfcc: [...ROAD_MTFCC], routePretypesDropped: [...ROUTE_PRETYPES], bareNumbersDropped: true, spelledOrdinalsFolded: ORDINAL_WORDS, streetIdentity: "LINEARID" },
    roadPretypesSeen: Object.fromEntries(sortDesc(p1.pretypes).slice(0, 80)),
  };
  out("summary.json", JSON.stringify(summary, null, 2));
  return { summary, detail };
};

/* ---------- main ---------- */

const main = async () => {
  const featCounties = await listDir("FEATNAMES", "featnames");
  const addrCounties = new Set(await listDir("ADDR", "addr"));
  console.log(`FEATNAMES files: ${featCounties.length}; ADDR files: ${addrCounties.size}`);
  let done = 0;
  await pool(featCounties, async (fips) => {
    await download("FEATNAMES", "featnames", fips);
    if (addrCounties.has(fips)) await download("ADDR", "addr", fips);
    if (++done % 500 === 0) console.log(`  downloaded ${done}/${featCounties.length}`);
  });

  const p1 = passOne(featCounties);
  const ranked = sortDesc(p1.streets);
  const detailKeys = new Set([...ranked.slice(0, TOP_DETAIL).map(([k]) => k), ...ALWAYS_DETAIL]);
  const exactKeys = new Set(sortDesc(p1.exact).slice(0, TOP_EXACT_DETAIL).map(([k]) => k));
  const p2 = passTwo(featCounties, addrCounties, detailKeys, exactKeys);
  const { summary, detail } = writeOutputs(p1, p2, ranked, featCounties, addrCounties);

  console.log(JSON.stringify({ ...summary, rules: undefined, roadPretypesSeen: undefined }, null, 2));
  console.log("Top 25:", detail.slice(0, 25).map((d) => `${d.name} ${d.streets}`).join(", "));
};

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
