#!/usr/bin/env python3
"""
analyze.py - Portland crawl space homes report: the whole analysis, from the
Census Bureau's files to the JSON the site page reads.

WHAT IT PRODUCES
  site/src/data/crawlSpaceHomes.json   every figure on /data/portland-crawl-space-homes/
  raw/ahs2019m-portland-sf.csv.gz      the Portland records the 2019 figures rest on
  raw/ahs2015m-portland-sf.csv.gz      the Portland records for the 2015 check
  raw/acs2023-b25127-msa-counties.csv  the seven county rows of ACS table B25127
  raw/downloads.json                   URL, size, SHA-256 and date of every file read

HOW TO RUN (from this folder)
  python3 -I analyze.py                 download what is missing, recompute everything
  python3 -I analyze.py --check         recompute the Portland figures from raw/ only
                                        and confirm they match the published JSON
  python3 -I analyze.py --cache DIR     keep the large Census downloads in DIR
                                        (default: .cache/ here, which git ignores)

Standard library only. The national file is about 1 GB unzipped and is read
straight out of its zip, so nothing that size is written to disk.

METHOD IN ONE PARAGRAPH
Universe: occupied one-family homes, detached or attached (AHS BLD 02 or 03,
INTSTATUS 1), with a reported foundation type. Every share is a weighted ratio
using WEIGHT. Every margin is a 90 percent margin from the 160 replicate weights,
as the Census Bureau's "Quick Guide to Estimating Variance Using Replicate
Weights" sets out: variance = 4/160 x sum over replicates of (replicate estimate
minus full-sample estimate) squared; margin = 1.645 x the square root. Differences
are computed replicate by replicate within one sample, so their margins carry the
correlation between the two figures. Comparisons across two different samples
(Portland, from the metropolitan sample, against the US or Seattle, from the
national sample) treat the samples as independent.

THE ESTIMATE THAT IS NOT A MEASUREMENT
County figures are ESTIMATES. The AHS has no county field in its public file, so
the county numbers apply the metro-wide crawl space share for each build era to
each county's count of occupied single-family homes in that era (ACS 2019-2023
table B25127). That assumes a home built in, say, the 1970s is as likely to sit on
a crawl space in Clark County as anywhere else in the metro, which nothing here can
test. Homes built in 2020 or later are counted but not estimated: the 2019 survey
saw none of them, and new construction in the region has moved away from crawl
spaces. The page labels every one of these numbers as an estimate.
"""

from __future__ import annotations

import argparse
import csv
import datetime as dt
import gzip
import hashlib
import io
import json
import math
import os
import sys
import urllib.request
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, '..', '..', '..', '..'))
RAW = os.path.join(HERE, 'raw')
OUT_JSON = os.path.join(REPO, 'site', 'src', 'data', 'crawlSpaceHomes.json')

AHS = 'https://www2.census.gov/programs-surveys/ahs'
DOWNLOADS = {
    'ahs2019m': f'{AHS}/2019/AHS%202019%20Metropolitan%20PUF%20v1.0%20Flat%20CSV.zip',
    'ahs2019n': f'{AHS}/2019/AHS%202019%20National%20PUF%20v1.1%20Flat%20CSV.zip',
    'ahs2015m': f'{AHS}/2015/AHS%202015%20Metropolitan%20PUF%20v3.1%20Flat%20CSV.zip',
    'acs2023b25127': 'https://www2.census.gov/programs-surveys/acs/summary_file/2023/table-based-SF/data/5YRData/acsdt5y2023-b25127.dat',
}

PORTLAND = '38900'
SEATTLE = '42660'
# Names as the AHS 2019 value labels give them (OMB13CBSA).
CBSA_NAMES = {
    '12060': 'Atlanta', '14460': 'Boston', '16980': 'Chicago', '19100': 'Dallas-Fort Worth',
    '19820': 'Detroit', '26420': 'Houston', '31080': 'Los Angeles', '33100': 'Miami',
    '35620': 'New York', '37980': 'Philadelphia', '38060': 'Phoenix', '40140': 'Riverside',
    '41860': 'San Francisco', '47900': 'Washington, DC',
    '17140': 'Cincinnati', '17460': 'Cleveland', '19740': 'Denver',
    '28140': 'Kansas City', '32820': 'Memphis', '33340': 'Milwaukee',
    '35380': 'New Orleans', '38300': 'Pittsburgh', '38900': 'Portland-Vancouver',
    '39580': 'Raleigh', '42660': 'Seattle',
}
CBSA_FULL = {
    '12060': 'Atlanta-Sandy Springs-Roswell, GA', '14460': 'Boston-Cambridge-Newton, MA-NH',
    '16980': 'Chicago-Naperville-Elgin, IL-IN-WI', '19100': 'Dallas-Fort Worth-Arlington, TX',
    '19820': 'Detroit-Warren-Dearborn, MI', '26420': 'Houston-The Woodlands-Sugar Land, TX',
    '31080': 'Los Angeles-Long Beach-Anaheim, CA', '33100': 'Miami-Fort Lauderdale-West Palm Beach, FL',
    '35620': 'New York-Newark-Jersey City, NY-NJ-PA', '37980': 'Philadelphia-Camden-Wilmington, PA-NJ-DE-MD',
    '38060': 'Phoenix-Mesa-Scottsdale, AZ', '40140': 'Riverside-San Bernardino-Ontario, CA',
    '41860': 'San Francisco-Oakland-Hayward, CA', '47900': 'Washington-Arlington-Alexandria, DC-VA-MD-WV',
    '17140': 'Cincinnati, OH-KY-IN', '17460': 'Cleveland-Elyria, OH',
    '19740': 'Denver-Aurora-Lakewood, CO', '28140': 'Kansas City, MO-KS',
    '32820': 'Memphis, TN-MS-AR', '33340': 'Milwaukee-Waukesha-West Allis, WI',
    '35380': 'New Orleans-Metairie, LA', '38300': 'Pittsburgh, PA',
    '38900': 'Portland-Vancouver-Hillsboro, OR-WA', '39580': 'Raleigh, NC',
    '42660': 'Seattle-Tacoma-Bellevue, WA',
}

# FOUNDTYPE (AHS 2019 value labels). Mobile-home codes 5-7 and 9 cannot occur
# once BLD is restricted to one-family houses; they are excluded if they do.
FOUNDATION = {'1': 'basement', '2': 'basement', '3': 'crawl', '4': 'slab', '8': 'other'}
FOUNDATION_DETAIL = {'1': 'basement_all', '2': 'basement_part', '3': 'crawl', '4': 'slab', '8': 'other'}
GROUPS = ['crawl', 'basement', 'slab', 'other']

# Build eras chosen to match the ACS B25127 year-built buckets exactly, so the
# county estimate needs no re-binning.
ERAS = [
    ('pre1940', 'Before 1940', None, 1939),
    ('1940-1959', '1940 to 1959', 1940, 1959),
    ('1960-1979', '1960 to 1979', 1960, 1979),
    ('1980-1999', '1980 to 1999', 1980, 1999),
    ('2000-2019', '2000 to 2019', 2000, 2019),
]

MOLD_VARS = ['MOLDBASEM', 'MOLDBATH', 'MOLDBEDRM', 'MOLDKITCH', 'MOLDLROOM', 'MOLDOTHER']
PROBLEMS = [
    ('leak_outside', 'Water leaked in from outside in the last 12 months', 'LEAKO'),
    ('foundation_cracks', 'Foundation has holes, cracks or crumbling', 'FNDCRUMB'),
    ('mold_any_room', 'Mold seen in any room in the last 12 months', None),
]

REP = [f'REPWEIGHT{i}' for i in range(1, 161)]
KEEP = ['CONTROL', 'OMB13CBSA', 'INTSTATUS', 'BLD', 'FOUNDTYPE', 'YRBUILT', 'TENURE',
        'LEAKO', 'FNDCRUMB', *MOLD_VARS, 'WEIGHT', *REP]

# A share is published only with this many unweighted records in its base, and
# flagged when its coefficient of variation passes CAUTION_CV.
MIN_N = 30
CAUTION_N = 50
CAUTION_CV = 0.30
Z90 = 1.645

# ACS B25127: one-family (detached or attached) occupied units by year built.
# (owner column, renter column) per era, from the table's published labels.
ACS_ERA_COLS = {
    'pre1940': ('039', '082'),
    '1940-1959': ('032', '075'),
    '1960-1979': ('025', '068'),
    '1980-1999': ('018', '061'),
    '2000-2019': ('011', '054'),
    '2020-later': ('004', '047'),
}
MSA_COUNTIES = [
    ('41005', 'Clackamas County', 'OR'),
    ('41009', 'Columbia County', 'OR'),
    ('41051', 'Multnomah County', 'OR'),
    ('41067', 'Washington County', 'OR'),
    ('41071', 'Yamhill County', 'OR'),
    ('53011', 'Clark County', 'WA'),
    ('53059', 'Skamania County', 'WA'),
]


def v(x: str) -> str:
    """AHS flat files quote coded values: '38900' -> 38900."""
    return x.strip().strip("'")


# --- downloads ---------------------------------------------------------------

def fetch(key: str, cache: str, log: dict) -> str:
    url = DOWNLOADS[key]
    name = url.rsplit('/', 1)[1].replace('%20', '_')
    path = os.path.join(cache, name)
    if not os.path.exists(path):
        print(f'  downloading {url}', file=sys.stderr)
        req = urllib.request.Request(url, headers={'User-Agent': 'data-report-analysis/1.0'})
        with urllib.request.urlopen(req, timeout=600) as r, open(path + '.part', 'wb') as f:
            while chunk := r.read(1 << 20):
                f.write(chunk)
        os.replace(path + '.part', path)
        log[key] = {'retrieved': dt.date.today().isoformat()}
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        while chunk := f.read(1 << 20):
            h.update(chunk)
    entry = log.setdefault(key, {})
    entry.update({'url': url, 'bytes': os.path.getsize(path), 'sha256': h.hexdigest()})
    entry.setdefault('retrieved', dt.date.fromtimestamp(os.path.getmtime(path)).isoformat())
    return path


def zip_rows(path: str):
    with zipfile.ZipFile(path) as z:
        member = next(n for n in z.namelist() if n.lower().endswith('.csv'))
        with z.open(member) as raw:
            yield from csv.DictReader(io.TextIOWrapper(raw, encoding='latin-1', newline=''))


# --- replicate-weight estimation ---------------------------------------------

class Acc:
    """Weighted sums under the full weight and the 160 replicates, plus a count."""
    __slots__ = ('w', 'n')

    def __init__(self):
        self.w = [0.0] * 161
        self.n = 0

    def add(self, ws):
        self.n += 1
        w = self.w
        for i in range(161):
            w[i] += ws[i]


def se_from(values):
    full = values[0]
    return math.sqrt(4 / 160 * sum((r - full) ** 2 for r in values[1:]))


def ratio_series(num: Acc, den: Acc):
    return [(num.w[i] / den.w[i]) if den.w[i] else 0.0 for i in range(161)]


def pct(num: Acc, den: Acc) -> dict:
    series = ratio_series(num, den)
    est = series[0] * 100
    se = se_from(series) * 100
    out = {'est': round(est, 1), 'moe': round(Z90 * se, 1), 'n': num.n, 'base_n': den.n}
    cv = se / est if est else None
    if den.n < MIN_N:
        out['suppressed'] = True
    elif den.n < CAUTION_N or (cv is not None and cv > CAUTION_CV):
        out['caution'] = True
    return out


def total(acc: Acc) -> dict:
    return {'est': round(acc.w[0]), 'moe': round(Z90 * se_from(acc.w)), 'n': acc.n}


def diff_pct(a_num, a_den, b_num, b_den) -> dict:
    a = ratio_series(a_num, a_den)
    b = ratio_series(b_num, b_den)
    d = [(a[i] - b[i]) * 100 for i in range(161)]
    moe = Z90 * se_from(d)
    return {'est': round(d[0], 1), 'moe': round(moe, 1), 'significant': abs(d[0]) > moe}


def diff_independent(a: dict, b: dict) -> dict:
    d = a['est'] - b['est']
    moe = math.sqrt(a['moe'] ** 2 + b['moe'] ** 2)
    return {'est': round(d, 1), 'moe': round(moe, 1), 'significant': abs(d) > moe}


def weights(row) -> list:
    return [float(row['WEIGHT'])] + [float(row[k]) for k in REP]


def in_universe(row) -> str | None:
    """Foundation group for an occupied one-family home with a reported foundation, else None."""
    if v(row['INTSTATUS']) != '1' or v(row['BLD']) not in ('02', '03'):
        return None
    return FOUNDATION.get(v(row['FOUNDTYPE']))


def era_of(yrbuilt: str) -> str | None:
    try:
        y = int(v(yrbuilt))
    except ValueError:
        return None
    for key, _label, lo, hi in ERAS:
        if (lo is None or y >= lo) and y <= hi:
            return key
    return None


def yes_no(row, var) -> bool | None:
    x = v(row.get(var, ''))
    return True if x == '1' else False if x == '2' else None


def mold_any(row) -> bool | None:
    vals = [v(row.get(m, '')) for m in MOLD_VARS]
    if any(x not in ('1', '2') for x in vals):
        return None
    return any(x == '1' for x in vals)


# --- tallies -----------------------------------------------------------------

def tally_foundation(rows, area_of):
    """{area: {'ALL': Acc, group: Acc, detail: Acc}} for occupied one-family homes.

    area_of returns one area key, several (a row can count toward Seattle and
    the US in the same pass), or None to skip the row."""
    acc: dict = {}
    for row in rows:
        g = in_universe(row)
        if g is None:
            continue
        areas = area_of(row)
        if not areas:
            continue
        if isinstance(areas, str):
            areas = (areas,)
        ws = weights(row)
        for area in areas:
            d = acc.setdefault(area, {})
            for key in ('ALL', g, 'detail:' + FOUNDATION_DETAIL[v(row['FOUNDTYPE'])]):
                d.setdefault(key, Acc()).add(ws)
    return acc


def foundation_block(d: dict) -> dict:
    allacc = d['ALL']
    shares = {g: pct(d.get(g, Acc()), allacc) for g in GROUPS}
    detail = {k.split(':', 1)[1]: pct(a, allacc) for k, a in d.items() if k.startswith('detail:')}
    crawl_homes = total(d.get('crawl', Acc()))
    return {'homes': total(allacc), 'crawlHomes': crawl_homes, 'shares': shares, 'detail': detail}


def portland_detail(rows):
    """Era, tenure and problem cross-tabs for Portland. Also returns the era replicate series."""
    era = {e[0]: {'ALL': Acc(), 'crawl': Acc()} for e in ERAS}
    era['1960-or-later'] = {'ALL': Acc(), 'crawl': Acc()}
    tenure = {t: {'ALL': Acc(), 'crawl': Acc()} for t in ('owner', 'renter')}
    prob = {p[0]: {g: {'base': Acc(), 'yes': Acc()} for g in GROUPS + ['ALL']} for p in PROBLEMS}
    for row in rows:
        g = in_universe(row)
        if g is None:
            continue
        ws = weights(row)
        e = era_of(row['YRBUILT'])
        if e:
            era[e]['ALL'].add(ws)
            if g == 'crawl':
                era[e]['crawl'].add(ws)
                # Numerator of "share of crawl space homes built 1960 or later";
                # its denominator is every crawl space home with a known year.
                era['1960-or-later']['ALL'].add(ws)
                if e not in ('pre1940', '1940-1959'):
                    era['1960-or-later']['crawl'].add(ws)
        t = {'1': 'owner', '2': 'renter'}.get(v(row['TENURE']))
        if t:
            tenure[t]['ALL'].add(ws)
            if g == 'crawl':
                tenure[t]['crawl'].add(ws)
        for key, _label, var in PROBLEMS:
            ans = mold_any(row) if var is None else yes_no(row, var)
            if ans is None:
                continue
            for grp in (g, 'ALL'):
                prob[key][grp]['base'].add(ws)
                if ans:
                    prob[key][grp]['yes'].add(ws)
    return era, tenure, prob


# --- the analysis ------------------------------------------------------------

def write_extract(rows, path):
    with gzip.open(path, 'wt', newline='', encoding='utf-8') as f:
        w = csv.writer(f)
        w.writerow(KEEP)
        n = 0
        for row in rows:
            if v(row['OMB13CBSA']) != PORTLAND or v(row['INTSTATUS']) != '1' or v(row['BLD']) not in ('02', '03'):
                continue
            w.writerow([row.get(k, '') for k in KEEP])
            n += 1
    return n


def read_extract(path):
    with gzip.open(path, 'rt', newline='', encoding='utf-8') as f:
        yield from csv.DictReader(f)


def portland_figures(rows2019):
    rows2019 = list(rows2019)
    found = tally_foundation(rows2019, lambda r: PORTLAND)[PORTLAND]
    era, tenure, prob = portland_detail(rows2019)
    return rows2019, found, era, tenure, prob


def era_table(era):
    out = []
    for key, label, _lo, _hi in ERAS:
        out.append({'era': key, 'label': label, 'homes': total(era[key]['ALL']),
                    'crawl': pct(era[key]['crawl'], era[key]['ALL'])})
    return out


def problem_table(prob):
    out = []
    for key, label, var in PROBLEMS:
        row = {'measure': key, 'label': label, 'variable': var or '+'.join(MOLD_VARS), 'byFoundation': {}}
        for g in GROUPS + ['ALL']:
            row['byFoundation'][g] = pct(prob[key][g]['yes'], prob[key][g]['base'])
        row['crawlVsBasement'] = diff_pct(prob[key]['crawl']['yes'], prob[key]['crawl']['base'],
                                          prob[key]['basement']['yes'], prob[key]['basement']['base'])
        row['crawlVsSlab'] = diff_pct(prob[key]['crawl']['yes'], prob[key]['crawl']['base'],
                                      prob[key]['slab']['yes'], prob[key]['slab']['base'])
        out.append(row)
    return out


def acs_counties(path_or_rows):
    """Seven county rows of B25127 as {fips: {era: (est, moe)}}."""
    want = {f'0500000US{f}' for f, _n, _s in MSA_COUNTIES}
    rows = {}
    if isinstance(path_or_rows, str):
        with open(path_or_rows, newline='', encoding='latin-1') as f:
            for row in csv.DictReader(f, delimiter='|'):
                if row['GEO_ID'] in want:
                    rows[row['GEO_ID'][-5:]] = row
    else:
        rows = path_or_rows
    out = {}
    for fips, row in rows.items():
        eras = {}
        for era, (own, rent) in ACS_ERA_COLS.items():
            est = int(row[f'B25127_E{own}']) + int(row[f'B25127_E{rent}'])
            moe = math.sqrt(int(row[f'B25127_M{own}']) ** 2 + int(row[f'B25127_M{rent}']) ** 2)
            eras[era] = (est, moe)
        out[fips] = eras
    return out, rows


def county_estimates(era_acc, acs):
    """Apply metro-wide era shares (with their replicates) to county era counts."""
    share_series = {k: ratio_series(era_acc[k]['crawl'], era_acc[k]['ALL']) for k, *_ in ERAS}
    results = []
    sums = [0.0] * 161
    acs_var_total = 0.0
    for fips, name, state in MSA_COUNTIES:
        eras = acs[fips]
        series = [sum(eras[k][0] * share_series[k][i] for k, *_ in ERAS) for i in range(161)]
        var_ahs = (4 / 160) * sum((s - series[0]) ** 2 for s in series[1:])
        var_acs = sum((share_series[k][0] ** 2) * (eras[k][1] / Z90) ** 2 for k, *_ in ERAS)
        acs_var_total += var_acs
        for i in range(161):
            sums[i] += series[i]
        moe = Z90 * math.sqrt(var_ahs + var_acs)
        pre2020 = sum(eras[k][0] for k, *_ in ERAS)
        pre2020_moe = math.sqrt(sum(eras[k][1] ** 2 for k, *_ in ERAS))
        est = series[0]
        results.append({
            'fips': fips, 'county': name, 'state': state,
            'singleFamilyBuiltBefore2020': {'est': pre2020, 'moe': round(pre2020_moe)},
            'singleFamilyBuilt2020OrLater': {'est': eras['2020-later'][0], 'moe': round(eras['2020-later'][1])},
            'crawlSpaceEstimate': {
                'est': round(est), 'moe': round(moe),
                'low': round(est - moe), 'high': round(est + moe),
                'shareOfBuiltBefore2020': round(100 * est / pre2020, 1) if pre2020 else None,
            },
            'isEstimate': True,
        })
    metro_var = (4 / 160) * sum((s - sums[0]) ** 2 for s in sums[1:]) + acs_var_total
    return results, {'est': round(sums[0]), 'moe': round(Z90 * math.sqrt(metro_var))}


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--cache', default=os.path.join(HERE, '.cache'))
    ap.add_argument('--check', action='store_true',
                    help='recompute Portland figures from raw/ and compare with the published JSON')
    args = ap.parse_args()

    p2019 = os.path.join(RAW, 'ahs2019m-portland-sf.csv.gz')
    p2015 = os.path.join(RAW, 'ahs2015m-portland-sf.csv.gz')
    pacs = os.path.join(RAW, 'acs2023-b25127-msa-counties.csv')

    if args.check:
        with open(OUT_JSON, encoding='utf-8') as f:
            published = json.load(f)
        _rows, found, era, tenure, prob = portland_figures(read_extract(p2019))
        with open(pacs, newline='', encoding='utf-8') as f:
            acs, _ = acs_counties({r['fips']: r for r in csv.DictReader(f)})
        counties, _metro = county_estimates(era, acs)
        fresh = {
            'portland': foundation_block(found),
            'portlandByEra': era_table(era),
            'portlandProblemsByFoundation': problem_table(prob),
            'countyEstimates': counties,
        }
        pub_portland = next(a for a in published['foundationByArea'] if a['cbsa'] == PORTLAND)
        pub = {
            'portland': {k: pub_portland[k] for k in ('homes', 'crawlHomes', 'shares', 'detail')},
            'portlandByEra': published['portlandByEra'],
            'portlandProblemsByFoundation': published['portlandProblemsByFoundation'],
            'countyEstimates': published['countyEstimates'],
        }
        ok = json.dumps(fresh, sort_keys=True) == json.dumps(pub, sort_keys=True)
        print('check:', 'Portland figures match the published JSON' if ok else 'MISMATCH')
        sys.exit(0 if ok else 1)

    os.makedirs(args.cache, exist_ok=True)
    os.makedirs(RAW, exist_ok=True)
    log_path = os.path.join(RAW, 'downloads.json')
    log = json.load(open(log_path)) if os.path.exists(log_path) else {}

    # 1. 2019 metropolitan sample: Portland and the nine other metros surveyed that year.
    path = fetch('ahs2019m', args.cache, log)
    print('reading 2019 metropolitan sample', file=sys.stderr)
    metro = tally_foundation(zip_rows(path), lambda r: v(r['OMB13CBSA']))
    n_extract = write_extract(zip_rows(path), p2019)

    # 2. 2019 national sample: the United States and Seattle.
    path = fetch('ahs2019n', args.cache, log)
    print('reading 2019 national sample (about 1 GB, a few minutes)', file=sys.stderr)
    # The national file identifies the 15 largest metros (Seattle among them);
    # every other code is 99998 (other metro) or 99999 (not in a metro).
    national = tally_foundation(zip_rows(path),
                                lambda r: ('US', v(r['OMB13CBSA'])) if v(r['OMB13CBSA']) in CBSA_FULL else 'US')
    us = national['US']

    # 3. 2015 metropolitan sample: the Portland consistency check.
    path = fetch('ahs2015m', args.cache, log)
    print('reading 2015 metropolitan sample', file=sys.stderr)
    write_extract(zip_rows(path), p2015)
    p15 = tally_foundation(read_extract(p2015), lambda r: PORTLAND)[PORTLAND]

    # 4. ACS county counts.
    path = fetch('acs2023b25127', args.cache, log)
    acs, acs_rows = acs_counties(path)
    cols = ['GEO_ID'] + [f'B25127_{t}{c}' for pair in ACS_ERA_COLS.values() for c in pair for t in ('E', 'M')]
    with open(pacs, 'w', newline='', encoding='utf-8') as f:
        w = csv.writer(f)
        w.writerow(['fips', 'county', 'state'] + cols[1:])
        for fips, name, state in MSA_COUNTIES:
            w.writerow([fips, name, state] + [acs_rows[fips][c] for c in cols[1:]])

    with open(log_path, 'w') as f:
        json.dump(log, f, indent=2, sort_keys=True)
        f.write('\n')

    # Portland detail from the extract, so --check reproduces it exactly.
    _rows, found, era, tenure, prob = portland_figures(read_extract(p2019))
    counties, metro_estimate = county_estimates(era, acs)

    areas = []
    for cbsa in sorted(metro):
        block = foundation_block(metro[cbsa] if cbsa != PORTLAND else found)
        areas.append({'cbsa': cbsa, 'area': CBSA_NAMES.get(cbsa, cbsa), 'areaFull': CBSA_FULL.get(cbsa, cbsa),
                      'sample': '2019 metropolitan', **block})
    # Metros from the national sample that the metropolitan sample does not cover.
    for cbsa in sorted(k for k in national if k != 'US' and k not in metro):
        areas.append({'cbsa': cbsa, 'area': CBSA_NAMES[cbsa], 'areaFull': CBSA_FULL[cbsa],
                      'sample': '2019 national', **foundation_block(national[cbsa])})
    areas.append({'cbsa': 'US', 'area': 'United States', 'areaFull': 'United States',
                  'sample': '2019 national', **foundation_block(us)})

    def area(c):
        return next(a for a in areas if a['cbsa'] == c)

    pdx, sea, usa = area(PORTLAND), area(SEATTLE), area('US')
    portland_2015 = foundation_block(p15)
    comparisons = [
        {'label': 'Portland-Vancouver minus United States, crawl space share',
         **diff_independent(pdx['shares']['crawl'], usa['shares']['crawl'])},
        {'label': 'Portland-Vancouver minus Seattle, crawl space share',
         **diff_independent(pdx['shares']['crawl'], sea['shares']['crawl'])},
        {'label': 'Portland-Vancouver 2019 minus 2015, crawl space share',
         **diff_independent(pdx['shares']['crawl'], portland_2015['shares']['crawl'])},
        {'label': 'Portland homes built 1980 to 1999 minus before 1940, crawl space share',
         **diff_pct(era['1980-1999']['crawl'], era['1980-1999']['ALL'], era['pre1940']['crawl'], era['pre1940']['ALL'])},
        {'label': 'Portland owner-occupied minus renter-occupied, crawl space share',
         **diff_pct(tenure['owner']['crawl'], tenure['owner']['ALL'], tenure['renter']['crawl'], tenure['renter']['ALL'])},
    ]

    result = {
        'meta': {
            'generated': dt.date.today().isoformat(),
            'script': 'docs/seo/data/crawl-space-homes/analyze.py',
            'universe': 'Occupied one-family homes, detached or attached (AHS BLD 02 or 03, INTSTATUS 1), with a reported foundation type.',
            'margins': '90 percent, from 160 replicate weights (Fay method): variance = 4/160 x sum of squared replicate deviations.',
            'minimumBaseN': MIN_N,
            'cautionRule': f'base under {CAUTION_N} records, or coefficient of variation over {CAUTION_CV}',
            'portlandRecords2019': n_extract,
            'downloads': log,
        },
        'foundationByArea': areas,
        'portland2015': portland_2015,
        'portlandByEra': era_table(era),
        'portlandCrawlHomesBuilt1960OrLater': pct(era['1960-or-later']['crawl'], era['1960-or-later']['ALL']),
        'portlandByTenure': [
            {'tenure': t, 'homes': total(tenure[t]['ALL']), 'crawl': pct(tenure[t]['crawl'], tenure[t]['ALL'])}
            for t in ('owner', 'renter')
        ],
        'portlandProblemsByFoundation': problem_table(prob),
        'comparisons': comparisons,
        'countyEstimates': counties,
        'countyEstimateMetroTotal': metro_estimate,
    }
    os.makedirs(os.path.dirname(OUT_JSON), exist_ok=True)
    with open(OUT_JSON, 'w', encoding='utf-8') as f:
        json.dump(result, f, indent=2)
        f.write('\n')
    print(f'wrote {os.path.relpath(OUT_JSON, REPO)}', file=sys.stderr)


if __name__ == '__main__':
    main()
