#!/usr/bin/env python3 -I
"""
Build the canonical CENTS district roster and enrich it with federal indicators.

  .venv-analysis/bin/python -I scripts/enrich_districts.py            # uses the on-disk API cache
  .venv-analysis/bin/python -I scripts/enrich_districts.py --refresh  # re-fetches every endpoint

Roster (primary files only, nothing invented):
  North Carolina  lib/tracker/records.json + story/data/districts.json (LEAID, reply text, K-8 ADM)
  12 other states data/outreach/sent-log.csv (who was asked, when) + lib/district-trackers/data/*.json (status)
A reply is recorded only when a primary record says so. A district with no tracker row has reply_status
"not_reviewed" (replied = null), never "no". Awaiting rows are "no reply on file", not "refused".

Federal layers, Urban Institute Education Data Portal (https://educationdata.urban.org/api/v1/):
  school-districts/ccd/directory/{year}   locale, enrollment, name  (LEAID matching)
  school-districts/ccd/enrollment/{year}/grade-{g}  K-8 headcount;  .../grade-99/race  composition
  school-districts/saipe/{year}           Census SAIPE child poverty 5-17
  school-districts/ccd/finance/{year}     NCES/Census F-33 (negative codes = missing -> null)
Not available at district level from these endpoints, so null and listed in the manifest gaps:
  Title I status, economically-disadvantaged share.

Outputs: data/processed/districts_enriched.{json,csv}, data/processed/enrichment_manifest.json,
         data/audit/unmatched_leaids.csv
"""
import csv, difflib, hashlib, io, json, re, sys, time, urllib.request
from collections import defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
API = 'https://educationdata.urban.org/api/v1/'
CACHE = ROOT / '.cache' / 'urban'
OUT = ROOT / 'data' / 'processed'
AUDIT = ROOT / 'data' / 'audit'
REFRESH = '--refresh' in sys.argv
FIPS = {'NC': 37, 'FL': 12, 'MS': 28, 'TX': 48, 'CT': 9, 'GA': 13, 'MD': 24, 'SC': 45, 'LA': 22, 'OH': 39, 'MI': 26, 'WI': 55, 'IN': 18}
STATES = list(FIPS)
used = {}   # endpoint url -> sha256 of the canonical response body


def sha(b):
    return hashlib.sha256(b).hexdigest()


def fetch_all(path, **q):
    url = API + path + '/?' + '&'.join(f'{k}={v}' for k, v in q.items()) + '&limit=10000'
    key = CACHE / (sha(url.encode())[:20] + '.json')
    if key.exists() and not REFRESH:
        rows = json.loads(key.read_text())
    else:
        rows, nxt = [], url
        while nxt:
            for attempt in range(5):
                try:
                    with urllib.request.urlopen(nxt, timeout=120) as r:
                        page = json.load(r)
                    break
                except Exception:
                    if attempt == 4:
                        raise
                    time.sleep(2 * (attempt + 1))
            rows += page['results']
            nxt = page.get('next')
        CACHE.mkdir(parents=True, exist_ok=True)
        key.write_text(json.dumps(rows, separators=(',', ':')))
    body = json.dumps(rows, sort_keys=True, separators=(',', ':')).encode()
    used[url] = {'rows': len(rows), 'sha256': sha(body)}
    return rows


def download(url, binary=False):
    """Cache a public file (Census / FDIC) and record its checksum in the manifest."""
    key = CACHE / ('dl_' + sha(url.encode())[:20])
    if key.exists() and not REFRESH:
        raw = key.read_bytes()
    else:
        for attempt in range(5):
            try:
                with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'research-script'}), timeout=180) as r:
                    raw = r.read()
                break
            except Exception:
                if attempt == 4:
                    raise
                time.sleep(2 * (attempt + 1))
        CACHE.mkdir(parents=True, exist_ok=True)
        key.write_bytes(raw)
    used[url] = {'bytes': len(raw), 'sha256': sha(raw)}
    return raw if binary else raw.decode('latin-1')


def fdic_branches(state_abbrs, year):
    """Branch counts per county from the FDIC Summary of Deposits (public API, no key)."""
    counts = defaultdict(int)
    for ab in state_abbrs:
        off = 0
        while True:
            url = f'https://api.fdic.gov/banks/sod?filters=STALPBR%3A{ab}%20AND%20YEAR%3A{year}&fields=STCNTYBR&limit=10000&offset={off}'
            body = json.loads(download(url))
            rows = body['data']
            for r in rows:
                counts[str(r['data']['STCNTYBR']).zfill(5)] += 1
            off += len(rows)
            if not rows or off >= body['meta']['total']:
                break
    return counts


def latest(path, years, **q):
    for y in years:
        rows = fetch_all(f'{path}/{y}', **q)
        if rows:
            return y, rows
    raise SystemExit(f'no data for {path} in {years}')


# ---------------------------------------------------------------- names
SUFFIX = re.compile(r'\b(county|parish|public schools?|school district|schools?|independent|consolidated|community|unified|'
                    r'isd|cisd|usd|csd|c i s d|i s d|district|city|board of education|regional|township|town of|corporation|'
                    r'public|the|of|system|municipal|separate|exempted|local|village|area|agricultural|consolidated|special)\b')


ABBR = {'cons': 'consolidated', 'consol': 'consolidated', 'dist': 'district', 'cty': 'county', 'co': 'county', 'sch': 'school',
        'schs': 'schools', 'schl': 'school', 'mun': 'municipal', 'sep': 'separate', 'st': 'saint', 'ind': 'independent', 'sd': 'school district',
        'corp': 'corporation', 'comm': 'community', 'cmty': 'community', 'pub': 'public', 'ex': 'exempted', 'vlg': 'village', 'twp': 'township'}


def norm(s):
    s = s.lower().replace('&', ' and ').replace('-', ' ').replace("'", '')
    s = re.sub(r'[^a-z0-9 ]', ' ', s)
    return re.sub(r'\s+', ' ', ' '.join(ABBR.get(w, w) for w in s.split())).strip()


TYPES = {'city', 'local', 'county', 'exempted', 'village', 'independent', 'consolidated', 'municipal', 'special', 'separate', 'agricultural'}


def types(s):
    return {w for w in norm(s).split() if w in TYPES}


def core(s):
    s = norm(s)
    s = SUFFIX.sub(' ', s)
    return re.sub(r'\s+', ' ', s).strip()


# ---------------------------------------------------------------- roster
def build_roster():
    rows = []
    story = json.load(open(ROOT / 'story/data/districts.json'))
    story = story if isinstance(story, list) else story['districts']
    for s in story:   # NC: the story build is the audited census (reply text checked against response.md)
        resp = s['group'] != 'no_reply'
        rows.append({
            'state': 'NC', 'name': s['name'], 'slug': s['slug'], 'leaid_primary': str(s['leaid']).zfill(7), 'delivered': True,
            'request_date': s['request_date'], 'reply_date': s['reply_date'] if resp else None,
            'tracker_status': s['code'], 'outreach_status': s['code'], 'reply_status': 'replied' if resp else 'no_reply_on_file',
            'k8_program': {'no_dedicated_course': 'none', 'optional_or_partial': 'partial', 'unclear': 'unclear', 'in_progress': 'pending'}.get(s['group']),
            'reply_text': s.get('reply_text') if resp else None, 'k8_ncdpi_adm': s.get('k8_membership'),
            'follow_up_date': s.get('follow_up_date') or None, 'reply_review_through': '2026-10-11',
        })
    sent = sorted(csv.DictReader(open(ROOT / 'data/outreach/sent-log.csv')), key=lambda r: r['status'] != 'sent')  # prefer a delivered row over a bounce
    trackers = {}
    for st in STATES:
        p = ROOT / 'lib/district-trackers/data' / f'{st.lower()}.json'
        if st != 'NC' and p.exists():
            trackers[st] = {norm(x['name']): x for x in json.load(open(p))}
    # Same rules as lib/district-trackers/sent-log.ts: same-name districts with different recipient domains are different
    # districts; a district whose only request bounced was not contacted and is left out (listed in the manifest).
    domains = defaultdict(set)
    for r in sent:
        if r['status'] == 'sent':
            domains[(r['state'], norm(r['district']))].add(r['recipient'].split('@')[-1].lower())
    seen, bounced_only = set(), []
    for r in sent:
        st = r['state']
        dom = r['recipient'].split('@')[-1].lower()
        split = len(domains[(st, norm(r['district']))]) > 1
        key = (st, norm(r['district']), dom if split else '')
        if r['status'] != 'sent' and not domains[(st, norm(r['district']))]:
            bounced_only.append(f"{st}: {r['district']}")
            continue
        if r['status'] != 'sent' or key in seen:
            continue
        seen.add(key)
        r = dict(r, district=f"{r['district']} ({dom})" if split else r['district'], _base=r['district'], _dom=dom)
        t = trackers.get(st, {}).get(norm(r['district'].split(' (')[0] if split else r['district']))
        status = t['status'] if t else None
        replied = None if t is None else (status not in ('awaiting_response',))
        rows.append({
            'state': st, 'name': r['district'], 'slug': None, 'leaid_primary': None, 'delivered': r['status'] == 'sent',
            'request_date': r['sent_at_utc'][:10], 'reply_date': (t or {}).get('replyDate'), 'tracker_status': status,
            'outreach_status': status, 'reply_status': 'not_reviewed' if t is None else ('replied' if replied else 'no_reply_on_file'),
            'k8_program': {'confirmed_not_implementing': 'none', 'unclear_or_unresponsive': 'unclear', 'response_in_progress': 'pending', 'pending_clarification': 'pending'}.get(status),
            'reply_review_through': '2026-10-29',
            'reply_text': None, 'k8_ncdpi_adm': None, 'follow_up_date': None, '_base': r['_base'], '_dom': r['_dom'],
        })
    build_roster.bounced_only = bounced_only
    return rows


def main():
    roster = build_roster()
    directory, enr, sai, fin, race = {}, defaultdict(dict), {}, {}, defaultdict(dict)
    years = {}
    for st, fp in FIPS.items():
        y, rows = latest('school-districts/ccd/directory', (2023, 2022, 2021), fips=fp)
        years['directory'] = y
        for r in rows:
            r['leaid'] = str(r['leaid']).zfill(7)
            directory[r['leaid']] = r
    def z(rows):
        for r in rows:
            r['leaid'] = str(r['leaid']).zfill(7)
        return rows
    for g in range(0, 9):
        for st, fp in FIPS.items():
            for r in z(fetch_all(f'school-districts/ccd/enrollment/{years["directory"]}/grade-{g}', fips=fp)):
                enr[r['leaid']][g] = r['enrollment'] if r['race'] == 99 and r['sex'] == 99 else enr[r['leaid']].get(g)
    for st, fp in FIPS.items():
        for r in z(fetch_all(f'school-districts/ccd/enrollment/{years["directory"]}/grade-99/race', fips=fp)):
            if r['sex'] == 99:
                race[r['leaid']][r['race']] = r['enrollment']
        y, rows = latest('school-districts/saipe', (2023, 2022, 2021), fips=fp)
        years['saipe'] = y
        sai.update({r['leaid']: r for r in z(rows)})
        y, rows = latest('school-districts/ccd/finance', (2022, 2021, 2020, 2019), fips=fp)
        years['finance'] = y
        fin.update({r['leaid']: r for r in z(rows)})

    # ----- EdFacts grade 8 mathematics proficiency (latest year with data; suppressed values are negative codes)
    math8, math_year = {}, None
    for y in (2018, 2017, 2016):
        got = {}
        for st, fp in FIPS.items():
            for r in z(fetch_all(f'school-districts/edfacts/assessments/{y}/grade-8', fips=fp)):
                if all(r.get(k) == 99 for k in ('race', 'sex', 'lep', 'homeless', 'migrant', 'disability', 'foster_care', 'military_connected', 'econ_disadvantaged')):
                    got[r['leaid']] = r
        if got:
            math8, math_year = got, y
            break
    years['edfacts_math_grade8'] = math_year
    # ----- county layers: Census SAIPE county file (median household income), Census population estimates, FDIC branch counts
    saipe_year, pop_year, fdic_year = 2023, 2023, 2024
    income, county_name = {}, {}
    for line in download(f'https://www2.census.gov/programs-surveys/saipe/datasets/{saipe_year}/{saipe_year}-state-and-county/est{str(saipe_year)[2:]}all.txt').splitlines():
        tk = line.split()
        if len(tk) > 21 and tk[1] != '0' and tk[0].isdigit():
            fips5 = tk[0].zfill(2) + tk[1].zfill(3)
            try:
                income[fips5] = float(tk[20])
            except ValueError:
                pass
    pop = {}
    for r in csv.DictReader(io.StringIO(download('https://www2.census.gov/programs-surveys/popest/datasets/2020-2024/counties/totals/co-est2024-alldata.csv'))):
        if r['COUNTY'] != '000':
            pop[r['STATE'].zfill(2) + r['COUNTY'].zfill(3)] = float(r[f'POPESTIMATE{pop_year}'])
    branches = fdic_branches(list(FIPS), fdic_year)
    years.update({'county_income_saipe': saipe_year, 'county_population_popest': pop_year, 'fdic_sod_branches': fdic_year})
    county = {}
    for c5 in {str(d.get('county_code')).zfill(5) for d in directory.values() if d.get('fips') in FIPS.values() and d.get('county_code')}:
        n_ = pop.get(c5)
        county[c5] = {'income': income.get(c5), 'branches_per_10k': (10000 * branches.get(c5, 0) / n_) if n_ else None, 'branches': branches.get(c5, 0)}
    inc_vals = sorted(v['income'] for v in county.values() if v['income'])
    bra_vals = sorted(v['branches_per_10k'] for v in county.values() if v['branches_per_10k'] is not None)
    q1 = lambda xs: xs[int(0.25 * (len(xs) - 1))]
    cut_inc, cut_bra = q1(inc_vals), q1(bra_vals)

    # ----- LEAID matching
    by_state = defaultdict(list)
    for leaid, d in directory.items():
        if d.get('agency_type') in (1, 2, 3):   # regular, supervisory union, state-operated components; charters excluded
            by_state[d['fips']].append(d)
    overrides = {}
    for o in csv.DictReader(open(ROOT / 'data/audit/manual_leaid_overrides.csv')):
        if o['nces_leaid']:
            overrides[(o['state'], o['district_name'], o['email_domain'])] = o
    unmatched, stats = [], defaultdict(lambda: defaultdict(int))
    for r in roster:
        fp = FIPS[r['state']]
        cands = by_state[fp]
        match, how = None, None
        ov = overrides.get((r['state'], r.get('_base'), r.get('_dom')))
        if ov:
            d = directory.get(ov['nces_leaid'].zfill(7))
            if not d or d['fips'] != fp:
                raise SystemExit(f"override {ov} does not resolve to a {r['state']} LEA in the directory")
            match, how = d, 'manual_override'
        if not match and r['leaid_primary']:
            d = directory.get(r['leaid_primary'])
            if d and d['fips'] == fp:
                match, how = d, 'primary_leaid'
        if not match:
            n = norm(r['name'])
            ex = [d for d in cands if norm(d['lea_name']) == n]
            if len(ex) == 1:
                match, how = ex[0], 'exact'
            if not match:
                c = core(r['name'])
                ex = [d for d in cands if core(d['lea_name']) == c and c]
                if len(ex) == 1:
                    match, how = ex[0], 'core'
                elif len(ex) > 1 and len([d for d in ex if types(d['lea_name']) == types(r['name'])]) == 1:
                    match, how = [d for d in ex if types(d['lea_name']) == types(r['name'])][0], 'core+type'
                elif len(ex) > 1:
                    unmatched.append((r, 'ambiguous_core', ';'.join(d['leaid'] for d in ex)))
                    continue
            if not match:
                names = {core(d['lea_name']): d for d in cands}
                best = difflib.get_close_matches(core(r['name']), list(names), n=2, cutoff=0.90)
                if len(best) == 1 or (len(best) == 2 and difflib.SequenceMatcher(None, core(r['name']), best[0]).ratio() - difflib.SequenceMatcher(None, core(r['name']), best[1]).ratio() > 0.05):
                    match, how = names[best[0]], 'fuzzy'
                else:
                    unmatched.append((r, 'no_match', ''))
                    continue
        r['_m'] = match
        r['match_method'] = how
        stats[r['state']][how] += 1
    # a LEAID may only be claimed by one roster row
    claimed = defaultdict(list)
    for r in roster:
        if r.get('_m'):
            claimed[r['_m']['leaid']].append(r)
    for leaid, rs in claimed.items():
        if len(rs) > 1:
            for r in rs:
                unmatched.append((r, 'leaid_claimed_twice', leaid))
                r.pop('_m')

    LOC = {1: 'City', 2: 'Suburb', 3: 'Town', 4: 'Rural'}
    RACE = {1: 'white', 2: 'black', 3: 'hispanic', 4: 'asian', 5: 'aian', 6: 'nhpi', 7: 'two_or_more'}
    def pos(v):
        return v if isinstance(v, (int, float)) and v >= 0 else None

    out = []
    for r in roster:
        d = r.pop('_m', None)
        o = {k: v for k, v in r.items() if k not in ('leaid_primary', '_base', '_dom')}
        o['leaid'] = d['leaid'] if d else None
        o['match_method'] = r.get('match_method')
        o['fips'] = FIPS[r['state']]
        if d:
            lid = d['leaid']
            loc = d.get('urban_centric_locale')
            o['locale_type'] = LOC.get(loc // 10) if isinstance(loc, int) and loc > 0 else None
            o['total_enrollment'] = pos(d.get('enrollment'))
            c5 = str(d.get('county_code') or '').zfill(5) if d.get('county_code') else None
            o['county_fips'] = c5
            mm = math8.get(lid)
            o['math8_proficiency_pct'] = mm['math_test_pct_prof_midpt'] if mm and pos(mm.get('math_test_pct_prof_midpt')) is not None else None
            o['math8_students_tested'] = pos(mm.get('math_test_num_valid')) if mm else None
            cc = county.get(c5) if c5 else None
            o['county_median_hh_income'] = cc['income'] if cc else None
            o['county_bank_branches_per_10k'] = round(cc['branches_per_10k'], 2) if cc and cc['branches_per_10k'] is not None else None
            lowi = None if not cc or not cc['income'] else cc['income'] <= cut_inc
            lowb = None if not cc or cc['branches_per_10k'] is None else cc['branches_per_10k'] <= cut_bra
            o['low_income_county'] = lowi
            o['low_bank_access_county'] = lowb
            o['financial_vulnerability_flags'] = None if lowi is None or lowb is None else int(lowi) + int(lowb)
            o['office_phone'] = d.get('phone') or None
            o['office_address'] = ', '.join(x for x in [d.get('street_mailing'), d.get('city_mailing'), d.get('state_mailing'), str(d.get('zip_mailing') or '')] if x) or None
            o['office_zips'] = sorted({str(z)[:5] for z in (d.get('zip_mailing'), d.get('zip_location')) if z})
            gr = enr.get(lid, {})
            vals = [gr.get(g) for g in range(0, 9)]
            o['k8_enrollment_ccd'] = sum(v for v in vals if isinstance(v, int) and v >= 0) if all(isinstance(v, int) and v >= 0 for v in vals if v is not None) and any(v is not None for v in vals) else None
            s = sai.get(lid)
            o['child_poverty_pct'] = round(100 * s['est_population_5_17_poverty_pct'], 2) if s and pos(s.get('est_population_5_17_poverty_pct')) is not None else None
            f = fin.get(lid, {})
            inst, rev, e = pos(f.get('exp_current_instruction_total')), pos(f.get('rev_total')), pos(f.get('enrollment_fall_responsible'))
            o['instruction_spend_per_pupil'] = round(inst / e, 2) if inst and e else None
            o['revenue_per_pupil'] = round(rev / e, 2) if rev and e else None
            tot = pos(race.get(lid, {}).get(99))
            for code, nm in RACE.items():
                v = pos(race.get(lid, {}).get(code))
                o[f'pct_{nm}'] = round(100 * v / tot, 2) if tot and v is not None else None
        else:
            o['office_phone'] = o['office_address'] = None
            for k in ('county_fips', 'math8_proficiency_pct', 'math8_students_tested', 'county_median_hh_income', 'county_bank_branches_per_10k', 'low_income_county', 'low_bank_access_county', 'financial_vulnerability_flags'):
                o[k] = None
            o['office_zips'] = []
            for k in ('locale_type', 'total_enrollment', 'k8_enrollment_ccd', 'child_poverty_pct', 'instruction_spend_per_pupil', 'revenue_per_pupil'):
                o[k] = None
            for nm in RACE.values():
                o[f'pct_{nm}'] = None
        # K-8 headcount used for weighting: CCD for everyone; NCDPI ADM kept alongside for NC
        o['k8_enrollment'] = o['k8_enrollment_ccd']
        out.append(o)
    out.sort(key=lambda o: (o['state'], o['name']))

    OUT.mkdir(parents=True, exist_ok=True)
    AUDIT.mkdir(parents=True, exist_ok=True)
    cols = ['reply_review_through', 'state', 'fips', 'leaid', 'match_method', 'name', 'slug', 'delivered', 'request_date', 'follow_up_date', 'reply_date', 'reply_status',
            'tracker_status', 'k8_program', 'locale_type', 'total_enrollment', 'k8_enrollment', 'k8_ncdpi_adm', 'child_poverty_pct',
            'instruction_spend_per_pupil', 'revenue_per_pupil', 'math8_proficiency_pct', 'math8_students_tested', 'county_fips', 'county_median_hh_income', 'county_bank_branches_per_10k', 'low_income_county', 'low_bank_access_county', 'financial_vulnerability_flags', 'office_phone', 'office_address'] + [f'pct_{n}' for n in RACE.values()]
    dead = [c for c in cols if all(o.get(c) in (None, '') for o in out)]   # no dead columns in public exports
    cols = [c for c in cols if c not in dead]
    with open(OUT / 'districts_enriched.csv', 'w', newline='') as fh:
        w = csv.DictWriter(fh, cols, extrasaction='ignore')
        w.writeheader()
        w.writerows([{**o, 'office_address': o.get('office_address')} for o in out])
    (OUT / 'districts_enriched.json').write_text(json.dumps(out, indent=1, ensure_ascii=False))
    with open(AUDIT / 'unmatched_leaids.csv', 'w', newline='') as fh:
        w = csv.writer(fh)
        w.writerow(['state', 'district', 'reason', 'candidate_leaids'])
        for r, why, c in sorted(unmatched, key=lambda x: (x[0]['state'], x[0]['name'])):
            w.writerow([r['state'], r['name'], why, c])

    def rate(f):
        n = sum(1 for o in out if f(o))
        return n, round(n / len(out), 4)
    per_state = {}
    for st in STATES:
        rows_ = [o for o in out if o['state'] == st]
        per_state[st] = {'districts': len(rows_), 'matched': sum(1 for o in rows_ if o['leaid']),
                         'with_k8_enrollment': sum(1 for o in rows_ if o['k8_enrollment'] is not None),
                         'with_poverty': sum(1 for o in rows_ if o['child_poverty_pct'] is not None),
                         'with_spending': sum(1 for o in rows_ if o['instruction_spend_per_pupil'] is not None)}
    # second source: state course records (parsed if a file is on disk; otherwise recorded as a gap)
    import importlib.util
    spec = importlib.util.spec_from_file_location('ingest_course_records', ROOT / 'scripts/ingest_course_records.py')
    ingest = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(ingest)
    course = ingest.build()
    manifest = {
        'script': 'scripts/enrich_districts.py', 'api_base': API, 'years': years, 'k8_definition': 'CCD enrollment grades KG through 8, race=99, sex=99 (Pre-K excluded)',
        'roster_inputs': {p: sha((ROOT / p).read_bytes()) for p in ['lib/tracker/records.json', 'story/data/districts.json', 'data/outreach/sent-log.csv'] +
                          [f'lib/district-trackers/data/{s.lower()}.json' for s in STATES if s != 'NC']},
        'roster_rows': len(out), 'match_rate': {'matched': rate(lambda o: o['leaid'])[0], 'share': rate(lambda o: o['leaid'])[1]},
        'match_methods': {s: dict(v) for s, v in stats.items()}, 'per_state': per_state, 'unmatched_logged': len(unmatched), 'bounced_only_excluded': build_roster.bounced_only,
        'primary_socioeconomic_measure': 'Census SAIPE est_population_5_17_poverty_pct (child poverty, ages 5-17), via school-districts/saipe',
        'dropped_empty_columns': dead,
        'external_outcomes': {'math8': 'EdFacts grade 8 mathematics, % proficient (midpoint), Urban Institute edfacts/assessments, total population rows; vintage differs from the 2023 CCD layers',
                              'county': 'SAIPE county median household income, Census population estimates, FDIC Summary of Deposits branch counts (branches per 10,000 residents)',
                              'vulnerability_cutoffs': {'low_income_county': f'county median household income <= {cut_inc:.0f} (bottom quartile of counties containing an audited district)', 'low_bank_access_county': f'branches per 10,000 residents <= {cut_bra:.2f} (bottom quartile of the same counties)'}},
        'gaps': ['SNAP participation and the Census keyed APIs were not used: no keyless public source was reachable, so they are absent rather than estimated',
                 'FDIC branch density is a proxy for physical bank access; it ignores online and credit-union access','Title I status and economically-disadvantaged share are not district-level fields in the CCD endpoints used; they are not in the export, and SAIPE child poverty is the socioeconomic measure',
                 'Finance year is the latest the API returns for all states; negative F-33 codes treated as missing',
                 'Reply review: districts with no tracker row are reply_status=not_reviewed (replied unknown)'],
        'state_course_records': {k: course[k] for k in ('available', 'status', 'schema', 'expected_file', 'course_code_prefixes', 'districts_in_scope')},
        'endpoints': used,
        'outputs': {},
    }
    for p in ['data/processed/districts_enriched.json', 'data/processed/districts_enriched.csv', 'data/audit/unmatched_leaids.csv', 'data/processed/nc_course_records.json']:
        manifest['outputs'][p] = sha((ROOT / p).read_bytes())
    # deterministic release id: hash of every input and output checksum (no timestamps)
    manifest['release_id'] = 'cents-analysis-' + sha(json.dumps([manifest['roster_inputs'], manifest['outputs'], manifest['years']], sort_keys=True).encode())[:12]
    (OUT / 'enrichment_manifest.json').write_text(json.dumps(manifest, indent=1))
    print(f'roster {len(out)}  matched {manifest["match_rate"]}  unmatched logged {len(unmatched)}')
    for st, v in per_state.items():
        print(st, v)


if __name__ == '__main__':
    main()
