#!/usr/bin/env python3 -I
"""
Econometric, survival, statutory and text analysis for the CENTS district audit.

  .venv-analysis/bin/python -I scripts/run_analysis.py

Reads only: data/processed/districts_enriched.json, data/states/*.json, data/audit/foia_deadlines.csv
            (optional) data/audit/state_marker_coding.csv
Writes data/analysis/{student_weighted_impact,econometric_models,enforcement_teeth,manski_bounds,reply_similarity}.json

Rules kept: a missing reply is "not replied on file", never "no"; districts without a federal match are excluded from
weighted sums and counted, never imputed; every number below is computed here from the input files.
"""
import csv, glob, json, math, re
from collections import Counter, defaultdict
from datetime import date
from pathlib import Path

import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import sparse, stats
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'data' / 'analysis'
OUT.mkdir(parents=True, exist_ok=True)


def clean(o):
    if isinstance(o, dict):
        return {k: clean(v) for k, v in o.items()}
    if isinstance(o, (list, tuple)):
        return [clean(v) for v in o]
    if isinstance(o, (np.integer,)):
        return int(o)
    if isinstance(o, (np.floating, float)):
        return None if (math.isnan(o) or math.isinf(o)) else float(o)
    if isinstance(o, (np.bool_,)):
        return bool(o)
    return o


def write(name, obj):
    s = json.dumps(clean(obj), indent=1, ensure_ascii=False)
    assert 'NaN' not in s and 'Infinity' not in s
    (OUT / name).write_text(s)


rows = json.load(open(ROOT / 'data/processed/districts_enriched.json'))
df = pd.DataFrame(rows)
states = {s['abbr']: s for s in (json.load(open(f)) for f in sorted(glob.glob(ROOT.as_posix() + '/data/states/*.json')))}
df['state_status'] = df['state'].map(lambda a: states[a]['status'])
df['state_has_k8_mandate'] = (df['state_status'] == 'k8_requirement').astype(int)
reviewed = df['reply_status'].isin(['replied', 'no_reply_on_file']) & df['delivered']
df['replied'] = np.where(reviewed, (df['reply_status'] == 'replied').astype(float), np.nan)

# ------------------------------------------------------------------ 1. student-weighted impact
def headcount(sub, col='k8_enrollment'):
    have = sub[col].notna()
    return {'districts': int(len(sub)), 'districts_with_enrollment': int(have.sum()), 'districts_without_enrollment': int((~have).sum()),
            'k8_students': int(sub.loc[have, col].sum())}


def impact(d, col):
    asked = d[d['delivered']]
    rep = d[d['reply_status'] == 'replied']
    return {
        'asked': headcount(asked, col),
        'replied': headcount(rep, col),
        'confirmed_no_dedicated_course': headcount(rep[rep['k8_program'] == 'none'], col),
        'confirmed_optional_or_partial_program': headcount(rep[rep['k8_program'] == 'partial'], col),
        'replied_unclear_or_in_progress': headcount(rep[rep['k8_program'].isin(['unclear', 'pending'])], col),
        'no_reply_on_file': headcount(d[d['reply_status'] == 'no_reply_on_file'], col),
        'not_reviewed': headcount(d[d['reply_status'] == 'not_reviewed'], col),
    }


nc = df[df['state'] == 'NC']
write('student_weighted_impact.json', {
    'definition': 'K-8 = CCD enrollment grades KG-8 (state totals use CCD for every state; NC also shown on NCDPI 2024-25 Month 1 ADM). '
                  'No district is imputed; districts with no federal match are counted separately.',
    'confirmed_active_program_note': 'No district in the audit confirmed a full K-8 course. The only affirmative reply class is optional_or_partial.',
    'all_13_states': impact(df, 'k8_enrollment'),
    'north_carolina_ccd': impact(nc, 'k8_enrollment'),
    'north_carolina_ncdpi_adm': impact(nc, 'k8_ncdpi_adm'),
    'by_state': {st: impact(g, 'k8_enrollment') for st, g in df.groupby('state')},
})

# ------------------------------------------------------------------ 2. models
def fit_logit(d, y, xs, labels):
    d = d.dropna(subset=[y] + xs)
    X = sm.add_constant(d[xs].astype(float))
    n1 = int(d[y].sum())
    if len(d) < 20 or n1 < 3 or len(d) - n1 < 3:
        return {'n': int(len(d)), 'events': n1, 'error': 'too few events or non-events to fit'}
    try:
        res = sm.Logit(d[y].astype(float), X).fit(disp=0, maxiter=200)
    except Exception as e:  # perfect separation etc.
        return {'n': int(len(d)), 'events': n1, 'error': f'{type(e).__name__}: {e}'}
    ci = res.conf_int()
    terms = {}
    for v in xs:
        terms[labels.get(v, v)] = {'coef': res.params[v], 'odds_ratio': math.exp(res.params[v]), 'or_ci95': [math.exp(ci.loc[v, 0]), math.exp(ci.loc[v, 1])],
                                   'p_value': res.pvalues[v]}
    return {'n': int(len(d)), 'events': n1, 'mcfadden_pseudo_r2': res.prsquared, 'log_likelihood': res.llf, 'terms': terms}


m = df.copy()
m['log_k8_enrollment'] = np.log(m['k8_enrollment'].where(m['k8_enrollment'] > 0))
m['spend_per_1000'] = m['instruction_spend_per_pupil'] / 1000
m['poverty_pct_pts'] = m['child_poverty_pct']
m['rural'] = m['locale_type'].map({'Rural': 1, 'City': 0, 'Suburb': 0})   # Town is excluded from this contrast, as specified
XA = ['log_k8_enrollment', 'poverty_pct_pts', 'spend_per_1000', 'rural', 'state_has_k8_mandate']
LAB = {'log_k8_enrollment': 'log K-8 enrollment', 'poverty_pct_pts': 'child poverty (per pct pt)', 'spend_per_1000': 'instruction $ per pupil (per $1,000)',
       'rural': 'Rural (vs City/Suburb)', 'state_has_k8_mandate': 'state has K-8 requirement'}
A_all = m[reviewed]
modelA = {
    'outcome': 'replied (1) vs no reply on file (0). Sample = districts whose inbox was reviewed (tracker row exists).',
    'primary_north_carolina': {
        'role': 'PRIMARY. North Carolina is a complete census (115 districts), all requested on the same day (2026-07-28) and observed for about 10 weeks to 2026-10-11.',
        **fit_logit(A_all[A_all['state'] == 'NC'], 'replied', XA[:-1], LAB)},
    'baseline_pooled_snapshot': {
        'role': 'RIGHT-CENSORED BASELINE SNAPSHOT, not a behavioural model. Non-NC requests were sent 2026-10-28 to 2026-11-03 and their inboxes were reviewed within 0-1 days, so almost every non-NC district is censored almost immediately. State-level covariates, including the K-8 requirement, are confounded with that observation window; the pooled state-has-K-8-requirement odds ratio (about 0.25) is a timing artefact, not an effect of the mandate.',
        **fit_logit(A_all, 'replied', XA, LAB)},
    'reviewed_states': sorted(A_all['state'].unique()),
}

# Model B: among respondents, confirmed no dedicated course vs any other reply
R = m[m['reply_status'] == 'replied'].copy()
R['no_k8_program'] = (R['k8_program'] == 'none').astype(float)
R['has_k8_program'] = (R['k8_program'] == 'partial').astype(float)


def nonparam(d, col):
    a = d.loc[d['no_k8_program'] == 1, col].dropna()
    b = d.loc[d['no_k8_program'] == 0, col].dropna()
    if len(a) < 3 or len(b) < 3:
        return {'n_no_program': len(a), 'n_other_reply': len(b), 'error': 'too few'}
    u = stats.mannwhitneyu(a, b, alternative='two-sided')
    return {'n_no_program': len(a), 'n_other_reply': len(b), 'median_no_program': float(a.median()), 'median_other_reply': float(b.median()),
            'mann_whitney_u': float(u.statistic), 'p_value': float(u.pvalue)}


def kw(d, col):
    groups = {k: g[col].dropna() for k, g in d.groupby('k8_program')}
    groups = {k: v for k, v in groups.items() if len(v) >= 3}
    if len(groups) < 2:
        return {'error': 'fewer than two groups with n>=3'}
    h = stats.kruskal(*groups.values())
    return {'groups': {k: {'n': len(v), 'median': float(v.median())} for k, v in groups.items()}, 'h': float(h.statistic), 'p_value': float(h.pvalue)}


COLS = {'instruction_spend_per_pupil': 'instruction spend per pupil', 'child_poverty_pct': 'child poverty %', 'k8_enrollment': 'K-8 enrollment'}
modelB = {
    'definition': 'Among districts that replied. "no program" = reply confirms no dedicated K-8 course. Comparison group = every other reply class '
                  '(optional/partial, unclear, in progress). No district confirmed a full K-8 course, so "has program vs no program" is not estimable as asked.',
    'group_sizes': {k: int(v) for k, v in R['k8_program'].value_counts().items()},
    'mann_whitney': {lab: nonparam(R, c) for c, lab in COLS.items()},
    'kruskal_wallis_by_reply_class': {lab: kw(R, c) for c, lab in COLS.items()},
    'logit_no_program': fit_logit(R, 'no_k8_program', ['log_k8_enrollment', 'poverty_pct_pts', 'spend_per_1000'], LAB),
}
# Bureaucratic-response robustness: a "no course" reply is a definitive formal determination; "unclear" replies are mostly referrals.
# Compare the definitive replies with each other reply class separately, so the primary spending finding cannot be an artefact of how the comparison group is built.
def mw_exact(a, b):
    a, b = a.dropna(), b.dropna()
    if len(a) < 2 or len(b) < 2:
        return {'n_a': len(a), 'n_b': len(b), 'error': 'too few'}
    u = stats.mannwhitneyu(a, b, alternative='two-sided', method='auto')
    return {'n_a': int(len(a)), 'n_b': int(len(b)), 'median_a': float(a.median()), 'median_b': float(b.median()), 'mann_whitney_u': float(u.statistic), 'p_value': float(u.pvalue),
            'method': 'exact' if min(len(a), len(b)) <= 8 and len(set(a) | set(b)) == len(a) + len(b) else 'asymptotic'}


NOC = R[R['k8_program'] == 'none']
OTHER = R[R['k8_program'] != 'none']
PART = R[R['k8_program'] == 'partial']
UNCL = R[R['k8_program'].isin(['unclear', 'pending'])]
ROB = {'no_course_vs_all_other_replies': (NOC, OTHER), 'no_course_vs_optional_partial_only': (NOC, PART), 'no_course_vs_unclear_or_referral_only': (NOC, UNCL)}
modelB['bureaucratic_response_robustness'] = {
    'groups': {'confirmed_no_course': int(len(NOC)), 'all_other_replies': int(len(OTHER)), 'optional_or_partial': int(len(PART)), 'unclear_or_in_progress': int(len(UNCL))},
    'note': 'Comparison 1 is the primary split. Comparison 2 is the strict substantive subsample (both groups gave a determinate answer). Comparison 3 isolates the ambiguous replies. n shown is districts with a value for the measure, so it can be below the group size.',
    'comparisons': {k: {lab: mw_exact(a[c], b[c]) for c, lab in COLS.items()} for k, (a, b) in ROB.items()},
}

# wealth quartile check: do low- and high-spending districts fail at similar rates?
Rq = R.dropna(subset=['instruction_spend_per_pupil']).copy()
if len(Rq) >= 8:
    Rq['spend_quartile'] = pd.qcut(Rq['instruction_spend_per_pupil'], 4, labels=['Q1 lowest', 'Q2', 'Q3', 'Q4 highest'])
    modelB['no_program_share_by_spending_quartile'] = {str(k): {'replied': int(len(g)), 'no_program': int(g['no_k8_program'].sum()), 'share': float(g['no_k8_program'].mean())}
                                                       for k, g in Rq.groupby('spend_quartile', observed=True)}

# Kaplan-Meier on business days
dl = {r['state']: r for r in csv.DictReader(open(ROOT / 'data/audit/foia_deadlines.csv'))}


def bdays(a, b):
    return int(np.busday_count(a, b))


def cdays(a, b):
    return (date.fromisoformat(b) - date.fromisoformat(a)).days


def km(durs, events):
    order = sorted(set(d for d, e in zip(durs, events) if e))
    s_, curve = 1.0, [{'t': 0, 'survival': 1.0, 'at_risk': len(durs)}]
    for t in order:
        at_risk = sum(1 for d in durs if d >= t)
        ev = sum(1 for d, e in zip(durs, events) if e and d == t)
        s_ *= 1 - ev / at_risk
        curve.append({'t': t, 'survival': s_, 'at_risk': at_risk})
    first = lambda q: next((c['t'] for c in curve if c['survival'] <= q), None)
    tau = max(durs)
    rmst = sum(curve[i]['survival'] * ((curve[i + 1]['t'] if i + 1 < len(curve) else tau) - curve[i]['t']) for i in range(len(curve)))
    return curve, first(0.5), first(0.75), rmst, tau


def rule(st):
    """A deadline is only ever compared when the statute text was read and it names a fixed day count."""
    d = dl.get(st, {})
    rt = d.get('rule_type', 'unverified')
    if d.get('verified') == 'true' and rt in ('fixed_business_days', 'fixed_calendar_days') and d.get('deadline_days'):
        return rt, int(d['deadline_days']), d
    return rt, None, d


lat = {}
for st in ['NC'] + sorted(x for x in m[reviewed]['state'].unique() if x != 'NC'):
    g = m[reviewed & (m['state'] == st)]
    if g.empty:
        continue
    end = g['reply_review_through'].iloc[0]
    d_, e_, c_ = [], [], []
    excluded = 0
    for _, r in g.iterrows():
        if r['reply_status'] == 'replied' and r['reply_date'] and r['request_date']:
            d_.append(max(bdays(r['request_date'], r['reply_date']), 0)); e_.append(True); c_.append(max(cdays(r['request_date'], r['reply_date']), 0))
        elif r['reply_status'] == 'no_reply_on_file':
            if r['request_date'] > end:
                excluded += 1
                continue
            d_.append(bdays(r['request_date'], end)); e_.append(False); c_.append(cdays(r['request_date'], end))
    if not d_:
        continue
    curve, med, p25, rmst, tau = km(d_, e_)
    rt, days, dd = rule(st)
    unit = 'business_days' if rt == 'fixed_business_days' else 'calendar_days' if rt == 'fixed_calendar_days' else None
    basis = c_ if unit == 'calendar_days' else d_
    within = sum(1 for d, e in zip(basis, e_) if e and days is not None and d <= days)
    late = sum(1 for d, e in zip(basis, e_) if (not e) and days is not None and d > days)   # still waiting after the deadline passed
    lat[st] = {'primary': st == 'NC', 'n': len(d_), 'replied': int(sum(e_)), 'censored': int(len(e_) - sum(e_)), 'excluded_request_after_review': excluded, 'review_through': end,
               'observation_window_business_days': int(tau),
               'median_business_days_to_reply': med, 'median_label': 'Not yet reached (<50% replied)' if med is None else f'{med} business days',
               'p25_business_days': p25, 'rmst_business_days': rmst, 'rmst_window_business_days': int(tau),
               'median_among_repliers_only': float(np.median([d for d, e in zip(d_, e_) if e])) if any(e_) else None, 'km_curve': curve,
               'rule_type': rt, 'deadline_days': days, 'deadline_unit': unit, 'statute': dd.get('statute'), 'deadline_verified': dd.get('verified') == 'true',
               'deadline_comparison': 'compared' if days is not None else ('none: statute sets no fixed day count (reasonable time)' if rt == 'reasonable_time_no_fixed_days' else 'none: statute text not verified'),
               'replied_within_deadline': within if days is not None else None,
               'still_waiting_past_deadline': late if days is not None else None,
               'reported_unverified': dd.get('reported_unverified') or None,
               'date_quality': 'reply dates are tracker dates (day inbox was reviewed or reply logged)' if st != 'NC' else 'reply dates read from response.md; dates only, no times'}
latency = {'unit': 'business days (Mon-Fri, no holiday calendar); calendar days only where the statute counts calendar days',
           'primary_sample': 'North Carolina (n = 115 census, ~10-week window) is the primary latency estimate. Other states are 0-1 day snapshots.',
           'note': 'Median is null ("Not yet reached") when fewer than half of requests have replied by the review date. p25 is the time by which a quarter had replied; RMST is the mean business days waited, capped at the observed window, so it is comparable without extrapolating.',
           'deadline_rule': 'data/audit/foia_deadlines.csv: a deadline is compared only where verified=true and rule_type is fixed_business_days or fixed_calendar_days. Reasonable-time statutes (NC, FL, OH) and unverified rows are never flagged late.',
           'by_state': lat}
write('econometric_models.json', {'model_a_response_propensity': modelA, 'model_b_compliance_among_respondents': modelB, 'response_latency_survival': latency})

# ------------------------------------------------------------------ 3. enforcement teeth
MARKERS = ['explicit_k8_mandate', 'standalone_or_min_hours', 'state_assessment', 'district_reporting', 'curriculum_or_pd_mandate']
coding = {}
with open(ROOT / 'data/audit/state_marker_coding.csv') as fh:
    for r in csv.DictReader(fh):
        assert r['value'] in ('1', '0', 'not_verified'), r
        coding[(r['state'], r['marker'])] = ({'1': True, '0': False, 'not_verified': None}[r['value']], (r['evidence'] + (f" [{r['citation']}]" if r['citation'] else '')).strip())
assert len(coding) == 51 * len(MARKERS), 'state_marker_coding.csv must have one row per state and marker (run scripts/build_marker_coding.py)'
teeth = {}
for ab, s in states.items():
    mk = {n: coding[(ab, n)] for n in MARKERS}
    got = {n: v for n, (v, _) in mk.items()}
    confirmed = 2 * sum(1 for v in got.values() if v is True)
    unknown = sum(1 for v in got.values() if v is None)
    teeth[ab] = {'abbr': ab, 'name': s['name'], 'status': s['status'], 'score_confirmed': confirmed, 'score_max_possible': confirmed + 2 * unknown,
                 'markers': {n: {'value': v, 'basis': b} for n, (v, b) in mk.items()}, 'unrecorded_markers': unknown}
vals = [t['score_confirmed'] for t in teeth.values()]
# correlation with district outcomes in the 13 audited states
st_rows = []
for st, g in df[reviewed].groupby('state'):
    rep = g[g['reply_status'] == 'replied']
    st_rows.append({'state': st, 'districts_reviewed': len(g), 'reply_rate': len(rep) / len(g), 'replies': len(rep),
                    'no_course_share_of_replies': (rep['k8_program'] == 'none').mean() if len(rep) else np.nan, 'teeth': teeth[st]['score_confirmed']})
cdf = pd.DataFrame(st_rows)


def spear(x, y):
    if len(x) < 4 or len(set(x)) < 2 or len(set(y)) < 2:
        return {'n': len(x), 'rho': None, 'p_value': None, 'note': 'undefined: fewer than 4 states or no variation in one variable'}
    r = stats.spearmanr(x, y)
    return {'n': len(x), 'rho': float(r.statistic), 'p_value': float(r.pvalue)}


c2 = cdf[cdf['replies'] >= 3]
write('enforcement_teeth.json', {
    'rubric': {m_: 2 for m_ in MARKERS},
    'scoring_rule': 'Coded in data/audit/state_marker_coding.csv (1 = explicit in a primary source on file, 0 = recorded absent, not_verified = the archive holds only excerpts, which cannot show absence). '
                    'A marker scores +2 only when coded 1. not_verified is never scored 0: score_max_possible adds those points back, so score_confirmed is a lower bound.',
    'marker_coverage': {n: {'confirmed_true': sum(1 for t in teeth.values() if t['markers'][n]['value'] is True),
                            'confirmed_false': sum(1 for t in teeth.values() if t['markers'][n]['value'] is False),
                            'unrecorded': sum(1 for t in teeth.values() if t['markers'][n]['value'] is None)} for n in MARKERS},
    'status_counts': dict(Counter(t['status'] for t in teeth.values())),
    'score_distribution': dict(sorted(Counter(vals).items())),
    'highest': sorted(teeth.values(), key=lambda t: (-t['score_confirmed'], t['abbr']))[:5],
    'lowest': sorted(teeth.values(), key=lambda t: (t['score_confirmed'], t['abbr']))[:5],
    'spearman_vs_district_outcomes': {'states_in_sample': cdf.to_dict('records'),
                                      'teeth_vs_reply_rate': spear(list(cdf['teeth']), list(cdf['reply_rate'])),
                                      'teeth_vs_no_course_share_of_replies_(states_with_3+_replies)': spear(list(c2['teeth']), list(c2['no_course_share_of_replies']))},
    'jurisdictions': teeth,
})

# ------------------------------------------------------------------ 4. Manski bounds
asked = df[df['delivered']].copy()
asked['w'] = asked['k8_enrollment']


def bounds(d, weight):
    """Y = 1: district confirms an optional/partial K-8 program. Y = 0: confirms no dedicated course. Y unobserved otherwise."""
    if weight:
        d = d[d['w'].notna()]
        w = d['w']
    else:
        w = pd.Series(1.0, index=d.index)
    tot = w.sum()
    y1 = w[d['k8_program'] == 'partial'].sum()
    y0 = w[d['k8_program'] == 'none'].sum()
    unk = tot - y1 - y0
    return {'universe': float(tot), 'confirmed_program': float(y1), 'confirmed_no_course': float(y0), 'undetermined': float(unk),
            'program_rate_lower': y1 / tot, 'program_rate_upper': (y1 + unk) / tot,
            'no_course_rate_lower': y0 / tot, 'no_course_rate_upper': (y0 + unk) / tot,
            'width': unk / tot,
            'point_if_non_respondents_like_determined_respondents': (y1 / (y1 + y0)) if (y1 + y0) else None,
            # Sensitivity, NOT bounds: non-respondents (and undetermined replies) comply at k x the rate seen among districts that gave a determinate answer
            'sensitivity_program_rate': {f'{k}x': (y1 + k * (y1 / (y1 + y0)) * unk) / tot for k in (0, 0.5, 1)} if (y1 + y0) else None,
            'sensitivity_no_course_rate': {f'{k}x': (y0 + k * (y0 / (y1 + y0)) * unk) / tot for k in (0, 0.5, 1)} if (y1 + y0) else None}


def block(d):
    return {'district_weighted': bounds(d, False), 'k8_student_weighted': bounds(d, True)}


strata = {}
for status, g in asked.groupby('state_status'):
    strata[status] = {'states': sorted(g['state'].unique()), **block(g)}
write('manski_bounds.json', {
    'outcome': 'Y=1 if the district confirmed an optional or partial K-8 program; Y=0 if it confirmed no dedicated course; every other district (no reply, unclear, in progress, not reviewed) is Y-missing.',
    'method': 'Worst-case (no-assumption) Manski bounds: missing Y set to all-0 for the lower bound and all-1 for the upper bound.',
    'universe': 'all districts a request was delivered to (delivered=true). Student-weighted universe excludes districts with no federal enrollment match.',
    'overall': block(asked),
    'north_carolina': block(asked[asked['state'] == 'NC']),
    'by_state_statutory_category': strata,
    'conditioning_note': 'Conditioning on statutory category without further assumptions cannot narrow the bounds: the category-weighted sum of worst-case bounds equals the unconditional bound. The table shows how the identified set differs by category, not a tighter overall interval.',
    'integrity_framing': 'The no-assumption interval is a non-imputation integrity bound: it is how wide the evidence is when no missing reply is guessed. It is not an estimate. The sensitivity_* blocks are assumption-dependent scenarios (non-respondents comply at 0x, 0.5x or 1.0x the rate among districts that gave a determinate answer) and should be quoted as scenarios.',
    'assumption_dependent': 'point_if_non_respondents_like_determined_respondents is NOT a bound; it is the rate if missingness were ignorable and is shown only for contrast.',
})

# ------------------------------------------------------------------ 5. boilerplate similarity
T = df[df['reply_text'].notna() & (df['reply_text'].str.len() > 0)].copy()
T['clean'] = T['reply_text'].str.replace(r'\[[^\]]*\]', ' ', regex=True)
vec = TfidfVectorizer(ngram_range=(1, 3), min_df=2, sublinear_tf=True, stop_words='english')
Xt = vec.fit_transform(T['clean'])
S = cosine_similarity(Xt)
names = list(zip(T['state'], T['name']))
thr = 0.5
pairs = [{'a': names[i][1], 'b': names[j][1], 'cosine': float(S[i, j])} for i in range(len(T)) for j in range(i + 1, len(T)) if S[i, j] >= thr]
parent = list(range(len(T)))


def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x


for i in range(len(T)):
    for j in range(i + 1, len(T)):
        if S[i, j] >= thr:
            parent[find(i)] = find(j)
groups = defaultdict(list)
for i in range(len(T)):
    groups[find(i)].append(i)
terms = np.array(vec.get_feature_names_out())
clusters = []
for idx in groups.values():
    if len(idx) < 2:
        continue
    top = np.asarray(Xt[idx].mean(axis=0)).ravel().argsort()[::-1][:6]
    clusters.append({'size': len(idx), 'districts': [names[i][1] for i in idx], 'top_terms': list(terms[top]), 'text_sample': T.iloc[idx[0]]['clean'].strip()[:240]})
clusters.sort(key=lambda c: -c['size'])
write('reply_similarity.json', {
    'method': f'TF-IDF (1-3 grams, min_df=2, sublinear tf, English stop words), cosine similarity, connected components at cosine >= {thr}. Bracketed redactions removed first.',
    'texts_analyzed': int(len(T)), 'states_with_text': sorted(T['state'].unique()),
    'note': 'Full reply text is on file for North Carolina only; other states carry status codes, not text.',
    'pairs_above_threshold': len(pairs), 'clusters': clusters, 'top_pairs': sorted(pairs, key=lambda p: -p['cosine'])[:25],
    'median_pairwise_cosine': float(np.median(S[np.triu_indices(len(T), 1)])) if len(T) > 1 else None,
})

# ------------------------------------------------------------------ 5b. prescriptive: 0-1 integer linear programs (scipy.optimize.milp / HiGHS)
from scipy.optimize import LinearConstraint, Bounds, milp

ST = {ab: t for ab, t in teeth.items()}
df['teeth'] = df['state'].map(lambda a_: ST[a_]['score_confirmed'])
df['tau'] = 1 + 0.15 * df['teeth']


def solve(c, A_ub, b_ub, n):
    res = milp(c=-np.asarray(c), constraints=[LinearConstraint(np.asarray(A_ub), -np.inf, np.asarray(b_ub))], integrality=np.ones(n), bounds=Bounds(0, 1))
    assert res.success, res.message
    return np.round(res.x).astype(int), -res.fun, res.status


def dispersion(states_):
    c_ = Counter(states_)
    n_ = sum(c_.values())
    return {'by_state': dict(sorted(c_.items())), 'states': len(c_), 'max_state_share': (max(c_.values()) / n_) if n_ else None,
            'hhi': sum((v / n_) ** 2 for v in c_.values()) if n_ else None}


FIPS_STATES = sorted(df['state'].unique())
# ---- reply propensity from the North Carolina census (Model A covariates plus a Town indicator, so Town districts can be scored)
pm = m.copy()
pm['town'] = (pm['locale_type'] == 'Town').astype(float)
pm['rural'] = (pm['locale_type'] == 'Rural').astype(float)
PX = ['log_k8_enrollment', 'poverty_pct_pts', 'spend_per_1000', 'rural', 'town']
fit_nc = pm[reviewed & (pm['state'] == 'NC')].dropna(subset=['replied', 'log_k8_enrollment', 'poverty_pct_pts', 'spend_per_1000', 'locale_type'])
lg = sm.Logit(fit_nc['replied'].astype(float), sm.add_constant(fit_nc[PX].astype(float))).fit(disp=0, maxiter=200)
pm['p_hat'] = np.nan
okp = pm[PX].notna().all(axis=1) & pm['locale_type'].notna()
Xall = sm.add_constant(pm.loc[okp, PX].astype(float), has_constant='add')
p0 = lg.predict(Xall)                                   # NC-model probability of eventually replying, by covariates

# State reply velocity relative to NC, shrunk by a Gamma-Poisson empirical Bayes model.
# NC's Kaplan-Meier curve gives the share expected to have replied after t business days; E_s adds that up over a state's reviewed
# districts at their own elapsed time. y_s is what the state actually shows. rho_s = y_s / E_s is its velocity relative to NC.
km_nc = lat['NC']['km_curve']
def F_nc(t):
    sv = 1.0
    for c_ in km_nc:
        if c_['t'] <= t:
            sv = c_['survival']
    return 1 - sv
rev = df[reviewed].copy()
rev['elapsed_bd'] = [bdays(a_, b_) for a_, b_ in zip(rev['request_date'], rev['reply_review_through'])]
st_obs = {}
for st_, g_ in rev.groupby('state'):
    st_obs[st_] = {'n': int(len(g_)), 'y': int((g_['reply_status'] == 'replied').sum()), 'E': float(sum(F_nc(t_) for t_ in g_['elapsed_bd'])), 'max_elapsed_bd': int(g_['elapsed_bd'].max())}
non_nc = {k_: v_ for k_, v_ in st_obs.items() if k_ != 'NC' and v_['E'] > 0}
from math import lgamma, log
def nb_ll(a_):
    return sum(lgamma(v_['y'] + a_) - lgamma(a_) - lgamma(v_['y'] + 1) + a_ * log(a_ / (a_ + v_['E'])) + v_['y'] * log(v_['E'] / (a_ + v_['E'])) for v_ in non_nc.values())
grid = np.logspace(-1, 3, 200)
a_hat = float(grid[int(np.argmax([nb_ll(a_) for a_ in grid]))])
rng_eb = np.random.default_rng(20261202)
S_DRAWS = 1000
beta_draws = rng_eb.multivariate_normal(lg.params.values, lg.cov_params().values, size=S_DRAWS)
rho_post = {}
for st_ in FIPS_STATES:
    o_ = st_obs.get(st_)
    if st_ == 'NC':
        rho_post[st_] = {'shape': None, 'rate': None, 'mean': 1.0, 'lo': 1.0, 'hi': 1.0, 'reference': True, 'y': o_['y'], 'E': o_['E'], 'n': o_['n']}
        continue
    y_, E_ = (o_['y'], o_['E']) if o_ else (0, 0.0)
    shape, rate = a_hat + y_, a_hat + E_
    rho_post[st_] = {'shape': shape, 'rate': rate, 'mean': shape / rate, 'lo': float(stats.gamma.ppf(0.025, shape, scale=1 / rate)), 'hi': float(stats.gamma.ppf(0.975, shape, scale=1 / rate)),
                     'reference': False, 'y': y_, 'E': E_, 'n': (o_ or {}).get('n', 0), 'raw_velocity': (y_ / E_) if E_ > 0 else None, 'reviewed': bool(o_)}
Xv = Xall.values
p0_draws = 1 / (1 + np.exp(-(Xv @ beta_draws.T)))          # districts x draws
rho_d = {}
for st_, r_ in rho_post.items():
    rho_d[st_] = np.ones(S_DRAWS) if r_['reference'] else rng_eb.gamma(r_['shape'], 1 / r_['rate'], size=S_DRAWS)
rho_mat = np.vstack([rho_d[st_] for st_ in pm.loc[okp, 'state']])
p_draws = np.clip(p0_draws * rho_mat, 0.05, 0.95)
pm['p_hat'] = np.nan; pm['p_lo'] = np.nan; pm['p_hi'] = np.nan
pm.loc[okp, 'p_hat'] = np.clip(p0.values * np.array([rho_post[st_]['mean'] for st_ in pm.loc[okp, 'state']]), 0.05, 0.95)
pm.loc[okp, 'p_lo'] = np.percentile(p_draws, 2.5, axis=1)
pm.loc[okp, 'p_hi'] = np.percentile(p_draws, 97.5, axis=1)
pm.loc[okp, 'p_nc'] = np.clip(p0.values, 0.05, 0.95)
df['p_nc'] = pm['p_nc']
df['p_hat'] = pm['p_hat']; df['p_lo'] = pm['p_lo']; df['p_hi'] = pm['p_hi']
pool = df[df['delivered']].copy()
universe_students = float(pool.loc[pool['k8_enrollment'].notna(), 'k8_enrollment'].sum())
propensity = {'source': 'logistic regression on the North Carolina census (replied vs no reply on file), partially pooled by state with a Gamma-Poisson empirical Bayes velocity multiplier', 'n': int(len(fit_nc)), 'events': int(fit_nc['replied'].sum()),
              'covariates': ['log K-8 enrollment', 'child poverty %', 'instruction $ per pupil (per $1,000)', 'Rural (vs City/Suburb)', 'Town (vs City/Suburb)'],
              'coefficients': {k: float(v) for k, v in lg.params.items()}, 'clamp': [0.05, 0.95],
              'formula': 'p_i = clip( expit(x_i beta) * rho_s(i), 0.05, 0.95 ). rho_s = state reply velocity relative to NC: y_s observed replies over E_s = sum of NC Kaplan-Meier F(elapsed business days) across the state\'s reviewed districts. Prior rho ~ Gamma(a, a); posterior rho_s ~ Gamma(a + y_s, a + E_s). a is the marginal-likelihood (negative binomial) maximiser across non-NC reviewed states. NC is the reference (rho = 1).',
              'prior_shape_a': a_hat, 'state_velocity': rho_post, 'prediction_interval': f'95% interval from {S_DRAWS} joint draws of the NC logit coefficients (multivariate normal) and each state\'s posterior rho',
              'statutory_window': 'enters through eligibility (a district is not scored for follow-up before its verified or 5-business-day window) and through E_s, which counts only the replies NC\'s own curve predicts by that elapsed time',
              'note': 'Still a modelling choice: NC covariate weights are transferred to other states and shrunk by observed early velocity. States with no reviewed inbox keep the prior (rho = 1) with a wide interval.'}

# ---- Model 1: FOIA follow-up ILP
B_ = pool[(pool['reply_status'] == 'no_reply_on_file') & pool['k8_enrollment'].notna()].copy()
no_p = int(B_['p_hat'].isna().sum())
B_ = B_[B_['p_hat'].notna()].reset_index(drop=True)
sent_log = [r for r in csv.DictReader(open(ROOT / 'data/outreach/sent-log.csv'))]
GENERIC = {'info', 'contact', 'records', 'foi', 'foia', 'publicrecords', 'openrecords', 'office', 'admin', 'webmaster', 'main', 'district', 'hello'}
log_feat = defaultdict(lambda: {'sent': False, 'bounced': False, 'generic': False})
for r in sent_log:
    k_ = (r['state'], r['district'].split(' (')[0].lower())
    local = r['recipient'].split('@')[0].lower().replace('.', '').replace('_', '').replace('-', '')
    if r['status'] == 'sent':
        log_feat[k_]['sent'] = True
        log_feat[k_]['generic'] = log_feat[k_]['generic'] or local in GENERIC
    else:
        log_feat[k_]['bounced'] = True


def effort(r):
    f = log_feat.get((r['state'], r['name'].split(' (')[0].lower()))
    big_urban = (r['k8_enrollment'] >= 10000) and r['locale_type'] in ('City', 'Suburb')
    return 1.0 + 0.5 * (0 if f and f['sent'] else 1) + 0.25 * (1 if f and f['bounced'] else 0) + 0.25 * (1 if f and f['generic'] else 0) - 0.25 * (1 if big_urban else 0)


B_['cost'] = [effort(r) for _, r in B_.iterrows()]
effort_proxy = {
    'formula': 'c_i = 1.0 + 0.5*I(no delivered request with a named recipient on file in the send log) + 0.25*I(an earlier request to the district bounced) + 0.25*I(the recipient is a generic mailbox: info, contact, records, foia, ...) - 0.25*I(K-8 enrollment >= 10,000 and locale City or Suburb, i.e. a formal records office)',
    'inputs': 'data/outreach/sent-log.csv (flags only; addresses are never exported) and CCD locale and enrollment',
    'honest_limit': 'No time-and-motion data exists, so the weights are a stated proxy, not a calibrated estimate. Their influence is bounded by the Monte Carlo below, which perturbs every c_i by +/-25%.',
    'distribution': {'min': float(B_['cost'].min()), 'median': float(B_['cost'].median()), 'max': float(B_['cost'].max())},
    'contact_flags': {'no_send_log_record': int(sum(1 for _, r in B_.iterrows() if not log_feat.get((r['state'], r['name'].split(' (')[0].lower()), {}).get('sent'))),
                      'prior_bounce': int(sum(1 for v_ in log_feat.values() if v_['bounced'])), 'generic_mailbox': int(sum(1 for v_ in log_feat.values() if v_['generic']))},
}
B_['elapsed_bd'] = [bdays(r['request_date'], r['reply_review_through']) for _, r in B_.iterrows()]


def window(st):
    rt, days, _ = rule(st)
    return days if rt == 'fixed_business_days' else 5     # calendar-day and unverified rules fall back to 5 business days (MD's 30 calendar days is applied below)


def eligible(r):
    rt, days, _ = rule(r['state'])
    if rt == 'fixed_calendar_days' and days is not None:
        return cdays(r['request_date'], r['reply_review_through']) >= days
    return r['elapsed_bd'] >= window(r['state'])


B_['eligible'] = [eligible(r) for _, r in B_.iterrows()]
B_['coef'] = B_['k8_enrollment'] * B_['p_hat'] * B_['tau']
B_['width_pts'] = 100 * B_['k8_enrollment'] / universe_students
n_ = len(B_)


def pack(idx, label):
    sel = B_.iloc[idx]
    return {'method': label, 'districts_selected': int(len(sel)), 'hours_used': float(sel['cost'].sum()), 'k8_students': int(sel['k8_enrollment'].sum()),
            'objective': float(sel['coef'].sum()), 'expected_width_reduction_pts': float((sel['width_pts'] * sel['p_hat']).sum()), 'max_width_reduction_pts': float(sel['width_pts'].sum()),
            'dispersion': dispersion(list(sel['state'])),
            'districts': [{'rank': i + 1, 'district': r['name'], 'state': r['state'], 'k8_enrollment': int(r['k8_enrollment']), 'state_teeth_score': int(r['teeth']), 'tau': float(r['tau']), 'reply_propensity': float(r['p_hat']), 'reply_propensity_95pi': [float(r['p_lo']), float(r['p_hi'])],
                           'hours': float(r['cost']), 'objective_coefficient': float(r['coef']), 'days_since_request': int(cdays(r['request_date'], r['reply_review_through'])),
                           'interval_width_reduction_pts': float(r['width_pts'])} for i, (_, r) in enumerate(sel.sort_values('coef', ascending=False).iterrows())]}


budgets = {}
for Bh in (15, 25, 50):
    K = Bh                                   # the most districts any budget could fund at the minimum 1.0 h each
    cap = int(np.floor(0.35 * K))
    rows_ = [B_['cost'].values] + [(B_['state'] == st).astype(float).values for st in sorted(B_['state'].unique())]
    rhs = [Bh] + [cap] * (len(rows_) - 1)
    ub = np.where(B_['eligible'], 1, 0)
    res = milp(c=-B_['coef'].values, constraints=[LinearConstraint(np.array(rows_), -np.inf, np.array(rhs))], integrality=np.ones(n_), bounds=Bounds(0, ub))
    assert res.success, res.message
    x = np.round(res.x).astype(int)
    # naive greedy: highest objective coefficient first until the hours budget is spent; ignores eligibility and the per-state cap
    order = np.argsort(-B_['coef'].values, kind='stable'); gsel, used = [], 0.0
    for i in order:
        if used + B_['cost'].iloc[i] <= Bh:
            gsel.append(i); used += B_['cost'].iloc[i]
    milp_pack = pack(list(np.where(x == 1)[0]), 'MILP (HiGHS): budget, per-state cap, eligibility')
    milp_pack.update({'solver_status': int(res.status), 'solver_message': str(res.message), 'mip_gap': float(getattr(res, 'mip_gap', 0) or 0)})
    g = pack(gsel, 'Naive greedy by objective coefficient (budget only)')
    g['ineligible_selected'] = int((~B_['eligible'].iloc[gsel]).sum())
    g['violates_state_cap'] = any(v > cap for v in g['dispersion']['by_state'].values())
    budgets[str(Bh)] = {'budget_hours': Bh, 'K': K, 'per_state_cap': cap, 'milp': milp_pack, 'greedy': g}

# ---- 1,000-run Monte Carlo robustness of the MILP: reply propensity +/-30%, effort +/-25%, every draw re-solved
N_MC = 1000
rng = np.random.default_rng(20261203)
el = np.where(B_['eligible'].values)[0]                 # ineligible districts are fixed at 0, so only these vary
w_, tau_, wid_, p_, c_, stt_ = (B_[k_].values[el] for k_ in ('k8_enrollment', 'tau', 'width_pts', 'p_hat', 'cost', 'state'))
names_ = B_['name'].values[el]
sts_ = sorted(set(stt_))
S_ind = np.array([(stt_ == st_).astype(float) for st_ in sts_])
mc_out = {}
for Bh in (15, 25, 50):
    cap = int(np.floor(0.35 * Bh))
    base_sel = {(r_['district'], r_['state']) for r_ in budgets[str(Bh)]['milp']['districts']}
    base_x = np.array([(names_[i], stt_[i]) in base_sel for i in range(len(el))], dtype=float)
    cnt = np.zeros(len(el)); re_shr, base_shr, same, jac = [], [], 0, []
    for _ in range(N_MC):
        pd_ = np.clip(p_ * rng.uniform(0.7, 1.3, len(el)), 0.05, 0.95)
        cd_ = c_ * rng.uniform(0.75, 1.25, len(el))
        A = np.vstack([cd_, S_ind])
        rr = milp(c=-(w_ * pd_ * tau_), constraints=[LinearConstraint(A, -np.inf, np.array([Bh] + [cap] * len(sts_)))], integrality=np.ones(len(el)), bounds=Bounds(0, 1))
        x = np.round(rr.x)
        cnt += x
        re_shr.append(float((x * wid_ * pd_).sum())); base_shr.append(float((base_x * wid_ * pd_).sum()))
        same += int(np.array_equal(x, base_x))
        inter, uni = float((x * base_x).sum()), float(((x + base_x) > 0).sum())
        jac.append(inter / uni if uni else 1.0)
    pc = lambda a_, q_: float(np.percentile(a_, q_))
    freq = cnt / N_MC
    mc_out[str(Bh)] = {
        'budget_hours': Bh, 'draws': N_MC, 'eligible_districts': int(len(el)),
        'selection_stability': sorted([{'district': names_[i], 'state': stt_[i], 'k8_enrollment': int(w_[i]), 'selected_pct': float(100 * freq[i]), 'in_baseline_portfolio': bool(base_x[i])} for i in range(len(el)) if freq[i] > 0],
                                      key=lambda d_: (-d_['selected_pct'], d_['district'])),
        'baseline_portfolio_districts': int(base_x.sum()), 'baseline_always_selected': int(sum(1 for i in range(len(el)) if base_x[i] and freq[i] == 1.0)),
        'share_of_draws_identical_to_baseline_pct': float(100 * same / N_MC), 'mean_jaccard_overlap_with_baseline': float(np.mean(jac)),
        'expected_width_shrinkage_pts': {'reoptimised_each_draw': {'mean': float(np.mean(re_shr)), 'p5': pc(re_shr, 5), 'p50': pc(re_shr, 50), 'p95': pc(re_shr, 95)},
                                         'baseline_portfolio_held_fixed': {'mean': float(np.mean(base_shr)), 'p5': pc(base_shr, 5), 'p50': pc(base_shr, 50), 'p95': pc(base_shr, 95)},
                                         'mean_regret_pts': float(np.mean(re_shr) - np.mean(base_shr))},
    }
write('milp_sensitivity.json', {'method': f'{N_MC} Monte Carlo draws per budget. Each draw multiplies every eligible district\'s reply propensity by U(0.7, 1.3) (re-clipped to 0.05-0.95) and its effort by U(0.75, 1.25), then re-solves the Model 1 MILP with scipy.optimize.milp (HiGHS). Fixed seed.',
                               'population': 'only districts eligible for follow-up can enter a portfolio (ineligible districts are fixed at 0)', 'budgets': mc_out})

track_b_ilp = {
    'formulation': {
        'decision': 'x_i in {0,1} for each reviewed, enrollment-matched district i with no reply on file and a predicted reply propensity',
        'objective': 'maximize sum_i x_i * w_i * p_i * tau_s(i)',
        'terms': 'w_i = K-8 enrollment; p_i = empirical-Bayes reply propensity (NC logistic model scaled by the state early reply velocity), clamped to 0.05-0.95; tau_s = 1 + 0.15 * enforcement teeth score of the state',
        'constraints': ['sum_i c_i x_i <= B   (B in {15, 25, 50} researcher-hours)', 'sum_{i in S} x_i <= floor(0.35 K)   for every state S, with K = B', 'x_i = 0 if the district is not yet eligible for follow-up'],
        'eligibility': 'elapsed business days since the request, to the date replies were last reviewed, must reach the verified statutory window (SC 10 business days, MI 5 business days, MD 30 calendar days); where no fixed or verified window exists the floor is 5 business days',
    },
    'effort_proxy': effort_proxy,
    'assumptions': ['Effort c_i is a documented proxy from the send log and district size and urbanicity (see effort_proxy), not a measured time.',
                    'K, the size used for the per-state cap, is the largest number of districts the budget could fund (B at 1.0 hour each).',
                    'Elapsed time is measured to the last review date of each state\'s inbox, because that is the last date a reply status is known.'],
    'propensity_model': propensity, 'universe_k8_students': universe_students,
    'population': {'reviewed_no_reply_with_enrollment': int(n_ + no_p), 'dropped_no_propensity_inputs': no_p, 'eligible_now': int(B_['eligible'].sum()), 'ineligible_too_recent': int((~B_['eligible']).sum()),
                   'eligible_by_state': dict(sorted(Counter(B_.loc[B_['eligible'], 'state']).items()))},
    'headline_budget_hours': 25, 'budgets': budgets,
}

# ---- Model 2: curriculum deployment ILP
A_ = pool[pool['k8_program'].isin(['none', 'unclear', 'pending']) & pool['k8_enrollment'].notna()].copy().reset_index(drop=True)
A_['coef'] = A_['k8_enrollment'] * (1 + A_['child_poverty_pct'].fillna(0) / 100) * A_['tau']
nA = len(A_)
noc = (A_['k8_program'] == 'none').astype(float).values
rowsA, rhsA = [np.ones(nA), -noc], [20, -14]
for st in sorted(A_['state'].unique()):
    ind = (A_['state'] == st).astype(float).values
    rowsA.append(ind - 0.4 * np.ones(nA)); rhsA.append(0)          # sum_{S} y <= 0.4 * sum y
resA = milp(c=-A_['coef'].values, constraints=[LinearConstraint(np.array(rowsA), -np.inf, np.array(rhsA))], integrality=np.ones(nA), bounds=Bounds(0, 1))
assert resA.success, resA.message
y = np.round(resA.x).astype(int)


def packA(idx, label):
    sel = A_.iloc[idx]
    return {'method': label, 'districts_selected': int(len(sel)), 'confirmed_no_course_selected': int((sel['k8_program'] == 'none').sum()), 'k8_students': int(sel['k8_enrollment'].sum()), 'objective': float(sel['coef'].sum()),
            'dispersion': dispersion(list(sel['state'])),
            'districts': [{'rank': i + 1, 'district': r['name'], 'state': r['state'], 'k8_enrollment': int(r['k8_enrollment']), 'child_poverty_pct': (None if pd.isna(r['child_poverty_pct']) else float(r['child_poverty_pct'])),
                           'state_teeth_score': int(r['teeth']), 'tau': float(r['tau']), 'reply_class': r['k8_program'], 'objective_coefficient': float(r['coef'])}
                          for i, (_, r) in enumerate(sel.sort_values('coef', ascending=False).iterrows())]}


gA = list(np.argsort(-A_['coef'].values, kind='stable')[:20])
mA = packA(list(np.where(y == 1)[0]), 'MILP (HiGHS): 20-district wave, >=14 confirmed no-course, <=40% per state')
mA.update({'solver_status': int(resA.status), 'solver_message': str(resA.message)})
gr = packA(gA, 'Naive top 20 by objective coefficient (no floor, no state cap)')
gr['meets_confirmed_floor'] = gr['confirmed_no_course_selected'] >= 14
gr['max_state_share_ok'] = (gr['dispersion']['max_state_share'] or 0) <= 0.4
track_a_ilp = {
    'formulation': {'decision': 'y_j in {0,1} for each district j that confirmed no dedicated K-8 course (49) or replied unclear / in progress (63)',
                    'objective': 'maximize sum_j y_j * w_j * (1 + poverty_j / 100) * tau_s(j)',
                    'terms': 'w_j = K-8 enrollment; poverty_j = Census SAIPE child poverty % (a missing value contributes a factor of 1 and is flagged); tau_s = 1 + 0.15 * enforcement teeth score',
                    'constraints': ['sum_j y_j <= 20   (one rollout wave)', 'sum_{j in NoCourse} y_j >= 14   (at least 70% of a full wave confirmed no course)', 'sum_{j in S} y_j <= 0.40 * sum_j y_j   for every state S']},
    'counts': dict(Counter(A_['k8_program'])), 'districts_without_enrollment_excluded': int((pool['k8_program'].isin(['none', 'unclear', 'pending']) & pool['k8_enrollment'].isna()).sum()),
    'poverty_missing': int(A_['child_poverty_pct'].isna().sum()), 'milp': mA, 'greedy': gr,
    'mandate_illusion_districts_in_portfolio': [d['district'] for d in mA['districts'] if ST[d['state']]['markers']['explicit_k8_mandate']['value'] is True and d['reply_class'] == 'none'],
}
write('outreach_priority.json', {
    'purpose': 'Prescriptive layer: two 0-1 integer linear programs solved with scipy.optimize.milp (HiGHS). They say where follow-up and outreach effort would matter most under stated limits. They are not judgements about any district.',
    'scope': 'North Carolina (115 districts, complete census) is the completed validation study. The 12-state expansion (1,007 districts, requests sent 2026-10-28 to 2026-11-03) is the active operational testbed these programs allocate.',
    'track_b_ilp': track_b_ilp, 'track_a_ilp': track_a_ilp,
})

# ------------------------------------------------------------------ 5c. cohorts (what is and is not in each denominator)
asked_ = df[df['delivered']]
rev_ = asked_[asked_['reply_status'].isin(['replied', 'no_reply_on_file'])]
nc_ = rev_[rev_['state'] == 'NC']; non_ = rev_[rev_['state'] != 'NC']
queued = asked_[asked_['reply_status'] == 'not_reviewed']
nrep = lambda d_: int((d_['reply_status'] == 'replied').sum())
rate = lambda d_: nrep(d_) / len(d_) if len(d_) else None
cohorts = {
    'definition': 'Tier 1 is North Carolina, a complete state census requested on one day and observed for the full window. Tier 1b is the other reviewed districts: their inboxes were audited, but only 0-1 business days after the request, so they are an early snapshot, not a complete window. Tier 2 is queued for inbox audit and sits in no denominator below.',
    'raw_all_requests': {'districts': int(len(asked_)), 'replied': nrep(asked_), 'reply_rate': rate(asked_), 'note': 'Counts every request in the denominator, including districts whose replies have not been looked at.'},
    'reviewed_cohort': {'districts': int(len(rev_)), 'replied': nrep(rev_), 'reply_rate': rate(rev_), 'states': sorted(rev_['state'].unique())},
    'tier1_north_carolina': {'districts': int(len(nc_)), 'replied': nrep(nc_), 'reply_rate': rate(nc_), 'observation_window_business_days': lat['NC']['observation_window_business_days']},
    'tier1b_other_reviewed_early_snapshot': {'districts': int(len(non_)), 'replied': nrep(non_), 'reply_rate': rate(non_), 'max_observation_window_business_days': int(max(v_['max_elapsed_bd'] for k_, v_ in st_obs.items() if k_ != 'NC')),
                                              'by_state': {st_: {'reviewed': int(len(g_)), 'replied': nrep(g_)} for st_, g_ in non_.groupby('state')}},
    'tier2_queued_for_inbox_audit': {'districts': int(len(queued)), 'excluded_from_denominators': True, 'by_state': {st_: int(n_) for st_, n_ in queued['state'].value_counts().sort_index().items()},
                                      'states_with_no_reviewed_districts': sorted(set(asked_['state']) - set(rev_['state'])),
                                      'k8_students': int(queued['k8_enrollment'].sum())},
    'spending_test_by_cohort': {
        'north_carolina_repliers': {lab: nonparam(R[R['state'] == 'NC'], c) for c, lab in COLS.items()},
        'other_reviewed_repliers': {lab: nonparam(R[R['state'] != 'NC'], c) for c, lab in COLS.items()},
        'all_reviewed_repliers': {lab: nonparam(R, c) for c, lab in COLS.items()}},
}
em = json.loads((OUT / 'econometric_models.json').read_text())
em['cohorts'] = cohorts
em['milp_calibration'] = {'effort_proxy': effort_proxy, 'reply_propensity': propensity,
                          'monte_carlo': {'draws': N_MC, 'propensity_perturbation': '+/-30% uniform', 'effort_perturbation': '+/-25% uniform', 'output': 'data/analysis/milp_sensitivity.json'}}
write('econometric_models.json', em)

# ------------------------------------------------------------------ 5d. external outcomes and community financial vulnerability
O = df[df['k8_enrollment'].notna()].copy()
def sp_(d_, a_, b_):
    d_ = d_.dropna(subset=[a_, b_])
    if len(d_) < 10: return {'n': int(len(d_)), 'error': 'too few'}
    r_ = stats.spearmanr(d_[a_], d_[b_]); return {'n': int(len(d_)), 'rho': float(r_.statistic), 'p_value': float(r_.pvalue)}
Rm = R.copy()
mwm = lambda col: mw_exact(Rm.loc[Rm['k8_program'] == 'none', col], Rm.loc[Rm['k8_program'] != 'none', col])
def vul(d_):
    d_ = d_[d_['k8_enrollment'].notna()]
    tot = float(d_['k8_enrollment'].sum()); known = d_[d_['financial_vulnerability_flags'].notna()]
    cat = {'neither': known[known['financial_vulnerability_flags'] == 0], 'one_flag': known[known['financial_vulnerability_flags'] == 1], 'both_flags': known[known['financial_vulnerability_flags'] == 2]}
    inc = known[known['low_income_county'] == True]; bra = known[known['low_bank_access_county'] == True]
    out_ = {'districts': int(len(d_)), 'k8_students': int(tot), 'students_with_county_data': int(known['k8_enrollment'].sum()),
            'low_income_county_students': int(inc['k8_enrollment'].sum()), 'low_bank_access_county_students': int(bra['k8_enrollment'].sum()),
            'by_flag_count': {k_: {'districts': int(len(v_)), 'k8_students': int(v_['k8_enrollment'].sum())} for k_, v_ in cat.items()}}
    kn = out_['students_with_county_data'] or 1
    out_['share_either_flag'] = (out_['by_flag_count']['one_flag']['k8_students'] + out_['by_flag_count']['both_flags']['k8_students']) / kn
    out_['share_both_flags'] = out_['by_flag_count']['both_flags']['k8_students'] / kn
    out_['share_low_income'] = out_['low_income_county_students'] / kn
    out_['share_low_bank_access'] = out_['low_bank_access_county_students'] / kn
    return out_
rep_ = df[df['reply_status'] == 'replied']
write('outcomes_and_vulnerability.json', {
    'math_outcomes': {'measure': 'EdFacts grade 8 mathematics, % proficient (midpoint), 2018, districts with data; ecological and a different vintage from the 2023 federal layers',
                      'districts_with_math': int(df['math8_proficiency_pct'].notna().sum()),
                      'spearman_math_vs_spending': {'all_matched': sp_(df, 'math8_proficiency_pct', 'instruction_spend_per_pupil'), 'north_carolina': sp_(df[df['state'] == 'NC'], 'math8_proficiency_pct', 'instruction_spend_per_pupil')},
                      'spearman_math_vs_child_poverty': {'all_matched': sp_(df, 'math8_proficiency_pct', 'child_poverty_pct'), 'north_carolina': sp_(df[df['state'] == 'NC'], 'math8_proficiency_pct', 'child_poverty_pct')},
                      'mann_whitney_no_course_vs_other_replies': mwm('math8_proficiency_pct'),
                      'reading': 'Whether a district confirms a K-8 financial-literacy course is tested against its grade 8 math proficiency. A relationship would not show that one causes the other.'},
    'student_financial_vulnerability': {
        'definition': 'A county is flagged low-income when its SAIPE median household income is in the bottom quartile of counties containing an audited district, and low-bank-access when FDIC branches per 10,000 residents are in that bottom quartile. A district takes its county\'s flags. Flag count 0, 1 or 2 is the Student Financial Vulnerability Index.',
        'cutoffs': json.load(open(ROOT / 'data/processed/enrichment_manifest.json'))['external_outcomes']['vulnerability_cutoffs'],
        'confirmed_no_course': vul(df[df['k8_program'] == 'none']), 'replied_other': vul(df[(df['reply_status'] == 'replied') & (df['k8_program'] != 'none')]),
        'no_reply_on_file': vul(df[df['reply_status'] == 'no_reply_on_file']), 'all_asked': vul(df[df['delivered']]),
        'caveat': 'County indicators describe the county, not the district or the child. Branch density ignores online and credit-union access.'},
})

# ------------------------------------------------------------------ 5e. counterfactual backtest of the 2026-08-10 North Carolina follow-up wave
CFG = json.load(open(ROOT / 'data/audit/schedule_config.json'))
CUT, K54 = CFG['backtest']['followup_date'], CFG['backtest']['followup_budget_districts']
story = {d_['leaid']: d_ for d_ in json.load(open(ROOT / 'story/data/districts.json'))}
bt = pm[pm['state'] == 'NC'].copy()
bt['first_reply'] = [story[l_]['first_reply_date'] for l_ in bt['leaid']]
bt['fu'] = [story[l_]['follow_up_date'] == CUT for l_ in bt['leaid']]
bt['replied_before'] = [isinstance(r_, str) and r_ < CUT for r_ in bt['first_reply']]
assert int(bt['fu'].sum()) == K54 and not (bt['fu'] & bt['replied_before']).any()
assert bt[PX + ['k8_enrollment']].notna().all().all() and bt['locale_type'].notna().all()
# propensity fitted ONLY on what was knowable before the wave: replies dated before the follow-up date
lg0 = sm.Logit(bt['replied_before'].astype(float), sm.add_constant(bt[PX].astype(float))).fit(disp=0, maxiter=200)
bt['p_pre'] = lg0.predict(sm.add_constant(bt[PX].astype(float)))
bt['tau'] = df.loc[bt.index, 'tau']
bt['p_final'] = df.loc[bt.index, 'p_hat']
U_NC = float(bt.loc[bt['delivered'], 'k8_enrollment'].sum())
pool_ = bt[~bt['replied_before']].copy().reset_index(drop=True)
pool_['after'] = [isinstance(r_, str) and r_ >= CUT for r_ in pool_['first_reply']]
pool_['det'] = pool_['after'] & pool_['k8_program'].isin(['none', 'partial'])     # only a determinate reply narrows the interval


def top_k(p_col):
    obj = (pool_['k8_enrollment'] * pool_[p_col] * pool_['tau']).values
    r_ = milp(c=-obj, constraints=[LinearConstraint(np.ones((1, len(pool_))), K54, K54)], integrality=np.ones(len(pool_)), bounds=Bounds(0, 1))
    assert r_.success, r_.message
    x_ = np.round(r_.x).astype(bool)
    greedy = set(np.argsort(-obj, kind='stable')[:K54])
    return x_, greedy == set(np.where(x_)[0])


def observed(g):
    return {'districts': int(len(g)), 'k8_students': int(g['k8_enrollment'].sum()), 'replies_on_or_after_followup_date': int(g['after'].sum()),
            'determinate_replies': int(g['det'].sum()), 'determinate_k8_students': int(g.loc[g['det'], 'k8_enrollment'].sum()),
            'realized_width_reduction_pts': float(100 * g.loc[g['det'], 'k8_enrollment'].sum() / U_NC)}


def modelled(g, p_col):
    return {'expected_replies': float(g[p_col].sum()), 'expected_width_reduction_pts': float(100 * (g[p_col] * g['k8_enrollment']).sum() / U_NC)}


act = pool_['fu'].values.astype(bool)


def compare(p_col):
    sel, same_as_sort = top_k(p_col)
    A, M, O, Mo, Ao = pool_[act], pool_[sel], pool_[act & sel], pool_[sel & ~act], pool_[act & ~sel]
    base = observed(O)
    lo = base['determinate_k8_students']
    hi = lo + int(Mo['k8_enrollment'].sum())
    r_det = float(O['det'].mean())
    k_ = float(O['after'].sum() / O[p_col].sum())
    det_share = float(O['det'].sum() / O['after'].sum()) if O['after'].sum() else 0.0
    q_ = np.clip(k_ * Mo[p_col], 0, 1)
    flat = lo + float(r_det * Mo['k8_enrollment'].sum())
    weighted = lo + float((q_ * det_share * Mo['k8_enrollment']).sum())
    pts = lambda s_: float(100 * s_ / U_NC)
    actual_obs = observed(A)
    return {'milp_equals_simple_sort': bool(same_as_sort), 'overlap_districts': int(len(O)), 'overlap_share_of_actual': float(len(O) / len(A)),
            'actual': {**observed(A), 'model': modelled(A, p_col)},
            'milp': {'districts': int(len(M)), 'k8_students': int(M['k8_enrollment'].sum()), 'model': modelled(M, p_col)},
            'overlap_observed': base, 'actual_only_observed': observed(Ao),
            'milp_only_observed_without_that_notice': observed(Mo),
            'milp_counterfactual_realized': {
                'bounds_pts': [pts(lo), pts(hi)], 'bounds_determinate_k8_students': [lo, hi],
                'estimate_flat_overlap_rate': {'determinate_conversion_rate': r_det, 'width_reduction_pts': pts(flat), 'expected_replies': float(O['after'].sum() + len(Mo) * O['after'].mean())},
                'estimate_propensity_weighted': {'calibration_factor': k_, 'determinate_share_of_replies': det_share, 'width_reduction_pts': pts(weighted), 'expected_replies': float(O['after'].sum() + q_.sum())},
                'beats_actual_without_assumptions': bool(pts(lo) > actual_obs['realized_width_reduction_pts'])},
            'picks': [{'district': r_['name'], 'k8_enrollment': int(r_['k8_enrollment']), 'pre_wave_propensity': float(r_[p_col]), 'in_actual_wave': bool(act[i_]), 'in_milp': bool(sel[i_])}
                      for i_, r_ in pool_.iterrows() if act[i_] or sel[i_]]}


primary = compare('p_pre')
look = compare('p_final'); look.pop('picks')
write('backtest_nc_aug10.json', {
    'question': f'On {CUT}, {K54} North Carolina districts were followed up by hand. Which {K54} would the Model 1 program have chosen from what was known that morning?',
    'state_before_wave': {'districts': int(len(bt)), 'replied_before': int(bt['replied_before'].sum()), 'silent_pool': int(len(pool_)), 'followed_up': int(act.sum()), 'silent_not_followed_up': int((~act).sum()),
                          'replied_after_followed': int(pool_.loc[act, 'after'].sum()), 'replied_after_not_followed': int(pool_.loc[~act, 'after'].sum()),
                          'replied_on_the_followup_date_itself': int((pool_['first_reply'] == CUT).sum()), 'observed_through': lat['NC']['review_through']},
    'program': f'maximize sum x_i w_i p_i tau subject to sum x_i = {K54}, x binary, over the silent pool. One state, so tau is constant and the per-state cap does not apply; with only a head-count constraint the program is equivalent to a sort, and is reported as such.',
    'propensity_pre_wave': {'fit': f'logistic regression on all {len(bt)} NC districts, outcome = replied before {CUT}; no later information used', 'events': int(bt['replied_before'].sum()), 'n': int(len(bt)),
                            'coefficients': {k: float(v) for k, v in lg0.params.items()}},
    'universe_nc_k8_students': int(U_NC),
    'result': primary,
    'sensitivity_with_look_ahead_propensity': {'warning': 'Uses the final propensity model, fitted on replies that arrived after the wave. Shown only to size the effect of that information.', **look},
    'caveats': ['Neither the actual wave nor the counterfactual was randomised. Districts that were followed up may differ from those that were not.',
                'Outcomes for districts the program picks but nobody followed up are not observed under a follow-up. The bounds assume nothing about them; the two estimates assume they would behave like the overlap.',
                'Model-expected values score both portfolios with the same model the program maximises, so the program wins on that measure by construction. It is not evidence that it would have won in the field.',
                'Reply dates are dates only. A reply dated on the follow-up date cannot be ordered against the notice.'],
})

# ------------------------------------------------------------------ 5f. four-week rolling-horizon follow-up schedule
W, GAM = CFG['wave_dates'], CFG['gamma']
T = len(W)


def eligible_on(r, day):
    rt, days, _ = rule(r['state'])
    if rt == 'fixed_calendar_days' and days is not None:
        return cdays(r['request_date'], day) >= days
    return bdays(r['request_date'], day) >= window(r['state'])


E_it = np.array([[eligible_on(r_, d_) for d_ in W] for _, r_ in B_.iterrows()], dtype=float)
states_r = sorted(B_['state'].unique())


def wave_cap(hours):
    return int(max(1, np.floor(CFG['per_state_cap_share'] * np.floor(hours))))


def solve_horizon(H, elig, gam):
    """x[i, t] flattened row-major. Returns the binary matrix and solver facts."""
    n, T_ = elig.shape
    Bt, cap = H / T_, wave_cap(H / T_)
    obj = np.array([B_['coef'].values * gam ** t_ for t_ in range(T_)]).T.ravel()
    cons = [LinearConstraint(sparse.kron(sparse.eye(n), np.ones((1, T_))), -np.inf, 1),
            LinearConstraint(sparse.kron(B_['cost'].values.reshape(1, -1), sparse.eye(T_)), -np.inf, Bt)]
    ind = sparse.csr_matrix(np.array([(B_['state'] == st_).values for st_ in states_r], dtype=float))
    cons.append(LinearConstraint(sparse.kron(ind, sparse.eye(T_)), -np.inf, cap))
    r_ = milp(c=-obj, constraints=cons, integrality=np.ones(n * T_), bounds=Bounds(0, elig.ravel()), options={'mip_rel_gap': 1e-6, 'time_limit': 120})
    assert r_.success, r_.message
    X = np.round(r_.x).reshape(n, T_).astype(int)
    assert (X.sum(1) <= 1).all() and (X <= elig).all() and (B_['cost'].values @ X <= Bt + 1e-9).all()
    return X, Bt, cap, {'solver_status': int(r_.status), 'mip_gap': float(getattr(r_, 'mip_gap', 0) or 0), 'objective_discounted': float(-r_.fun)}


def summary(idx, H):
    g = B_.iloc[idx]
    return {'districts': int(len(g)), 'hours_used': float(g['cost'].sum()), 'hours_idle': float(H - g['cost'].sum()), 'utilization': float(g['cost'].sum() / H),
            'k8_students': int(g['k8_enrollment'].sum()), 'expected_width_reduction_pts': float((g['width_pts'] * g['p_hat']).sum()), 'max_width_reduction_pts': float(g['width_pts'].sum()),
            'by_state': dict(sorted(Counter(g['state']).items()))}


horizons = {}
for H in CFG['horizon_budgets_hours']:
    X, Bt, cap, facts = solve_horizon(H, E_it, GAM)
    waves = []
    for t_, day in enumerate(W):
        idx = np.where(X[:, t_] == 1)[0]
        g = B_.iloc[idx].sort_values('coef', ascending=False)
        waves.append({'week': t_ + 1, 'date': day, 'budget_hours': Bt, **summary(idx, Bt), 'eligible_districts': int(E_it[:, t_].sum()),
                      'assignments': [{'district': r_['name'], 'state': r_['state'], 'k8_enrollment': int(r_['k8_enrollment']), 'hours': float(r_['cost']), 'reply_propensity': float(r_['p_hat']),
                                       'business_days_since_request': bdays(r_['request_date'], day), 'inbox_last_reviewed': r_['reply_review_through'],
                                       'interval_width_reduction_pts': float(r_['width_pts'])} for _, r_ in g.iterrows()]})
    # same budget, single period: (a) the published static plan (eligibility at the last inbox review); (b) one period with the calendar advanced to week 1
    capH = int(np.floor(CFG['per_state_cap_share'] * H))
    one = milp(c=-B_['coef'].values, constraints=[LinearConstraint(np.array([B_['cost'].values] + [(B_['state'] == st_).astype(float).values for st_ in states_r]), -np.inf, np.array([H] + [capH] * len(states_r)))],
               integrality=np.ones(len(B_)), bounds=Bounds(0, E_it[:, 0]), options={'mip_rel_gap': 1e-6, 'time_limit': 120})
    assert one.success, one.message
    static = budgets[str(H)]['milp']
    # same program with the state velocity multiplier switched off (every state behaves like North Carolina)
    keep_p, keep_c = B_['p_hat'].copy(), B_['coef'].copy()
    B_['p_hat'] = B_['p_nc']; B_['coef'] = B_['k8_enrollment'] * B_['p_nc'] * B_['tau']
    Xn = solve_horizon(H, E_it, GAM)[0]
    nc_only = summary(np.where(Xn.sum(1) == 1)[0], H)
    nc_only['districts_shared_with_main_schedule'] = int(((Xn.sum(1) == 1) & (X.sum(1) == 1)).sum())
    B_['p_hat'] = keep_p; B_['coef'] = keep_c
    chosen = B_[X.sum(1) == 1]
    ceil = chosen[chosen['p_hat'] >= 0.949]
    horizons[str(H)] = {'horizon_hours': H, 'without_state_velocity': nc_only,
                        'at_propensity_ceiling': {'districts': int(len(ceil)), 'expected_width_reduction_pts': float((ceil['width_pts'] * ceil['p_hat']).sum())}, 'weekly_hours': Bt, 'per_state_cap_per_week': cap, **facts,
                        'rolling': summary(np.where(X.sum(1) == 1)[0], H), 'waves': waves,
                        'static_as_published': {'districts': static['districts_selected'], 'hours_used': static['hours_used'], 'hours_idle': float(H - static['hours_used']), 'utilization': float(static['hours_used'] / H),
                                                'k8_students': static['k8_students'], 'expected_width_reduction_pts': static['expected_width_reduction_pts'], 'max_width_reduction_pts': static['max_width_reduction_pts'], 'by_state': static['dispersion']['by_state']},
                        'single_period_at_week1_clock': {'per_state_cap': capH, **summary(np.where(np.round(one.x) == 1)[0], H)}}
queue = df[df['delivered'] & (df['reply_status'] == 'not_reviewed')]
write('rolling_horizon_schedule.json', {
    'formulation': {'decision': 'x_{i,t} in {0,1}: follow up district i in weekly wave t', 'objective': f'maximize sum_t sum_i gamma^(t-1) x_it w_i p_i tau_s(i), gamma = {GAM}',
                    'constraints': ['sum_t x_it <= 1 for every district i', 'x_it = 0 unless district i has passed its state window (verified statutory deadline, else 5 business days) by the date of wave t', 'sum_i c_i x_it <= H / 4 in every wave', 'sum_{i in S} x_it <= max(1, floor(0.35 floor(H / 4))) for every state S and wave t']},
    'wave_dates': W, 'gamma': GAM, 'headline_budget_hours': CFG['headline_budget_hours'], 'pool': 'districts whose inbox was reviewed and showed no reply, with enrollment and a propensity', 'pool_size': int(len(B_)),
    'eligible_by_week': [int(E_it[:, t_].sum()) for t_ in range(T)],
    'reading': 'Every state window in the pool has already expired by the first wave, so the schedule does not cascade state by state as clocks run out. The static plan sat partly idle because it measured eligibility at the last inbox review; advancing the calendar alone fills the hours. What the horizon adds is a weekly sequence under weekly capacity and per-state caps.',
    'what_expected_narrowing_means': 'sum of reply propensity times enrollment share. It treats any reply as settling that district; in practice some replies are unclear, so it overstates. The propensity is that of replying at all, not the extra effect of a follow-up.',
    'before_sending': 'Reply status is only known to the last inbox review. Re-check the inbox before any notice; a district that has replied is dropped, not followed up.',
    'audit_first_queue': {'note': 'Districts whose inbox has not been reviewed. Their status is unknown, so they receive no follow-up hours and are never treated as silent.', 'districts': int(len(queue)),
                          'by_state': {k_: int(v_) for k_, v_ in queue['state'].value_counts().sort_index().items()}, 'states_with_no_district_in_the_schedule_pool': sorted(set(queue['state']) - set(B_['state']))},
    'horizons': horizons,
})

# ------------------------------------------------------------------ 5g. administrative triangulation (state course records against FOIA replies)
rec = json.load(open(ROOT / 'data/processed/nc_course_records.json'))
ncd = df[(df['state'] == 'NC') & df['delivered']].copy()
ncd['rec'] = [rec['by_leaid'].get(l_) for l_ in ncd['leaid']]
cls = {'foia_program': ncd['k8_program'] == 'partial', 'foia_no_course': ncd['k8_program'] == 'none',
       'foia_unclear_or_pending': (ncd['reply_status'] == 'replied') & ~ncd['k8_program'].isin(['none', 'partial']), 'foia_no_reply': ncd['reply_status'] != 'replied'}
avail = bool(rec['available'])
cell = lambda m_, v_: int((m_ & ncd['rec'].map(lambda r_: r_ is v_)).sum()) if avail else None
CODE = r'\b(?:EY|CS|BF|BB|WB|ME)\d{2}[A-Z0-9]{0,4}\b'
named = ncd[ncd['reply_text'].fillna('').str.contains(CODE, regex=True)]
silent = int(cls['foia_no_reply'].sum())
write('triangulation_nc.json', {
    'state_record_available': avail, 'state_record_status': rec['status'], 'districts': int(len(ncd)),
    'foia_margin': {k_: int(v_.sum()) for k_, v_ in cls.items()},
    'matrix': {'verified_active': cell(cls['foia_program'], True), 'silent_but_state_record_shows_course': cell(cls['foia_no_reply'], True),
               'confirmed_gap': int(cls['foia_no_course'].sum()) - (cell(cls['foia_no_course'], True) or 0), 'discordant_foia_no_course_state_record_shows_course': cell(cls['foia_no_course'], True),
               'unobserved': int((cls['foia_no_reply'] & ncd['rec'].isna()).sum()), 'by_class_and_record': {k_: {'course_on_record': cell(v_, True), 'no_course_on_record': cell(v_, False), 'record_missing': int((v_ & ncd['rec'].isna()).sum())} for k_, v_ in cls.items()}},
    'replies_naming_a_state_course_code': [{'district': r_['name'], 'codes': sorted(set(re.findall(CODE, r_['reply_text']))), 'reply_class': r_['k8_program'], 'state_record': (None if pd.isna(r_['rec']) else bool(r_['rec']))} for _, r_ in named.iterrows()],
    'discordance_bounds': {
        'silent_districts_with_a_course': {'districts': silent, 'lower': (cell(cls['foia_no_reply'], True) or 0) / silent, 'upper': ((cell(cls['foia_no_reply'], True) or 0) + int((cls['foia_no_reply'] & ncd['rec'].isna()).sum())) / silent},
        'code_naming_replies_not_borne_out': {'replies': int(len(named)), 'lower': float(sum(1 for v_ in named['rec'] if v_ is False) / len(named)) if len(named) else None,
                                              'upper': float(sum(1 for v_ in named['rec'] if v_ is not True) / len(named)) if len(named) else None}},
    'reading': 'Without a state record these bounds are the whole unit interval: the second source has not yet reduced any uncertainty.' if not avail else 'A missing state record stays missing; it is not read as no course.',
})

# ------------------------------------------------------------------ 5h. closed-loop deployment tracker (hand-kept log, validated here)
dl_path = ROOT / 'data/audit/deployment_log.json'
dlog = json.load(open(dl_path))
plan25 = {(d_['district'], d_['state']): d_ for d_ in budgets['25']['milp']['districts']}
silent_pool = {(r_['name'], r_['state']): float(r_['width_pts']) for _, r_ in B_.iterrows()}
notices = dlog['model1_followup_wave']['notices']
keys = [(n_['district'], n_['state']) for n_ in notices]
assert len(keys) == len(set(keys)), 'one notice per district'
assert all(k_ in silent_pool for k_ in keys), 'every logged notice must be a reviewed, silent district in the follow-up pool'
assert all(n_.get('sent_date') and n_.get('source') for n_ in notices), 'every notice needs a date and a source'
scheduled = {(a_['district'], a_['state']) for h_ in horizons.values() for w_ in h_['waves'] for a_ in w_['assignments']} | set(plan25)
conv = [n_ for n_ in notices if n_.get('reply_date_after_notice')]
real = float(sum(silent_pool[(n_['district'], n_['state'])] for n_ in conv if n_.get('reply_class') in ('none', 'partial')))   # only a determinate reply narrows the interval
nc_fu = df[(df['state'] == 'NC') & df['follow_up_date'].notna()]
write('deployment_impact.json', {
    'log_file': 'data/audit/deployment_log.json (hand-kept; every entry needs a date and a source)',
    'model1_followup_wave': {'planned_districts': len(plan25), 'planned_hours': budgets['25']['milp']['hours_used'], 'notices_sent': len(notices), 'notices_in_a_computed_plan': sum(1 for k_ in keys if k_ in scheduled), 'converted_silent_to_replied': len(conv),
                             'realized_width_reduction_pts': real, 'status': dlog['model1_followup_wave']['status'], 'planned_max_width_reduction_pts': budgets['25']['milp']['max_width_reduction_pts'],
                             'portfolio': [{'district': k_[0], 'state': k_[1], 'interval_width_reduction_pts': v_['interval_width_reduction_pts']} for k_, v_ in plan25.items()]},
    'pre_model_followup_for_context': {'what': 'North Carolina follow-up notices sent 2026-08-10, before the MILP existed and not chosen by it',
                                       'notices': int(len(nc_fu)), 'replied_after_notice': int(((nc_fu['reply_status'] == 'replied') & (nc_fu['reply_date'] > nc_fu['follow_up_date'])).sum()),
                                       'caution': 'Notices were not assigned at random; this does not measure what a follow-up causes.'},
    'institutional_deployments': dlog['institutional_deployments'], 'open_data_downloads': dlog['open_data_downloads'],
})

# ------------------------------------------------------------------ 6. explorer trendlines (every number the scatter callouts show)
def trend(d, x, y):
    d = d.dropna(subset=[x, y])
    if len(d) < 8 or d[x].nunique() < 3 or d[y].nunique() < 2:
        return {'n': int(len(d)), 'error': 'too few points'}
    lr = stats.linregress(d[x], d[y])
    sp = stats.spearmanr(d[x], d[y])
    return {'n': int(len(d)), 'slope': lr.slope, 'intercept': lr.intercept, 'pearson_r': lr.rvalue, 'p_value': lr.pvalue,
            'spearman_rho': sp.statistic, 'spearman_p': sp.pvalue, 'significant_at_0.05': bool(lr.pvalue < 0.05)}


E = m.copy()
E['latency_bdays'] = [max(bdays(a, b), 0) if (r == 'replied' and a and b) else np.nan for a, b, r in zip(E['request_date'], E['reply_date'], E['reply_status'])]
E['no_course'] = np.where(E['reply_status'] == 'replied', (E['k8_program'] == 'none').astype(float), np.nan)
E['replied_flag'] = E['replied']
write('explorer_trends.json', {
    'note': 'OLS on the points shown. Latency uses replied districts only (non-repliers have no reply date, so are not plotted). no_course is a 0/1 outcome among replied districts (linear probability fit).',
    'trends': {xv: {yv: {'all_states': trend(E, xv, yv), 'north_carolina': trend(E[E['state'] == 'NC'], xv, yv)}
                    for yv in ('latency_bdays', 'no_course', 'replied_flag')}
               for xv in ('child_poverty_pct', 'instruction_spend_per_pupil')},
})

# ------------------------------------------------------------------ public copies for download
import shutil
PUB = ROOT / 'public' / 'data' / 'analysis'
PUB.mkdir(parents=True, exist_ok=True)
for src in ['data/processed/districts_enriched.csv', 'data/processed/districts_enriched.json', 'data/processed/enrichment_manifest.json', 'data/analysis/enforcement_teeth.json',
            'data/analysis/econometric_models.json', 'data/analysis/manski_bounds.json', 'data/analysis/student_weighted_impact.json',
            'data/analysis/reply_similarity.json', 'data/analysis/outreach_priority.json', 'data/analysis/milp_sensitivity.json', 'data/analysis/outcomes_and_vulnerability.json', 'data/analysis/deployment_impact.json', 'data/analysis/backtest_nc_aug10.json', 'data/analysis/rolling_horizon_schedule.json', 'data/analysis/triangulation_nc.json', 'data/processed/nc_course_records.json', 'scripts/ingest_course_records.py', 'scripts/log_followup.py', 'data/audit/foia_deadlines.csv', 'data/audit/unmatched_leaids.csv',
            'data/audit/state_marker_coding.csv', 'data/audit/manual_leaid_overrides.csv',
            'scripts/enrich_districts.py', 'scripts/run_analysis.py']:
    shutil.copyfile(ROOT / src, PUB / Path(src).name)
print('analysis written to', OUT)
