#!/usr/bin/env python3
"""Shared weighted-model helpers, plus the historical 2024-25 report pipeline.

FOR THE 2025-26 DOWNLOAD: run release_2025_26_analyses.py, not this module.
That entry point uses its own frozen-release loader and year checks. It imports
this module's school-policy/SEP helpers and numerical functions, but never calls
load_subject, load_inputs, build_points, analyze or run_report_cli. The 2024-25
constants and attendance routines below belong to the historical pipeline.
They do not load old data merely because this module is imported.

Reading the shared numerical functions:
- standardize_fit learns weighted centers/scales from the fitting schools only;
  standardize_apply uses those same values for schools held out of the fit.
- fit_model returns standardized coefficients and in-sample weighted R2.
- repeated_cv reshuffles schools before every round of held-out prediction.
- split_coefficients reshuffles before each pair of half-sample fits.
These are school splits, not district splits. Repeat ranges are descriptive
stability checks, not confidence intervals.

In model rows, y is proficiency percent and w is the scored-student count.
ba is a school-site tract adult BA+ fraction; context is household income in
dollars or enrolled-student SEP percent, as chosen by the caller. These are
school aggregates and contextual estimates, not family or student records.
All numerical functions here use only the Python standard library.

HISTORICAL USE: the four report_income_education_* entry points use this module's
2024-25 loaders and report builders. Their --help lists the older pipeline's
options. They are not dependencies of the 2025-26 reproduction bundle.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import io
import json
import math
import random
from pathlib import Path
from typing import Sequence


# Historical 2024-25 source configuration; unused by the 2025-26 runner.
ACADEMIC_YEAR = "2024-2025"
TOTAL_POPULATION = "Total Population (All Students)"
ALL_GRADES = "All Grades"
SOURCE_COMMIT = "6c70d58d278d768a2b8d46dcdf4e7ddfbccc0a98"
SUBJECTS = {
    "English": ("english", "SchoolDataWithAddressesAndCensusSES.csv"),
    "Math": ("math", "SchoolDataMathWithAddressesAndCensusSES.csv"),
    "Science": ("science", "SchoolDataScienceWithAddressesAndCensusSES.csv"),
}
APPROVED_SHA256 = {
    "english": "10828e0b0bb6a5f2794836f5a36e85f6949a58cb2b7a3a14529f303106b6f1a9",
    "math": "076e89da00f4117d6f49a9f279641484407947145d56445e751a3febaa185283",
    "science": "eec291f604325979fba71cbc352f401b5d46664d2e4e02ac9569d3fdb25f9839",
}
ELEMENTARY_GRADES = {"Grade 3", "Grade 4", "Grade 5"}
MIDDLE_GRADES = {"Grade 6", "Grade 7", "Grade 8"}
LEVEL_FIELDS = ["Number Level 1", "Number Level 2", "Number Level 3", "Number Level 4"]
RESULT_FIELDS = [
    "report", "subject", "universe", "context", "sep_sensitivity", "attendance_required",
    "n_schools", "scored_students", "profile_universe_count", "candidate_all_grades", "ordinary_regular",
    "excluded_nonregular", "excluded_charter", "excluded_true_virtual", "excluded_special_enrollment",
    "outcome_identity_valid", "outcome_identity_invalid", "missing_ba", "missing_context",
    "invalid_attendance", "model_complete", "beta_context", "beta_ba", "beta_attendance", "in_sample_r2",
    "cv_repeats", "cv_folds", "cv_r2_mean", "cv_r2_p05", "cv_r2_p95",
    "interaction_in_sample_delta_r2", "interaction_cv_delta_mean",
    "interaction_cv_delta_p05", "interaction_cv_delta_p95", "interaction_cv_share_positive",
    "split_beta_context_p05", "split_beta_context_p95", "split_beta_ba_p05",
    "split_beta_ba_p95", "source_commit", "source_sha256", "academic_year",
]


def file_sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def _read_csv(path: Path) -> list[dict[str, str]]:
    with path.open(newline="", encoding="utf-8-sig") as handle:
        return list(csv.DictReader(handle))


def _rows_from_bytes(payload: bytes) -> list[dict[str, str]]:
    return list(csv.DictReader(io.StringIO(payload.decode("utf-8-sig"), newline="")))


def reconstruct_canonical_chunk_bytes(chunk_payloads: Sequence[bytes]) -> bytes:
    """Recreate the original CSV bytes from repeated-header dashboard chunks."""
    if not chunk_payloads:
        raise ValueError("Production manifest contains no chunks")
    combined = bytearray(chunk_payloads[0])
    first_header = chunk_payloads[0].splitlines(keepends=True)[0]
    for payload in chunk_payloads[1:]:
        lines = payload.splitlines(keepends=True)
        if not lines or lines[0] != first_header:
            raise ValueError("Production chunks do not have an identical CSV header")
        combined.extend(b"".join(lines[1:]))
    return bytes(combined)


def load_subject(data_dir: Path, subject_key: str, filename: str) -> tuple[list[dict[str, str]], str]:
    """Load an approved canonical file or its integrity-checked production chunks."""
    approved = APPROVED_SHA256[subject_key]
    canonical = data_dir / filename
    if canonical.is_file():
        actual = file_sha256(canonical)
        if actual != approved:
            raise ValueError(f"Unapproved {subject_key} input SHA-256: expected {approved}, found {actual}")
        rows = _read_csv(canonical)
    else:
        manifest_path = data_dir / "dashboard_data_manifest.json"
        if not manifest_path.is_file():
            raise FileNotFoundError(f"Missing approved canonical file and production manifest for {filename}")
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        if manifest.get("format_version") != 1:
            raise ValueError("Unsupported dashboard data manifest format_version")
        entry = manifest.get("subjects", {}).get(subject_key)
        if not entry or entry.get("canonical_file") != filename:
            raise ValueError(f"Production manifest has no {subject_key} entry for {filename}")
        if entry.get("source_sha256") != approved:
            raise ValueError(f"Unapproved {subject_key} manifest source SHA-256")
        chunk_payloads: list[bytes] = []
        for chunk in entry.get("chunks", []):
            chunk_name = str(chunk.get("file", ""))
            if not chunk_name or Path(chunk_name).name != chunk_name:
                raise ValueError(f"Unsafe production chunk filename: {chunk_name!r}")
            chunk_path = data_dir / chunk_name
            if not chunk_path.is_file():
                raise FileNotFoundError(f"Missing production chunk: {chunk_path}")
            payload = chunk_path.read_bytes()
            if len(payload) != int(chunk.get("bytes", -1)):
                raise ValueError(f"Production chunk byte-count mismatch: {chunk_path.name}")
            actual_chunk_hash = hashlib.sha256(payload).hexdigest()
            if actual_chunk_hash != chunk.get("sha256"):
                raise ValueError(f"Production chunk SHA-256 mismatch: {chunk_path.name}")
            chunk_rows = _rows_from_bytes(payload)
            if len(chunk_rows) != int(chunk.get("rows", -1)):
                raise ValueError(f"Production chunk row-count mismatch: {chunk_path.name}")
            chunk_payloads.append(payload)
        reconstructed = reconstruct_canonical_chunk_bytes(chunk_payloads)
        reconstructed_hash = hashlib.sha256(reconstructed).hexdigest()
        if reconstructed_hash != approved:
            raise ValueError(
                f"Reconstructed {subject_key} canonical SHA-256 mismatch: "
                f"expected {approved}, found {reconstructed_hash}"
            )
        if len(reconstructed) != int(entry.get("source_bytes", -1)):
            raise ValueError(f"Production manifest source byte-count mismatch for {subject_key}")
        rows = _rows_from_bytes(reconstructed)
        if len(rows) != int(entry.get("source_rows", -1)):
            raise ValueError(f"Production manifest total row-count mismatch for {subject_key}")
        actual = reconstructed_hash
    years = {str(row.get("Academic Year", "")).strip() for row in rows}
    if years != {ACADEMIC_YEAR}:
        raise ValueError(f"{filename} must contain only {ACADEMIC_YEAR}; found {sorted(years)}")
    return rows, actual


def load_inputs(data_dir: Path) -> tuple[dict[str, list[dict[str, str]]], dict[str, str]]:
    rows_by_subject: dict[str, list[dict[str, str]]] = {}
    hashes: dict[str, str] = {}
    for label, (key, filename) in SUBJECTS.items():
        rows_by_subject[label], hashes[key] = load_subject(data_dir, key, filename)
    return rows_by_subject, hashes


def school_key(row: dict[str, str]) -> str:
    district = str(row.get("District ID", "")).strip()
    school = str(row.get("School ID", "")).strip()
    if not district or not school:
        raise ValueError("Missing district/school identifier")
    return f"{district}::{school}"


def classify_school_universes(rows_by_subject: dict[str, list[dict[str, str]]], raw_profiles: dict[str, set[str]] | None = None) -> dict[str, set[str]]:
    """Classify whole school sites before selecting subject outcome rows.

    Grades 3-5 or 6-8 describe observed testing profiles, not audited attendance
    boundaries. Combining subjects prevents a mixed-grade site being misclassified."""
    profiles: dict[str, set[str]] = {}
    for rows in rows_by_subject.values():
        for row in rows:
            if row.get("Student Group", "").strip() != TOTAL_POPULATION:
                continue
            grade = row.get("Grade Level", "").strip()
            if not grade or grade == ALL_GRADES:
                continue
            profiles.setdefault(school_key(row), set()).add(grade)
    if raw_profiles is not None:
        profiles = raw_profiles
    elementary = {key for key, grades in profiles.items() if grades & ELEMENTARY_GRADES and grades <= ELEMENTARY_GRADES}
    middle = {key for key, grades in profiles.items() if grades & MIDDLE_GRADES and grades <= MIDDLE_GRADES}
    return {"elementary_primary": elementary, "middle_sensitivity": middle}


def _yes(value: object) -> bool:
    return str(value or "").strip().lower() in {"yes", "true", "1"}


def is_ordinary_regular(row: dict[str, str]) -> bool:
    """Keep regular schools with no charter, special-intake or virtual flag.

    The caller separately checks school grade span and census-use eligibility.
    """
    if row.get("ODE School Type", "").strip() != "Regular":
        return False
    if _yes(row.get("Is Charter School")) or _yes(row.get("Is Special Enrollment School")):
        return False
    status = row.get("ODE Virtual Status", "").strip().lower()
    true_virtual_status = status in {"focus virtual", "full virtual"} or status.startswith("override: virtual") or status.startswith("override: official") or status.startswith("override: no physical")
    return not (_yes(row.get("Is Virtual School")) or true_virtual_status)


def exact_int(value: object, field: str) -> int:
    text = str(value or "").replace(",", "").strip()
    try:
        number = float(text)
    except ValueError as exc:
        raise ValueError(f"Missing/non-numeric exact count in {field}: {value!r}") from exc
    if not math.isfinite(number) or number < 0 or not number.is_integer():
        raise ValueError(f"Invalid exact integer count in {field}: {value!r}")
    return int(number)


def finite_float(value: object) -> float | None:
    try:
        number = float(str(value or "").replace(",", "").strip())
    except ValueError:
        return None
    return number if math.isfinite(number) else None


def validate_outcome(row: dict[str, str]) -> tuple[int, float]:
    """Require exact count identities; return (scored students, proficiency percent)."""
    levels = [exact_int(row.get(field), field) for field in LEVEL_FIELDS]
    scored = exact_int(row.get("Scored Performance Denominator"), "Scored Performance Denominator")
    proficient = exact_int(row.get("Number Proficient"), "Number Proficient")
    if scored <= 0 or sum(levels) != scored:
        raise ValueError("Level 1-4 counts do not equal Scored Performance Denominator")
    if levels[2] + levels[3] != proficient:
        raise ValueError("Level 3+4 counts do not equal Number Proficient")
    return scored, 100.0 * proficient / scored


def validate_attendance(row: dict[str, str]) -> float:
    """Reconstruct regular attendance from its own included-student denominator.

    Only the 2024-25 tested-grade rollup is accepted. The attendance population
    need not equal the scored-student population used to weight achievement."""
    if row.get("Attendance_Report_Year", "").strip() != "2024-25":
        raise ValueError("Attendance_Report_Year is not 2024-25")
    if row.get("Attendance_Group_Source", "").strip() != "tested_grade_rollup":
        raise ValueError("Attendance_Group_Source is not tested_grade_rollup")
    included = exact_int(row.get("Attendance_Students_Included"), "Attendance_Students_Included")
    regular = exact_int(row.get("Attendance_Number_Regular_Attenders"), "Attendance_Number_Regular_Attenders")
    reported = finite_float(row.get("Attendance_Percent_Regular_Attenders"))
    if included <= 0 or regular > included or reported is None:
        raise ValueError("Invalid attendance count/rate fields")
    computed = 100.0 * regular / included
    if abs(reported - computed) > 0.051:
        raise ValueError("Attendance regular-attenders identity fails rounded-rate tolerance")
    return computed


def sep_value(row: dict[str, str], sensitivity: str) -> float | None:
    """Apply a named treatment of disclosed poverty intervals.

    Midpoints/endpoints are sensitivity choices, not recovered exact observations."""
    status = row.get("Students Experiencing Poverty Value Status", "").strip()
    if status not in {"exact", "left_censored_midpoint"}:
        return None
    lower = finite_float(row.get("Students Experiencing Poverty Lower Bound"))
    upper = finite_float(row.get("Students Experiencing Poverty Upper Bound"))
    value = finite_float(row.get("Students Experiencing Poverty"))
    if lower is None or upper is None or value is None or not (0 <= lower <= upper <= 100):
        raise ValueError("Invalid SEP bounds")
    if abs(value - (lower + upper) / 2.0) > 1e-9:
        raise ValueError("SEP primary value is not the documented interval midpoint")
    if status == "exact" and abs(lower - upper) > 1e-9:
        raise ValueError("Exact SEP row has unequal endpoints")
    if sensitivity == "exact_only" and status != "exact":
        return None
    return {"midpoint": value, "lower_endpoint": lower, "upper_endpoint": upper, "exact_only": value}[sensitivity]


def authoritative_rows(rows: list[dict[str, str]], keys: set[str]) -> tuple[list[dict[str, str]], dict[str, int]]:
    """Keep one official total-population All Grades outcome per eligible school.

    The exclusion counters can overlap; do not add them as disjoint categories."""
    selected: dict[str, dict[str, str]] = {}
    candidate = 0
    for row in rows:
        if row.get("Student Group", "").strip() != TOTAL_POPULATION or row.get("Grade Level", "").strip() != ALL_GRADES:
            continue
        key = school_key(row)
        if key not in keys:
            continue
        candidate += 1
        if key in selected:
            raise ValueError(f"Duplicate authoritative Total Population All Grades row: {key}")
        selected[key] = row
    values = [selected[key] for key in sorted(selected)]
    diagnostics = {
        "candidate_all_grades": candidate,
        "ordinary_regular": sum(is_ordinary_regular(row) for row in values),
        "excluded_nonregular": sum(row.get("ODE School Type", "").strip() != "Regular" for row in values),
        "excluded_charter": sum(_yes(row.get("Is Charter School")) for row in values),
        "excluded_true_virtual": sum(
            _yes(row.get("Is Virtual School"))
            or row.get("ODE Virtual Status", "").strip().lower() in {"focus virtual", "full virtual"}
            or row.get("ODE Virtual Status", "").strip().lower().startswith(("override: virtual", "override: official", "override: no physical"))
            for row in values
        ),
        "excluded_special_enrollment": sum(_yes(row.get("Is Special Enrollment School")) for row in values),
    }
    return [row for row in values if is_ordinary_regular(row)], diagnostics


def build_points(rows: list[dict[str, str]], context: str, sep_sensitivity: str, attendance_required: bool) -> tuple[list[dict[str, float | str]], dict[str, int]]:
    points: list[dict[str, float | str]] = []
    diagnostics = {"outcome_identity_valid": 0, "outcome_identity_invalid": 0, "missing_ba": 0, "missing_context": 0, "invalid_attendance": 0}
    for row in rows:
        try:
            scored, outcome = validate_outcome(row)
        except ValueError:
            diagnostics["outcome_identity_invalid"] += 1
            continue
        diagnostics["outcome_identity_valid"] += 1
        ba = finite_float(row.get("ACS_Ed_BA_or_Higher_Rate"))
        if ba is None or not (0 <= ba <= 1):
            diagnostics["missing_ba"] += 1
            continue
        if context == "income":
            context_value = finite_float(row.get("ACS_Median_Household_Income"))
            if context_value is None or context_value <= 0:
                diagnostics["missing_context"] += 1
                continue
        else:
            context_value = sep_value(row, sep_sensitivity)
            if context_value is None:
                diagnostics["missing_context"] += 1
                continue
        attendance = None
        if attendance_required:
            try:
                attendance = validate_attendance(row)
            except ValueError:
                diagnostics["invalid_attendance"] += 1
                continue
        points.append({"key": school_key(row), "y": outcome, "w": float(scored), "context": context_value, "ba": ba, "attendance": attendance if attendance is not None else math.nan})
    return points, diagnostics


# Shared numerical routines below operate on the caller's validated school rows.
def weighted_mean(values: Sequence[float], weights: Sequence[float]) -> float:
    return sum(v * w for v, w in zip(values, weights)) / sum(weights)


def weighted_sd(values: Sequence[float], weights: Sequence[float]) -> float:
    mean = weighted_mean(values, weights)
    return math.sqrt(sum(w * (v - mean) ** 2 for v, w in zip(values, weights)) / sum(weights))


def solve(matrix: list[list[float]], vector: list[float]) -> list[float] | None:
    """Solve normal equations with partial pivoting; return None at a tiny pivot."""
    n = len(vector)
    aug = [matrix[i][:] + [vector[i]] for i in range(n)]
    for col in range(n):
        pivot = max(range(col, n), key=lambda row: abs(aug[row][col]))
        if abs(aug[pivot][col]) < 1e-12:
            return None
        aug[col], aug[pivot] = aug[pivot], aug[col]
        scale = aug[col][col]
        aug[col] = [value / scale for value in aug[col]]
        for row in range(n):
            if row == col:
                continue
            factor = aug[row][col]
            aug[row] = [a - factor * b for a, b in zip(aug[row], aug[col])]
    return [aug[i][-1] for i in range(n)]


def weighted_regression(x_rows: Sequence[Sequence[float]], y: Sequence[float], w: Sequence[float]) -> list[float] | None:
    """Minimize sum(w * prediction_error**2), including an intercept.

    Return intercept then slopes in x_rows column order; None means a singular
    fit. Each row is one school; its weight is the number of scored students.
    """
    p = len(x_rows[0]) + 1
    xtwx = [[0.0] * p for _ in range(p)]
    xtwy = [0.0] * p
    for features, target, weight in zip(x_rows, y, w):
        vector = [1.0, *features]
        for i in range(p):
            xtwy[i] += weight * vector[i] * target
            for j in range(p):
                xtwx[i][j] += weight * vector[i] * vector[j]
    return solve(xtwx, xtwy)


def r2(y: Sequence[float], predictions: Sequence[float], w: Sequence[float]) -> float | None:
    """Compare weighted squared error with this evaluation sample's weighted mean.

    Negative R2 is possible for held-out predictions; zero outcome variance has
    no defined R2. This is school-level fit, not a share of individual outcomes.
    """
    mean = weighted_mean(y, w)
    sse = sum(weight * (target - pred) ** 2 for target, pred, weight in zip(y, predictions, w))
    sst = sum(weight * (target - mean) ** 2 for target, weight in zip(y, w))
    return None if sst <= 0 else 1.0 - sse / sst


def percentile(values: Sequence[float], q: float) -> float | None:
    if not values:
        return None
    ordered = sorted(values)
    position = (len(ordered) - 1) * q
    lower = int(math.floor(position)); upper = int(math.ceil(position))
    return ordered[lower] if lower == upper else ordered[lower] + (position - lower) * (ordered[upper] - ordered[lower])


def standardize_fit(points: Sequence[dict[str, float | str]], names: Sequence[str], interaction: bool = False) -> tuple[list[list[float]], list[float], list[float], dict[str, tuple[float, float]]]:
    """Learn weighted predictor centers/scales from these fitting rows only.

    Optional interactions are pairwise products of standardized predictors."""
    weights = [float(point["w"]) for point in points]
    params: dict[str, tuple[float, float]] = {}
    columns: dict[str, list[float]] = {}
    for name in names:
        values = [float(point[name]) for point in points]
        mean, sd = weighted_mean(values, weights), weighted_sd(values, weights)
        if sd <= 0:
            raise ValueError(f"Zero variance in predictor {name}")
        params[name] = (mean, sd)
        columns[name] = [(value - mean) / sd for value in values]
    rows = [[columns[name][i] for name in names] for i in range(len(points))]
    if interaction:
        rows = [features + [features[i] * features[j] for i in range(len(features)) for j in range(i + 1, len(features))] for features in rows]
    return rows, [float(point["y"]) for point in points], weights, params


def standardize_apply(points: Sequence[dict[str, float | str]], names: Sequence[str], params: dict[str, tuple[float, float]], interaction: bool = False) -> list[list[float]]:
    """Transform held-out rows with previously fitted centers/scales; never refit."""
    rows = [[(float(point[name]) - params[name][0]) / params[name][1] for name in names] for point in points]
    if interaction:
        rows = [features + [features[i] * features[j] for i in range(len(features)) for j in range(i + 1, len(features))] for features in rows]
    return rows


def fit_model(points: Sequence[dict[str, float | str]], names: Sequence[str], interaction: bool = False) -> tuple[list[float] | None, float | None]:
    """Fit standardized X and Y for comparable betas, then score in outcome units."""
    if len(points) <= len(names) + 2:
        return None, None
    x, y, w, _ = standardize_fit(points, names, interaction)
    y_mean, y_sd = weighted_mean(y, w), weighted_sd(y, w)
    yz = [(value - y_mean) / y_sd for value in y]
    coeffs = weighted_regression(x, yz, w)
    if coeffs is None:
        return None, None
    prediction_z = [coeffs[0] + sum(coef * value for coef, value in zip(coeffs[1:], row)) for row in x]
    predictions = [y_mean + y_sd * value for value in prediction_z]
    return coeffs, r2(y, predictions, w)


def repeated_cv(points: Sequence[dict[str, float | str]], names: Sequence[str], folds: int, repeats: int, seed: int, interaction: bool = False) -> list[float]:
    """Return one pooled out-of-fold weighted R-squared per fixed-seed repeat.

    Freshly shuffle the schools with seed + repeat, then assign every folds-th
    school to the same test group. Each school is predicted once per repeat
    using only the other groups for fitting/scaling. Pool those predictions
    before computing R2. Singular fits invalidate the repeat; a negative R2 is
    a valid poor-prediction result. Schools in one district may span groups.
    """
    if len(points) < max(12, folds * 2):
        return []
    results: list[float] = []
    for repeat in range(repeats):
        indices = list(range(len(points)))
        random.Random(seed + repeat).shuffle(indices)
        predictions: dict[int, float] = {}
        for fold in range(folds):
            test_indices = indices[fold::folds]
            test_set = set(test_indices)
            train = [point for idx, point in enumerate(points) if idx not in test_set]
            test = [points[idx] for idx in test_indices]
            x_train, y_train, w_train, params = standardize_fit(train, names, interaction)
            coeffs = weighted_regression(x_train, y_train, w_train)
            if coeffs is None:
                predictions = {}; break
            x_test = standardize_apply(test, names, params, interaction)
            for idx, row in zip(test_indices, x_test):
                predictions[idx] = coeffs[0] + sum(coef * value for coef, value in zip(coeffs[1:], row))
        if len(predictions) == len(points):
            y = [float(point["y"]) for point in points]
            w = [float(point["w"]) for point in points]
            results.append(r2(y, [predictions[i] for i in range(len(points))], w))
    return [value for value in results if value is not None]


def split_coefficients(points: Sequence[dict[str, float | str]], names: Sequence[str], repeats: int, seed: int) -> list[list[float]]:
    """Refit on newly shuffled halves to describe coefficient stability.

    Each repeat starts from the full school list and reshuffles with a new seed.
    Alternating entries form two disjoint halves, each with its own fitted
    standardization. The spread is descriptive, not a confidence interval.
    """
    values: list[list[float]] = []
    for repeat in range(repeats):
        shuffled = list(points)
        random.Random(seed + 1000 + repeat).shuffle(shuffled)
        for half in (shuffled[::2], shuffled[1::2]):
            coeffs, _ = fit_model(half, names)
            if coeffs is not None:
                values.append(coeffs)
    return values


# Historical report assembly below is not called by the 2025-26 runner.
def make_result(report: str, subject: str, universe: str, context: str, sensitivity: str, points: list[dict[str, float | str]], policy: dict[str, int], diagnostics: dict[str, int], hashes: dict[str, str], folds: int, repeats: int, seed: int) -> dict[str, object]:
    attendance_required = report in {"attendance_joint", "interactions"}
    names = ["context", "ba"] + (["attendance"] if attendance_required else [])
    coeffs, in_r2 = fit_model(points, names)
    cv = repeated_cv(points, names, folds, repeats, seed)
    result: dict[str, object] = {field: "" for field in RESULT_FIELDS}
    result.update({
        "report": report, "subject": subject, "universe": universe, "context": context,
        "sep_sensitivity": sensitivity, "attendance_required": str(attendance_required).lower(),
        "n_schools": len(points), "scored_students": int(sum(float(p["w"]) for p in points)),
        **policy, **diagnostics, "model_complete": len(points),
        "beta_context": coeffs[1] if coeffs else "", "beta_ba": coeffs[2] if coeffs else "",
        "beta_attendance": coeffs[3] if coeffs and attendance_required else "", "in_sample_r2": in_r2 if in_r2 is not None else "",
        "cv_repeats": repeats, "cv_folds": folds, "cv_r2_mean": sum(cv) / len(cv) if cv else "",
        "cv_r2_p05": percentile(cv, .05) if cv else "", "cv_r2_p95": percentile(cv, .95) if cv else "",
        "source_commit": SOURCE_COMMIT, "source_sha256": json.dumps(hashes, sort_keys=True), "academic_year": ACADEMIC_YEAR,
    })
    if report == "interactions":
        _, full_r2 = fit_model(points, names, True)
        full_cv = repeated_cv(points, names, folds, repeats, seed, True)
        deltas = [full - base for full, base in zip(full_cv, cv)]
        result.update({
            "interaction_in_sample_delta_r2": full_r2 - in_r2 if full_r2 is not None and in_r2 is not None else "",
            "interaction_cv_delta_mean": sum(deltas) / len(deltas) if deltas else "",
            "interaction_cv_delta_p05": percentile(deltas, .05) if deltas else "",
            "interaction_cv_delta_p95": percentile(deltas, .95) if deltas else "",
            "interaction_cv_share_positive": sum(value > 0 for value in deltas) / len(deltas) if deltas else "",
        })
    if report == "split_stability":
        split = split_coefficients(points, names, repeats, seed)
        result.update({
            "split_beta_context_p05": percentile([v[1] for v in split], .05) if split else "",
            "split_beta_context_p95": percentile([v[1] for v in split], .95) if split else "",
            "split_beta_ba_p05": percentile([v[2] for v in split], .05) if split else "",
            "split_beta_ba_p95": percentile([v[2] for v in split], .95) if split else "",
        })
    return result


def analyze(report: str, data_dir: Path, folds: int = 5, repeats: int = 20, seed: int = 20260910) -> list[dict[str, object]]:
    rows_by_subject, hashes = load_inputs(data_dir)
    from historical_school_profiles import grade_sets
    universes = classify_school_universes(rows_by_subject, grade_sets(data_dir))
    results: list[dict[str, object]] = []
    for universe, keys in universes.items():
        for subject, rows in rows_by_subject.items():
            ordinary, policy = authoritative_rows(rows, keys)
            policy["profile_universe_count"] = len(keys)
            for context, sensitivities in (("income", ["as_reported"]), ("sep_percent", ["midpoint", "lower_endpoint", "upper_endpoint", "exact_only"])):
                for sensitivity in sensitivities:
                    points, diagnostics = build_points(ordinary, context, sensitivity, report in {"attendance_joint", "interactions"})
                    results.append(make_result(report, subject, universe, context, sensitivity, points, policy, diagnostics, hashes, folds, repeats, seed))
    return results


def _fmt(value: object) -> str:
    return "n/a" if value == "" or value is None else f"{float(value):.3f}"


def write_report(path: Path, report: str, results: list[dict[str, object]], folds: int, repeats: int, seed: int) -> None:
    title = {
        "joint": "Income, education, and school proficiency joint models",
        "split_stability": "Income/education split-sample stability sensitivity",
        "attendance_joint": "Income, education, attendance, and school proficiency joint models",
        "interactions": "Income/education/attendance interaction sensitivity",
    }[report]
    from historical_report_reading import PURPOSE, MEASURES, TERMS, CORRECTION
    stem = path.stem
    question, purpose = PURPOSE[stem]
    if report == "split_stability":
        purpose = purpose.replace("20 splits", f"{repeats} splits").replace("40 fits", f"{2 * repeats} fits")
    lines = [title, "=" * len(title), "", CORRECTION, "", question, purpose, "", "What the measures describe", MEASURES, "", "Reading the results", TERMS, "", "Status: descriptive associational analysis; no coefficient is a causal effect.", f"Production source commit: {SOURCE_COMMIT}", f"Academic year: {ACADEMIC_YEAR}", "Approved SHA-256: " + json.dumps(APPROVED_SHA256, sort_keys=True), ""]
    lines += [
        "Schools included",
        "We compare elementary schools, giving more weight to schools with more scored students. The main sample includes regular schools, excluding charter, virtual and reviewed special-enrollment schools.", "",
        "Elementary schools have only grades 3-5 in the combined ODE assessment grade records. Suppressed, unavailable and no-test grade slots count toward the grade span. Outcomes use the official All Grades row for each subject.", "",
        "Middle-school results are a separate check. High and combined-grade sites are excluded from these models because their larger attendance areas can make the school-site tract a weaker description of where pupils live.", "",
        "Ordinary excludes charter, true virtual (but not Supplemental Virtual), and separately reviewed special-enrollment schools.",
        "Outcome counts must satisfy integer L1+L2+L3+L4=scored and L3+L4=proficient. Scored students are the model weights.",
        "Units in the CSV: BA+ is a fraction; income is dollars; SEP is a percentage.", "",
        "SEP midpoint is estimated for left-censored intervals; lower endpoint, upper endpoint, and exact-only results are sensitivities.",
        "Missingness is model-specific. Attendance models require tested_grade_rollup plus exact included/regular-attender counts and the rounded rate identity.",
        f"In-sample fit is separate from {repeats} repeated {folds}-fold school-row CV runs (fixed seed {seed}).",
        "Bracketed p05-p95 values are descriptive ranges across fixed-seed repeats, not confidence intervals.",
    ]
    if report == "split_stability":
        lines.append(f"Before each of {repeats} splits, we freshly reshuffle all eligible schools and fit both halves separately, producing {2 * repeats} fits. The middle 90% of coefficients describes their spread; it is not a confidence interval.")
    if report == "interactions":
        lines.append("Interaction usefulness is judged primarily by held-out delta R-squared using identical folds for base and interaction models.")
    lines += ["", "Results"]
    for row in results:
        lines.append(
            f"- {row['universe']} | {row['subject']} | {row['context']} ({row['sep_sensitivity']}): "
            f"n={row['n_schools']}, scored={row['scored_students']}, beta_context={_fmt(row['beta_context'])}, "
            f"beta_BA={_fmt(row['beta_ba'])}, beta_attendance={_fmt(row['beta_attendance'])}, "
            f"in_sample_R2={_fmt(row['in_sample_r2'])}, CV_R2_mean={_fmt(row['cv_r2_mean'])} "
            f"(repeat p05-p95 {_fmt(row['cv_r2_p05'])} to {_fmt(row['cv_r2_p95'])})"
            + (f", interaction_CV_delta_mean={_fmt(row['interaction_cv_delta_mean'])} (repeat p05-p95 {_fmt(row['interaction_cv_delta_p05'])} to {_fmt(row['interaction_cv_delta_p95'])})" if report == "interactions" else "")
            + (f", split beta context repeat p05-p95 {_fmt(row['split_beta_context_p05'])} to {_fmt(row['split_beta_context_p95'])}, split beta BA repeat p05-p95 {_fmt(row['split_beta_ba_p05'])} to {_fmt(row['split_beta_ba_p95'])}" if report == "split_stability" else "")
        )
        lines.append(
            f"  coverage: cross-subject profile={row['profile_universe_count']}, subject All Grades={row['candidate_all_grades']}, ordinary={row['ordinary_regular']}, "
            f"outcome-identity-valid={row['outcome_identity_valid']}, model-complete={row['model_complete']}; "
            f"missing BA={row['missing_ba']}, missing context={row['missing_context']}, invalid/missing attendance={row['invalid_attendance']}"
        )
    lines += ["", "Machine-readable companion: " + path.with_name(path.stem.replace("_report", "_results") + ".csv").name, ""]
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(lines), encoding="utf-8")


def write_csv(path: Path, results: list[dict[str, object]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=RESULT_FIELDS, lineterminator="\n")
        writer.writeheader(); writer.writerows(results)


def run_report_cli(report: str, default_output: Path, default_data_dir: Path) -> None:
    """Parse shared entry-point options, fit models, and write text/CSV companions."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-dir", type=Path, default=default_data_dir)
    parser.add_argument("--output", type=Path, default=default_output)
    parser.add_argument("--csv-output", type=Path)
    parser.add_argument("--folds", type=int, default=5)
    parser.add_argument("--repeats", type=int, default=20)
    parser.add_argument("--seed", type=int, default=20260910)
    args = parser.parse_args()
    if args.folds < 2 or args.repeats < 1:
        parser.error("--folds must be >=2 and --repeats >=1")
    csv_output = args.csv_output or args.output.with_name(args.output.stem.replace("_report", "_results") + ".csv")
    results = analyze(report, args.data_dir.resolve(), args.folds, args.repeats, args.seed)
    write_report(args.output.resolve(), report, results, args.folds, args.repeats, args.seed)
    write_csv(csv_output.resolve(), results)
    print(f"Wrote {args.output.resolve()}")
    print(f"Wrote {csv_output.resolve()}")
