"""Small, standard-library weighted statistics shared by analysis reports.

This is an importable helper, not a command-line report generator: it reads no
files and writes no outputs. Predictors for weighted_regression are columns,
not rows; its result is [intercept, slope_1, ...]. Callers must supply aligned,
finite observations and appropriate positive weights, and handle None results.
For ODE achievement analyses, callers use scored-student counts as weights.

The helpers implement descriptive moments, Pearson/partial correlations, and
weighted least squares. They do not calculate standard errors or causal effects.
Read weighted_regression and partial_corr for the main calculation paths."""
import math


def parse_float(value):
    if value is None:
        return None
    try:
        return float(str(value).replace(",", ""))
    except ValueError:
        return None


def weighted_mean(values, weights):
    total_w = sum(weights)
    if total_w <= 0:
        return None
    return sum(v * w for v, w in zip(values, weights)) / total_w


def weighted_median(values, weights):
    """Return the first observed value reaching half the positive weight.

    This is a cumulative-weight quantile, not interpolation between two values."""
    if not values or not weights:
        return None
    pairs = [(v, w) for v, w in zip(values, weights) if v is not None and w is not None and w > 0]
    if not pairs:
        return None
    pairs.sort(key=lambda x: x[0])
    total_w = sum(w for _, w in pairs)
    if total_w <= 0:
        return None
    midpoint = total_w / 2
    running = 0
    for value, weight in pairs:
        running += weight
        if running >= midpoint:
            return value
    return pairs[-1][0]


def weighted_var(values, weights, mean=None):
    """Return population-style weighted variance (divide by sum of weights).

    This is a descriptive spread measure, not an unbiased sample-variance estimator."""
    total_w = sum(weights)
    if total_w <= 0:
        return None
    if mean is None:
        mean = weighted_mean(values, weights)
    return sum(w * (v - mean) ** 2 for v, w in zip(values, weights)) / total_w


def weighted_corr(x, y, w):
    if not x or not y or not w:
        return None
    mean_x = weighted_mean(x, w)
    mean_y = weighted_mean(y, w)
    if mean_x is None or mean_y is None:
        return None
    total_w = sum(w)
    if total_w <= 0:
        return None
    cov = sum(wi * (xi - mean_x) * (yi - mean_y) for xi, yi, wi in zip(x, y, w)) / total_w
    var_x = weighted_var(x, w, mean_x)
    var_y = weighted_var(y, w, mean_y)
    if var_x is None or var_y is None or var_x <= 0 or var_y <= 0:
        return None
    return cov / math.sqrt(var_x * var_y)


def standardized(values, weights):
    mean = weighted_mean(values, weights)
    var = weighted_var(values, weights, mean)
    if mean is None or var is None or var <= 0:
        return None, None, None
    std = math.sqrt(var)
    return [(v - mean) / std for v in values], mean, std


def weighted_r2(y, yhat, w):
    """Return 1 - weighted residual sum of squares / weighted total variation.

    Negative values are possible for predictions worse than the weighted mean."""
    mean_y = weighted_mean(y, w)
    if mean_y is None:
        return None
    sse = sum(wi * (yi - yhi) ** 2 for yi, yhi, wi in zip(y, yhat, w))
    sst = sum(wi * (yi - mean_y) ** 2 for yi, wi in zip(y, w))
    if sst <= 0:
        return None
    return 1 - sse / sst


def solve_linear_system(matrix, vector):
    """Solve a square system by Gauss-Jordan elimination with partial pivoting.

    Return None when a pivot is below 1e-12; do not invent a singular-system fit."""
    n = len(matrix)
    augmented = [row[:] + [vector[i]] for i, row in enumerate(matrix)]

    for i in range(n):
        max_row = max(range(i, n), key=lambda r: abs(augmented[r][i]))
        if abs(augmented[max_row][i]) < 1e-12:
            return None
        augmented[i], augmented[max_row] = augmented[max_row], augmented[i]

        pivot = augmented[i][i]
        for j in range(i, n + 1):
            augmented[i][j] /= pivot

        for r in range(n):
            if r == i:
                continue
            factor = augmented[r][i]
            if factor == 0:
                continue
            for c in range(i, n + 1):
                augmented[r][c] -= factor * augmented[i][c]

    return [augmented[i][n] for i in range(n)]


def weighted_regression(x_cols, y, w):
    """Fit an intercept plus predictor columns by weighted least squares.

    Accumulate X'WX and X'Wy, then solve the normal equations. The caller handles
    missing data and checks the returned coefficients before using them."""
    if not y:
        return None
    p = len(x_cols)
    total_w = sum(w)
    if total_w <= 0:
        return None

    # Build normal equations for intercept + predictors.
    size = p + 1
    xtwx = [[0.0 for _ in range(size)] for _ in range(size)]
    xtwy = [0.0 for _ in range(size)]

    for idx, yi in enumerate(y):
        wi = w[idx]
        if not math.isfinite(wi):
            continue
        x_vals = [1.0] + [x[idx] for x in x_cols]
        for i in range(size):
            xtwy[i] += wi * x_vals[i] * yi
            for j in range(size):
                xtwx[i][j] += wi * x_vals[i] * x_vals[j]

    return solve_linear_system(xtwx, xtwy)


def predict_from_coeffs(x_cols, coeffs):
    predictions = []
    for idx in range(len(x_cols[0])):
        value = coeffs[0]
        for i, col in enumerate(x_cols):
            value += coeffs[i + 1] * col[idx]
        predictions.append(value)
    return predictions


def model_r2(x_cols, y, w):
    coeffs = weighted_regression(x_cols, y, w)
    if coeffs is None:
        return None
    yhat = predict_from_coeffs(x_cols, coeffs)
    return weighted_r2(y, yhat, w)


def partial_corr(target, focal, controls, weights):
    """Correlate the two weighted residuals after fitting the same controls.

    Residualize both target and focal variable, not just the outcome. With no
    controls this reduces to their weighted Pearson correlation."""
    if not controls:
        return weighted_corr(target, focal, weights)
    coef_target = weighted_regression(controls, target, weights)
    coef_focal = weighted_regression(controls, focal, weights)
    if coef_target is None or coef_focal is None:
        return None
    target_hat = predict_from_coeffs(controls, coef_target)
    focal_hat = predict_from_coeffs(controls, coef_focal)
    target_res = [y - yh for y, yh in zip(target, target_hat)]
    focal_res = [x - xh for x, xh in zip(focal, focal_hat)]
    return weighted_corr(target_res, focal_res, weights)
