#!/usr/bin/env node
/**
 * Most common city and town names in the United States, counted from the
 * Census Bureau's 2025 Gazetteer places file, with the USGS GNIS populated-
 * places file as a second measure.
 *
 * Reproduces every number in https://fakenamely.com/blog/most-common-city-names
 *
 * Requires Node 18+ and the `unzip` and `curl` commands. About 7.5 MB of
 * downloads, cached in --cache so a second run reads from disk. A run takes
 * a few seconds.
 *
 *   node most-common-city-names.mjs --cache ./city-names --out ./out
 *
 * Inputs:
 *   Census Gazetteer 2025, places, national file: one row per incorporated
 *     place and census designated place (CDP) in the 50 states, DC and Puerto
 *     Rico. NAME carries the legal/statistical descriptor ("Abbeville city",
 *     "Abanda CDP"); LSAD says which descriptor, FUNCSTAT whether the place is
 *     an active government (A, B), inactive (I), nonfunctioning (N), a
 *     statistical entity (S) or a fictitious "(balance)" record (F).
 *   USGS GNIS, Populated Places topical file (domestic names): one row per
 *     named populated place, including unincorporated communities and
 *     neighbourhoods, which is why its counts run far higher.
 *
 * Three counts per name, each answering a different question:
 *   incorporated  Gazetteer places with FUNCSTAT A or B: cities, towns,
 *                 villages and boroughs with an active government. The
 *                 closest thing to "how many cities are called X".
 *   all_places    every Gazetteer row, so CDPs and Puerto Rico's comunidades
 *                 and zonas urbanas too. "How many places does the Census
 *                 publish statistics for under this name."
 *   gnis          GNIS populated places with exactly this feature name, in
 *                 the 50 states and DC. "How many communities are called X."
 *
 * A base name is the NAME with its LSAD descriptor and any "(balance)" removed,
 * plus the word "Town" dropped from the 13 Massachusetts "X Town city" entries.
 * Nothing else is normalised: Saint and St., and Mount and Mt., stay distinct,
 * because the Census writes each place the way the place writes itself.
 *
 * Outputs:
 *   us-city-names-2025.csv            the 300 most common base names, by incorporated count
 *   us-city-names-2025-gnis.csv       the 100 most common GNIS populated-place names
 *   us-city-names-2025-by-state.csv   the three most repeated base names in each state
 *   us-city-names-2025-patterns.csv   how names are built: -ville, -ton, New, Lake, Saint…
 *   us-city-names-2025-summary.json   totals, Springfield, presidents, the rules applied
 */
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";

const GAZ_URL = "https://www2.census.gov/geo/docs/maps-data/data/gazetteer/2025_Gazetteer/2025_Gaz_place_national.zip";
const GNIS_URL = "https://prd-tnm.s3.amazonaws.com/StagedProducts/GeographicNames/Topical/PopulatedPlaces_National_Text.zip";
const TOP = 300;
const GNIS_TOP = 100;
const STATE_TOP = 3;

// LSAD descriptors as they appear at the end of NAME (Census code list,
// "Legal/Statistical Area Description Codes and Definitions").
const LSAD_SUFFIX = {
  21: "borough", 25: "city", 37: "municipality", 43: "town", 47: "village", 53: "city and borough",
  55: "comunidad", 57: "CDP", 62: "zona urbana", CG: "consolidated government", CN: "corporation",
  MG: "metropolitan government", UC: "urban county", UG: "unified government",
};
// Descriptors that LSAD 00 rows embed in the name anyway (Georgia and
// Tennessee consolidated governments, Indianapolis and Louisville balances).
const LOOSE_SUFFIXES = ["unified government", "consolidated government", "metropolitan government", "metro government", "urban county"];
const ACTIVE = new Set(["A", "B"]);
const TERRITORIES = new Set(["PR", "GU", "VI", "AS", "MP", "UM"]);
const STATE_NAMES_TO_USPS = {};

const args = process.argv.slice(2);
const argValue = (flag, fallback) => { const i = args.indexOf(flag); return i >= 0 && args[i + 1] ? args[i + 1] : fallback; };
const CACHE = argValue("--cache", "./city-names");
const OUT = argValue("--out", "./out");
mkdirSync(CACHE, { recursive: true });
mkdirSync(OUT, { recursive: true });

const isZip = (p) => existsSync(p) && statSync(p).size > 10_000 && readFileSync(p).subarray(0, 2).toString("latin1") === "PK";
const download = (url, file) => {
  const path = join(CACHE, file);
  if (isZip(path)) return path;
  execFileSync("curl", ["-sSL", "--retry", "3", "-A", "Mozilla/5.0", "-o", path, url]);
  if (!isZip(path)) throw new Error(`Download of ${url} did not return a zip archive; try again later.`);
  return path;
};
const unzipText = (path, member) => execFileSync("unzip", ["-p", path, member], { maxBuffer: 1 << 30 }).toString("utf8").replace(/^﻿/, "");
const listZip = (path) => execFileSync("unzip", ["-Z1", path]).toString("utf8").trim().split("\n");

// ---- readers ---------------------------------------------------------------

const readGazetteer = (zip) => {
  const member = listZip(zip).find((m) => m.endsWith(".txt"));
  const [header, ...lines] = unzipText(zip, member).trim().split(/\r?\n/);
  const cols = header.split("|").map((c) => c.trim());
  return lines.map((line) => {
    const r = Object.fromEntries(line.split("|").map((v, i) => [cols[i], v.trim()]));
    return { state: r.USPS, name: r.NAME, lsad: r.LSAD, funcstat: r.FUNCSTAT, base: baseName(r.NAME, r.LSAD) };
  });
};

const baseName = (name, lsad) => {
  let n = name.replace(/\s*\(balance\)$/, "");
  const suffix = LSAD_SUFFIX[lsad];
  if (suffix && n.toLowerCase().endsWith(" " + suffix.toLowerCase())) n = n.slice(0, -suffix.length - 1);
  for (const s of LOOSE_SUFFIXES) if (n.toLowerCase().endsWith(" " + s)) n = n.slice(0, -s.length - 1);
  // Thirteen Massachusetts municipalities are legally cities but keep "Town"
  // in their Census name ("Franklin Town city"). The place is called Franklin,
  // so the word is dropped; it is the one normalisation this script makes.
  if (lsad === "25" && / Town$/.test(n)) n = n.slice(0, -5);
  return n.trim();
};

const readGnis = (zip) => {
  const member = listZip(zip).find((m) => m.endsWith(".txt"));
  const [header, ...lines] = unzipText(zip, member).trim().split(/\r?\n/);
  const cols = header.split("|");
  const iName = cols.indexOf("feature_name"), iClass = cols.indexOf("feature_class"), iState = cols.indexOf("state_name"), iNum = cols.indexOf("state_numeric");
  return lines.map((l) => l.split("|")).filter((c) => c[iClass] === "Populated Place")
    .map((c) => ({ name: c[iName], stateName: c[iState], stateNum: c[iNum] }));
};

// ---- helpers ---------------------------------------------------------------

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] || a[0].localeCompare(b[0]));
const csvCell = (v) => (v == null ? "" : /[",\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 pct = (part, whole) => Number(((100 * part) / whole).toFixed(1));

// ---- analysis ----------------------------------------------------------------

const main = () => {
  const places = readGazetteer(download(GAZ_URL, "2025_Gaz_place_national.zip"));
  const gnisAll = readGnis(download(GNIS_URL, "PopulatedPlaces_National_Text.zip"));
  // GNIS state_numeric 01–56 are the 50 states and DC; 60+ are territories.
  const gnis = gnisAll.filter((p) => Number(p.stateNum) <= 56);

  // Sanity: every base name should now end without a known descriptor.
  const leftovers = places.filter((p) => / (CDP|comunidad|zona urbana|municipality|government|corporation)$/.test(p.base) || /\(balance\)/.test(p.base));
  const states = places.filter((p) => !TERRITORIES.has(p.state));
  const incorporated = states.filter((p) => ACTIVE.has(p.funcstat));

  const countBy = (rows) => { const m = new Map(); for (const r of rows) bump(m, r.base ?? r.name); return m; };
  const incCount = countBy(incorporated);
  const allCount = countBy(places);
  const gnisCount = countBy(gnis);
  const statesWith = (rows, key) => { const m = new Map(); for (const r of rows) { const k = r.base ?? r.name; if (!m.has(k)) m.set(k, new Set()); m.get(k).add(r.state ?? r.stateName); } return m; };
  const incStates = statesWith(incorporated);
  const allStates = statesWith(places);

  const rankedInc = sortDesc(incCount);
  const rankedAll = sortDesc(allCount);
  const rankedGnis = sortDesc(gnisCount);
  const rankOf = (ranked) => new Map(ranked.map(([k], i) => [k, i + 1]));
  const incRank = rankOf(rankedInc), allRank = rankOf(rankedAll), gnisRank = rankOf(rankedGnis);

  out("us-city-names-2025.csv", csv(
    ["rank_incorporated", "name", "incorporated_places", "states_with_incorporated", "all_places", "rank_all_places", "gnis_populated_places", "rank_gnis"],
    rankedInc.slice(0, TOP).map(([name, n], i) => [i + 1, name, n, incStates.get(name)?.size ?? 0, allCount.get(name) ?? 0, allRank.get(name) ?? "", gnisCount.get(name) ?? 0, gnisRank.get(name) ?? ""]),
  ));
  out("us-city-names-2025-gnis.csv", csv(
    ["rank_gnis", "name", "gnis_populated_places", "states", "incorporated_places", "all_places"],
    rankedGnis.slice(0, GNIS_TOP).map(([name, n], i) => [i + 1, name, n, statesWith(gnis).get(name)?.size ?? 0, incCount.get(name) ?? 0, allCount.get(name) ?? 0]),
  ));

  const rankedIncTop20 = rankedInc.slice(0, 20).map(([n]) => n);
  // Within each state, which base names repeat (a city and a CDP, or two towns)?
  const byState = {};
  for (const p of places) { const s = (byState[p.state] ??= new Map()); bump(s, p.base); }
  const stateRows = [];
  for (const [state, m] of Object.entries(byState).sort()) {
    const top = sortDesc(m).slice(0, STATE_TOP);
    const totalInc = incorporated.filter((p) => p.state === state).length;
    const totalAll = places.filter((p) => p.state === state).length;
    const top20Here = rankedIncTop20.filter((name) => incorporated.some((p) => p.state === state && p.base === name));
    top.forEach(([name, n], i) => stateRows.push([state, i + 1, name, n, totalAll, totalInc, top20Here.length, top20Here.join("; ")]));
  }
  out("us-city-names-2025-by-state.csv", csv(["state", "rank_in_state", "name", "places_in_state_with_name", "all_places_in_state", "incorporated_places_in_state", "national_top20_names_present", "which_top20_names"], stateRows));

  // Name patterns, on incorporated places.
  const patterns = [
    ["ends in -ville", /ville$/], ["ends in -ton", /ton$/], ["ends in -burg or -burgh", /burgh?$/], ["ends in -field", /field$/],
    ["ends in -wood", /wood$/], ["ends in -land", /land$/], ["ends in -port", /port$/], ["ends in -ford", /ford$/],
    ["ends in City", / City$/], ["ends in Heights", / Heights$/], ["ends in Park", / Park$/], ["ends in Springs", / Springs$/],
    ["ends in Beach", / Beach$/], ["ends in Falls", / Falls$/], ["ends in Hill or Hills", / Hills?$/],
    ["starts with New", /^New /], ["starts with Lake", /^Lake /], ["starts with Mount or Mt.", /^(Mount|Mt\.?) /],
    ["starts with Saint or St.", /^(Saint|St\.?) /], ["starts with Fort or Ft.", /^(Fort|Ft\.?) /],
    ["starts with North, South, East or West", /^(North|South|East|West) /], ["starts with Port", /^Port /],
    ["contains a hyphen", /-/], ["one word", /^[^\s]+$/],
  ];
  out("us-city-names-2025-patterns.csv", csv(
    ["pattern", "incorporated_places", "share_of_incorporated_pct", "all_places", "share_of_all_pct", "example"],
    patterns.map(([label, re]) => {
      const inc = incorporated.filter((p) => re.test(p.base)); const all = places.filter((p) => re.test(p.base));
      const ex = sortDesc(countBy(inc))[0]?.[0] ?? "";
      return [label, inc.length, pct(inc.length, incorporated.length), all.length, pct(all.length, places.length), ex];
    }),
  ));

  const detail = (name) => ({
    name, incorporated: incCount.get(name) ?? 0, incorporatedStates: [...(incStates.get(name) ?? [])].sort(),
    allPlaces: allCount.get(name) ?? 0, gnis: gnisCount.get(name) ?? 0,
  });
  const PRESIDENTS = ["Washington", "Jefferson", "Madison", "Monroe", "Jackson", "Lincoln", "Cleveland", "Harrison", "Grant", "Garfield", "Hayes", "Polk", "Taylor", "Tyler", "Adams", "Wilson", "Fillmore", "Pierce", "Buchanan", "Johnson", "Arthur", "McKinley", "Roosevelt", "Taft", "Harding", "Coolidge", "Hoover", "Truman", "Kennedy", "Carter", "Reagan", "Clinton", "Franklin", "Hamilton", "Lafayette", "Columbus"];
  const springfieldRows = places.filter((p) => /^Springfield\b/.test(p.base)).map((p) => ({ state: p.state, name: p.name, funcstat: p.funcstat }));
  const presenceByState = {};
  for (const s of [...new Set(incorporated.map((p) => p.state))].sort()) {
    presenceByState[s] = rankedIncTop20.filter((n) => incorporated.some((p) => p.state === s && p.base === n));
  }

  const summary = {
    generatedFrom: { gazetteer: GAZ_URL, gnis: GNIS_URL },
    gazetteerRows: places.length,
    gazetteerRowsStatesAndDC: states.length,
    incorporatedActive: incorporated.length,
    excludedInactiveOrNonfunctioning: states.filter((p) => ["I", "N"].includes(p.funcstat)).length,
    excludedBalanceRecords: states.filter((p) => p.funcstat === "F").length,
    cdps: places.filter((p) => p.lsad === "57").length,
    puertoRicoPlaces: places.filter((p) => p.state === "PR").length,
    uniqueBaseNamesIncorporated: incCount.size,
    uniqueBaseNamesAll: allCount.size,
    gnisPopulatedPlacesStatesAndDC: gnis.length,
    gnisUniqueNames: gnisCount.size,
    leftoverDescriptors: leftovers.map((p) => p.name),
    top20Incorporated: rankedInc.slice(0, 20).map(([n, c]) => detail(n)),
    top20AllPlaces: rankedAll.slice(0, 20).map(([n, c]) => ({ name: n, allPlaces: c, incorporated: incCount.get(n) ?? 0 })),
    top20Gnis: rankedGnis.slice(0, 20).map(([n, c]) => ({ name: n, gnis: c, incorporated: incCount.get(n) ?? 0 })),
    springfield: { ...detail("Springfield"), rows: springfieldRows },
    presidentsAndFounders: PRESIDENTS.map(detail).sort((a, b) => b.incorporated - a.incorporated),
    uniqueNameShare: { incorporatedNamesUsedOnce: [...incCount.values()].filter((v) => v === 1).length, allNamesUsedOnce: [...allCount.values()].filter((v) => v === 1).length },
    top20PresenceByState: presenceByState,
  };
  out("us-city-names-2025-summary.json", JSON.stringify(summary, null, 2) + "\n");
  process.stdout.write(`Wrote 5 files to ${OUT}: ${places.length} Gazetteer places, ${incorporated.length} active incorporated, ${gnis.length} GNIS populated places.\n`);
};

main();
