"""Plain-language introductions and compact tables for the 2024-25 reports.

Presentation only: numbers are read from the generated CSV companions.
Rerun render_evidence_report_pages.py after updating a report or its table.
"""
import csv
from html import escape
from pathlib import Path
CORRECTION='Grade-profile correction: 2026-11-06'
MEASURES=('BA+ is the share of adults aged 25 or older with a bachelor’s degree or higher in the census tract containing the school. '
          'Income is that tract’s median household income. School poverty (SEP) is the share of enrolled pupils that ODE identifies as experiencing poverty. '
          'The tract measures describe nearby adults and households; SEP describes the school’s pupils. Neither identifies the circumstances of an individual tested student.')
TERMS=('A model fit summarizes differences among schools. R-squared measures the share of the observed variation in school proficiency that the fitted model accounts for; '
       '0.60 means 60% of that variation in the analyzed sample. It does not mean that context causes 60% of a pupil’s result. '
       'Held-out R-squared tests predictions for schools left out of fitting. A negative value means predictions were worse than using the held-out group’s weighted mean. '
       'A standardized coefficient (beta) expresses the association in standard-deviation units while holding the other included predictors fixed. It is not a percentage-point effect.')
PURPOSE={
'income_education_joint_model_report':('Do income and adult education tell us different things?', 'Both tend to rise alongside school proficiency. We fit a model using both measures to ask whether each still has an association after accounting for the other. A companion model replaces tract income with school poverty.'),
'income_education_split_stability_report':('Would the result change if we studied different schools?', 'We check whether the relative associations of income (or school poverty) and adult education depend heavily on which schools enter the analysis. Before each of 20 splits, we freshly reshuffle the full eligible school list, divide it into two disjoint halves, and fit a model to each half: 40 fits. The spread describes sensitivity to school selection, not change over time or a confidence interval.'),
'income_education_attendance_joint_model_report':('How does attendance relate to proficiency alongside socioeconomic context?', 'Schools differ in regular attendance as well as income, adult education and poverty. The combined models describe adjusted attendance associations and prediction for schools left out of fitting; they do not compare against otherwise identical models without attendance. This is annual attendance during 2024–25, not participation in the achievement test.'),
'income_education_attendance_interaction_report':('Does the association depend on the other conditions?', 'A simple additive model assumes the same income association at every attendance level, for example. We add all three pairwise products together: context × BA+, context × attendance, and BA+ × attendance. This tests the bundle, not an attendance-specific interaction. Both versions use the same schools and the same held-out groups, so their difference is a fairer comparison than simply adding terms and judging the fit to the original sample.'),
'income_poverty_reassessment_note_2026-02-20':('Does school poverty predict proficiency better than neighborhood income?', 'We compare three models: one with tract income, one with school poverty, and one with both. Each also includes adult education and annual attendance. Predictions are tested on schools left out of fitting. Model coverage can differ when a required value is unavailable, so the companion coverage table matters as well as the prediction score.'),
'ba_signal_in_high_poverty_summary_2026-02-21':('Does adult education remain associated within high-poverty elementary schools?', 'We group schools by the share of enrolled pupils experiencing poverty, then examine the adult-education association within those groups. This asks whether the overall BA+ gradient merely reflects a contrast between low- and high-poverty schools. Within-band estimates can be less stable because there are fewer schools and a narrower range of conditions.'),
'why_poverty_outpredicts_income_explainer_2026-02-21':('Why might school poverty predict better than tract income?', 'School poverty measures the circumstances of enrolled pupils more directly than the income of households around a school building. This is a possible explanation for its stronger prediction in these models, not proof of a causal mechanism. The numerical comparisons below keep that interpretation separate from the observed result.'),
'statistical_results_overview':('What have the statistical checks established?', 'The reports below ask whether the visible SES gradients survive changes in predictors, school selection and model specification. They separate fitting the observed schools from predicting schools left out of the fit. The detailed reports and downloads show how the conclusions were reached.'),
'ses_explorations_summary_report':('How do the different checks fit together?', 'This summary brings together the income, adult-education, poverty and attendance comparisons. It distinguishes recurring findings from checks that are more sensitive to the model or the schools included.'),
'spending_class_size_findings_memo':('Are spending levels strongly associated with proficiency?', 'Reported spending has weak statewide correlations with proficiency and small, uneven contributions in adjusted prediction models. These comparisons do not estimate the effect of increasing funding.'),
}
BAND_EXPLANATION=('Here, low-poverty schools have fewer than 20% of enrolled students identified as SEP; '
                  'middle-poverty schools have 20% to under 40%; high-poverty schools have 40% or more. '
                  'The download also checks 50% or more, a subset of the high-poverty group. These last two groups overlap.')
BAND_TERMS=('A slope describes how much fitted school proficiency differs with BA+. A slope of +2 points per +10 BA+ points means '
            'that a ten-percentage-point difference in tract adult BA+ accompanies a two-percentage-point difference in fitted proficiency. '
            'The adjusted slope compares BA+ at the same school-poverty and regular-attendance percentages within the band. '
            'Added R-squared measures the improvement in fit when BA+ joins those two predictors. These fits use the analyzed schools; '
            'this report does not test predictions on schools left out of fitting or test whether band slopes differ statistically.')
def measures_for(stem):
    measures=MEASURES
    if stem=='spending_class_size_findings_memo':
        return measures.replace('Income is that tract’s median household income.',
            'This report uses tract per-capita income: total income divided by the number of tract residents. Other Evidence Lab models use median household income, so their income coefficients describe a different measure.')
    if stem=='statistical_results_overview':
        return measures.replace('Income is that tract’s median household income.',
            'The elementary SES models use tract median household income; the separate spending models use per-capita income, total tract income divided by its residents.')
    if stem=='ba_signal_in_high_poverty_summary_2026-02-21':
        return measures.replace('Income is that tract’s median household income. ', '')
    return measures

def terms_for(stem):
    return BAND_TERMS if stem=='ba_signal_in_high_poverty_summary_2026-02-21' else TERMS

COMMON_CSV={
'income_education_joint_model_report':'income_education_joint_model_results.csv',
'income_education_split_stability_report':'income_education_split_stability_results.csv',
'income_education_attendance_joint_model_report':'income_education_attendance_joint_model_results.csv',
'income_education_attendance_interaction_report':'income_education_attendance_interaction_results.csv',
}
def introduction(stem):
    title,why=PURPOSE.get(stem,('What this report asks','Read the purpose and definitions alongside the results.'))
    methods_link=''
    if stem=='spending_class_size_findings_memo':
        methods_link='<p>Assessment results, attendance and class size describe 2024–25. The spending memo compares 2023–24 and 2024–25 spending and their two-year average. Neighborhood census measures use ACS 2019–2023 estimates.</p><p><a href="../statistical-results-overview.html?year=2024-25#ridge-regression">How ridge regression handles overlapping measures</a></p>'
    extra='<p>'+escape(BAND_EXPLANATION)+'</p>' if stem=='ba_signal_in_high_poverty_summary_2026-02-21' else ''
    return f'<article class="card report-reading"><h2>{escape(title)}</h2><p>{escape(why)}</p>{extra}{methods_link}</article>'

def reading_notes(stem):
    measures=measures_for(stem)
    attendance=''
    if 'attendance' in stem or 'reassessment' in stem or stem=='ba_signal_in_high_poverty_summary_2026-02-21':
        attendance='<p>Regular attenders missed less than 10% of their enrolled school days. The historical analyses use ODE’s tested-grade attendance rollup. Its included-student count is separate from the count of students with test scores.</p>'
    return '<details class="card"><summary>What the measures and model terms mean</summary><p>'+escape(measures)+'</p><p>'+escape(terms_for(stem))+'</p>'+attendance+'<p>Larger scored-student populations receive more weight. The results describe relationships among schools; they do not follow individual pupils or estimate causal effects.</p></details>'

def band_table(report_dir):
    name='ba_signal_in_high_poverty_summary_2026-09-10.csv'
    with (Path(report_dir)/name).open(newline='') as f:rows=list(csv.DictReader(f))
    selected={(r['subject'],r['poverty_band']):r for r in rows if r['scope']=='elementary' and r['sep_scenario']=='midpoint'}
    body=''
    for subject in ('ELA','Math','Science'):
        low,high=selected[subject,'low_poverty'],selected[subject,'high_poverty']
        body+='<tr><th scope="row">'+escape(subject)+'</th>'+''.join('<td>'+f'{float(value):+.2f}'+'</td>' for value in (low['ba_bivariate_slope_pp_per_10_ba_points'],high['ba_bivariate_slope_pp_per_10_ba_points'],high['adjusted_ba_slope_pp_per_10_ba_points']))+'</tr>'
    return ('<article class="card"><h2>Adult education remains associated with proficiency within the high-poverty group</h2>'
            '<p>These are elementary-school results; school-poverty intervals use their documented midpoints. Each number below is the fitted proficiency difference, in percentage points, associated with a ten-percentage-point difference in tract BA+. '
            'The first two columns fit BA+ alone within each poverty group. The last column also accounts for the school’s poverty percentage and regular attendance within the high-poverty group.</p>'
            '<div class="stats-table-wrap" role="region" aria-label="Poverty-band results; scroll horizontally for all columns" tabindex="0"><table class="stats-table"><thead><tr><th scope="col">Subject</th><th scope="col">Below 20% SEP</th><th scope="col">40% or more SEP</th><th scope="col">40% or more SEP, adjusted</th></tr></thead><tbody>'+body+'</tbody></table></div>'
            '<p>The positive high-poverty slopes show that the overall association is not solely a contrast between the low- and high-poverty groups. '
            'Schools within a band still differ in poverty and many other characteristics. These results do not isolate an effect of neighborhood education or demonstrate a statistically established difference between the band slopes.</p>'
            '<p><a href="../artifacts/reports/'+name+'" download>Download all poverty-band results (CSV)</a></p></article>')

def compact_table(stem, report_dir):
    if stem=='ba_signal_in_high_poverty_summary_2026-02-21':return band_table(report_dir)
    name=COMMON_CSV.get(stem)
    if not name:return ''
    with (Path(report_dir)/name).open(newline='') as f:rows=list(csv.DictReader(f))
    rows=[r for r in rows if r['universe']=='elementary_primary' and r['sep_sensitivity'] in {'as_reported','midpoint'}]
    split='split_stability' in stem; interaction='interaction' in stem
    fields=[('Subject','subject'),('Context measure','context'),('Schools','n_schools')]
    if split:fields += [('Context coefficient: middle 90% of half-sample fits','split_beta_context_p05'),('BA+ coefficient: middle 90% of half-sample fits','split_beta_ba_p05')]
    elif interaction:fields += [('Base model: held-out R²','cv_r2_mean'),('Added held-out R² from interactions','interaction_cv_delta_mean')]
    else:fields += [('Fit to these schools: R²','in_sample_r2'),('Schools left out of fitting: R²','cv_r2_mean')]
    def val(r,k):
        if k=='context':return 'Tract income' if r[k]=='income' else 'School poverty (SEP)'
        if k in {'subject','n_schools'}:return r[k]
        if k.endswith('p05'):return f"{float(r[k]):.3f} to {float(r[k[:-3]+'p95']):.3f}"
        return f'{float(r[k]):.3f}'
    header=''.join('<th scope="col">'+escape(label)+'</th>' for label,_ in fields)
    body=''.join('<tr>'+''.join('<td>'+escape(val(r,k))+'</td>' for _,k in fields)+'</tr>' for r in rows)
    units = ('Coefficients use standard-deviation units: positive values accompany higher proficiency and negative values accompany lower proficiency, holding the other predictor fixed. ' if split else 'R² is the share of variation among school proficiency results accounted for by the model. Held-out values test predictions for schools left out of fitting. ')
    return '<article class="card"><h2>Elementary-school results</h2><p>'+units+'Each row uses the schools with all values required by that model. Full results include middle-school checks and alternative treatments of ODE poverty intervals.</p><div class="stats-table-wrap"><table class="stats-table"><thead><tr>'+header+'</tr></thead><tbody>'+body+'</tbody></table></div><p><a href="../artifacts/reports/'+name+'" download>Download the full results CSV</a></p></article>'
