#!/usr/bin/env python3
"""Deterministic reference engine for the 18 MSC validation dossiers. MIT; Python 3.11+."""

from __future__ import annotations

import argparse
import csv
import hashlib
import math
from statistics import NormalDist
from pathlib import Path


ENGINE_VERSION = "msc-repro-v2"
DEFAULT_DATA = Path(__file__).resolve().parents[1] / "datasets" / "msc-validation-inputs-v1.csv"
FIELDS = (
    "bundle_version", "page_id", "dataset_id", "record_id", "entity_id", "time_index",
    "arm_or_group", "variable", "value_number", "value_text", "value_type", "unit", "role",
    "data_status", "license",
)
REQUIRED = {
    "MSC-P-003": ("estimate_pp", "standard_error_pp", "z_critical"),
    "MSC-P-005": ("loading_1", "loading_2", "loading_3", "loading_4"),
    "MSC-P-006": ("construct_defined", "content_review_complete", "cognitive_pretest_complete", "independent_confirmation_declared", "reliability_model_declared", "invariance_scope_declared"),
    "MSC-P-008": ("trust_satisfaction_correlation", "separation_threshold", "sample_size"),
    "MSC-P-010": ("local_decision_value_eur", "experiment_cost_eur", "operational_risk_eur", "anticipated_gain_pp", "minimum_useful_gain_pp", "action_reversible", "assignment_feasible", "value_horizon_days", "valuation_scenario_prespecified", "risk_probability_model_declared"),
    "MSC-P-012": ("baseline_rate", "target_rate", "alpha_two_sided", "power", "attrition_rate", "design_effect"),
    "MSC-P-014": ("treated_geo_post_outcome", "counterfactual_post_outcome", "standard_error", "z_critical"),
    "MSC-P-015": ("treated_pre", "treated_post", "control_pre", "control_post", "standard_error", "z_critical"),
    "MSC-P-017": ("assigned_treatment", "assigned_control", "observed_treatment", "observed_control", "exposed_treatment", "exposed_control"),
    "MSC-P-019": ("residual_mean", "residual_sd", "maximum_absolute_standardized_residual", "maximum_leverage", "maximum_cooks_distance", "sample_size", "parameter_count", "cluster_count", "holdout_rmse"),
    "MSC-P-023": ("baseline_price_eur", "baseline_volume", "variable_cost_eur", "fixed_cost_change_eur", "elasticity", "price_ratio"),
    "MSC-P-028": ("predicted_transactions_period_1", "predicted_transactions_period_2", "predicted_transactions_period_3", "mean_transaction_value_eur", "contribution_margin_rate", "discount_rate_per_period", "frequency_value_correlation", "independence_diagnostic_completed", "monetary_model_calibrated"),
    "MSC-P-029": tuple([f"predicted_risk_{index}" for index in range(1, 9)] + [f"outcome_{index}" for index in range(1, 9)] + ["temporal_holdout_declared"]),
    "MSC-P-031": ("within_distance_1", "nearest_distance_1", "within_distance_2", "nearest_distance_2", "within_distance_3", "nearest_distance_3", "cluster_count", "initialization_seed"),
    "MSC-P-032": ("jaccard_1", "jaccard_2", "jaccard_3", "jaccard_4", "jaccard_5", "dissolution_threshold", "resample_count"),
    "MSC-P-033": ("train_y_1", "train_y_2", "train_y_3", "train_y_4", "train_y_5", "forecast_abs_error_1", "forecast_abs_error_2", "forecast_abs_error_3", "forecast_abs_error_4", "seasonal_period", "covered_observations", "total_observations", "nominal_coverage"),
    "MSC-P-035": ("current_spend", "previous_adstock", "adstock_decay", "saturation_alpha", "saturation_beta", "saturation_gamma"),
    "MSC-P-039": ("mean_a", "mean_b", "sd_a", "sd_b", "n_a", "n_b", "confidence_level"),
}
INTEGER_KEYS = {
    "sample_size", "construct_defined", "content_review_complete", "cognitive_pretest_complete",
    "independent_confirmation_declared", "reliability_model_declared", "invariance_scope_declared",
    "action_reversible", "assignment_feasible", "value_horizon_days", "valuation_scenario_prespecified", "risk_probability_model_declared", "independence_diagnostic_completed", "monetary_model_calibrated", "assigned_treatment", "assigned_control",
    "observed_treatment", "observed_control", "exposed_treatment", "exposed_control", "cluster_count",
    "initialization_seed", "jaccard_intersection", "jaccard_union", "resample_count",
    "covered_observations", "total_observations", "n_a", "n_b", "parameter_count",
    "temporal_holdout_declared", "seasonal_period",
    "outcome_1", "outcome_2", "outcome_3", "outcome_4",
    "outcome_5", "outcome_6", "outcome_7", "outcome_8",
}

EXPECTED_UNITS = {
    "MSC-P-003": ("percentage_point", "percentage_point", "dimensionless"),
    "MSC-P-005": ("dimensionless",) * 4,
    "MSC-P-006": ("binary",) * 6,
    "MSC-P-008": ("dimensionless", "dimensionless", "respondent"),
    "MSC-P-010": ("EUR", "EUR", "EUR", "percentage_point", "percentage_point", "binary", "binary", "day", "binary", "binary"),
    "MSC-P-012": ("probability", "probability", "probability", "probability", "probability", "dimensionless"),
    "MSC-P-014": ("index", "index", "index", "dimensionless"),
    "MSC-P-015": ("index", "index", "index", "index", "index", "dimensionless"),
    "MSC-P-017": ("unit",) * 6,
    "MSC-P-019": ("outcome", "outcome", "dimensionless", "dimensionless", "dimensionless", "observation", "parameter", "cluster", "outcome"),
    "MSC-P-023": ("EUR_per_unit", "unit", "EUR_per_unit", "EUR", "dimensionless", "ratio"),
    "MSC-P-028": ("transaction", "transaction", "transaction", "EUR_per_transaction", "proportion", "rate per period", "dimensionless", "binary", "binary"),
    "MSC-P-029": ("probability",) * 8 + ("binary",) * 9,
    "MSC-P-031": ("distance",) * 6 + ("cluster", "seed"),
    "MSC-P-032": ("dimensionless",) * 6 + ("resample",),
    "MSC-P-033": ("outcome",) * 9 + ("period", "observation", "observation", "probability"),
    "MSC-P-035": ("spend", "spend", "dimensionless", "response", "dimensionless", "spend"),
    "MSC-P-039": ("outcome", "outcome", "outcome", "outcome", "unit", "unit", "probability"),
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("page_id", choices=tuple(REQUIRED))
    parser.add_argument("dataset", nargs="?", type=Path, default=DEFAULT_DATA)
    return parser.parse_args()


def canonical_slice(rows: list[dict[str, str]]) -> str:
    ordered = sorted(rows, key=lambda row: (row["dataset_id"], row["record_id"], row["variable"]))
    return "\n".join("|".join(f"{field}={row[field].strip()}" for field in FIELDS) for row in ordered)


def load(page_id: str, path: Path) -> tuple[dict[str, float], str, str]:
    with path.open(encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        if tuple(reader.fieldnames or ()) != FIELDS:
            raise ValueError("dataset header must exactly match the bundle contract")
        all_rows = list(reader)
    seen: set[tuple[str, str, str, str]] = set()
    for row in all_rows:
        key = (row["page_id"], row["dataset_id"], row["record_id"], row["variable"])
        if key in seen:
            raise ValueError(f"duplicate bundle key: {key}")
        seen.add(key)
        if row["bundle_version"] != "msc-inputs-v1" or row["license"] != "CC0-1.0":
            raise ValueError("bundle version and CC0 license are mandatory")
        if (bool(row["value_number"].strip()) + bool(row["value_text"].strip())) != 1:
            raise ValueError("exactly one value column must be populated")
    rows = [row for row in all_rows if row["page_id"] == page_id]
    if not rows:
        raise ValueError(f"no atomic slice for {page_id}")
    if any(row["record_id"] != "protocol" or row["role"] != "input" for row in rows):
        raise ValueError("unexpected record or role in atomic slice")
    if any(row["data_status"] not in {"synthetic", "parameter"} for row in rows):
        raise ValueError("data_status must be synthetic or parameter")
    variables = {row["variable"] for row in rows}
    if variables != set(REQUIRED[page_id]):
        raise ValueError(f"slice variables must exactly match {REQUIRED[page_id]}")
    expected_units = dict(zip(REQUIRED[page_id], EXPECTED_UNITS[page_id], strict=True))
    if any(row["unit"] != expected_units[row["variable"]] for row in rows):
        raise ValueError("input unit does not match the branch contract")
    values: dict[str, float] = {}
    for row in rows:
        expected_type = "integer" if row["variable"] in INTEGER_KEYS else "number"
        if row["value_type"] != expected_type:
            raise ValueError("input value_type does not match the branch contract")
        if not row["value_number"].strip():
            raise ValueError("v1 reference branches require numeric inputs")
        value = float(row["value_number"])
        if not math.isfinite(value):
            raise ValueError("numeric inputs must be finite")
        if expected_type == "integer" and value != math.floor(value):
            raise ValueError(f"{row['variable']} must be an integer")
        values[row["variable"]] = value
    digest = hashlib.sha256(canonical_slice(rows).encode("utf-8")).hexdigest()
    status = "+".join(sorted({row["data_status"] for row in rows}))
    return values, digest, status


def regularized_beta(x: float, a: float, b: float) -> float:
    """Regularized incomplete beta using the Lentz continued fraction."""
    if not 0 <= x <= 1 or min(a, b) <= 0:
        raise ValueError("invalid beta arguments")

    def fraction(aa: float, bb: float, xx: float) -> float:
        qab, qap, qam = aa + bb, aa + 1, aa - 1
        c = 1.0
        d = 1.0 - qab * xx / qap
        d = 1.0 / max(abs(d), 1e-300) * (1 if d >= 0 else -1)
        h = d
        for m in range(1, 201):
            m2 = 2 * m
            term = m * (bb - m) * xx / ((qam + m2) * (aa + m2))
            d = 1.0 + term * d; d = 1.0 / (d if abs(d) > 1e-300 else 1e-300)
            c = 1.0 + term / c; c = c if abs(c) > 1e-300 else 1e-300
            h *= d * c
            term = -(aa + m) * (qab + m) * xx / ((aa + m2) * (qap + m2))
            d = 1.0 + term * d; d = 1.0 / (d if abs(d) > 1e-300 else 1e-300)
            c = 1.0 + term / c; c = c if abs(c) > 1e-300 else 1e-300
            delta = d * c; h *= delta
            if abs(delta - 1.0) < 3e-14:
                return h
        raise ValueError("beta continued fraction did not converge")

    if x in {0.0, 1.0}:
        return x
    front = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x))
    if x < (a + 1) / (a + b + 2):
        return front * fraction(a, b, x) / a
    return 1 - front * fraction(b, a, 1 - x) / b


def student_t_cdf(value: float, df: float) -> float:
    beta = regularized_beta(df / (df + value * value), df / 2, 0.5)
    return 1 - beta / 2 if value >= 0 else beta / 2


def student_t_quantile(probability: float, df: float) -> float:
    if not 0.5 < probability < 1 or df <= 0:
        raise ValueError("invalid Student quantile inputs")
    low, high = 0.0, 1.0
    while student_t_cdf(high, df) < probability:
        high *= 2
    for _ in range(100):
        middle = (low + high) / 2
        if student_t_cdf(middle, df) < probability:
            low = middle
        else:
            high = middle
    return (low + high) / 2


def compute(page_id: str, x: dict[str, float]) -> tuple[dict[str, float], str]:
    if page_id == "MSC-P-003":
        if x["standard_error_pp"] <= 0 or x["z_critical"] <= 0:
            raise ValueError("confidence interval requires positive SE and critical value")
        margin = x["z_critical"] * x["standard_error_pp"]
        return {"estimate_pp": x["estimate_pp"], "ci_lower_pp": x["estimate_pp"] - margin, "ci_upper_pp": x["estimate_pp"] + margin}, "parameter_confidence_interval_not_prediction_or_posterior"
    if page_id == "MSC-P-005":
        loadings = [x[f"loading_{index}"] for index in range(1, 5)]
        if any(abs(value) > 1 for value in loadings):
            raise ValueError("standardized loadings must be within [-1, 1]")
        ave = sum(value * value for value in loadings) / len(loadings)
        return {"minimum_loading": min(loadings), "maximum_loading": max(loadings), "ave": ave}, "convergent_evidence_does_not_establish_global_validity"
    if page_id == "MSC-P-006":
        completed = sum(x[key] for key in REQUIRED[page_id])
        if any(x[key] not in {0.0, 1.0} for key in REQUIRED[page_id]):
            raise ValueError("scale-development gates must be binary")
        return {"completed_gates": completed, "required_gates": float(len(REQUIRED[page_id]))}, "all_prespecified_development_gates_required"
    if page_id == "MSC-P-008":
        if not (-1 < x["trust_satisfaction_correlation"] < 1 and 0 < x["separation_threshold"] < 1 and x["sample_size"] > 3):
            raise ValueError("invalid correlation screening inputs")
        gap = x["trust_satisfaction_correlation"] - x["separation_threshold"]
        fisher_se = 1 / math.sqrt(x["sample_size"] - 3)
        lower = math.tanh(math.atanh(x["trust_satisfaction_correlation"]) - 1.95996398454 * fisher_se)
        upper = math.tanh(math.atanh(x["trust_satisfaction_correlation"]) + 1.95996398454 * fisher_se)
        return {"correlation": x["trust_satisfaction_correlation"], "correlation_ci_lower": lower, "correlation_ci_upper": upper, "threshold_excess": gap, "screening_signal": float(gap > 0)}, "correlation_screen_only_not_htmt_or_cfa_discriminant_validity"
    if page_id == "MSC-P-010":
        if min(x["local_decision_value_eur"], x["experiment_cost_eur"], x["operational_risk_eur"], x["anticipated_gain_pp"], x["minimum_useful_gain_pp"]) < 0 or x["value_horizon_days"] <= 0:
            raise ValueError("decision values, risks, costs and gains must be nonnegative")
        if any(x[key] not in {0.0, 1.0} for key in ("action_reversible", "assignment_feasible", "valuation_scenario_prespecified", "risk_probability_model_declared")):
            raise ValueError("decision screen flags must be binary")
        net = x["local_decision_value_eur"] - x["experiment_cost_eur"] - x["operational_risk_eur"]
        feasible = float(net > 0 and x["anticipated_gain_pp"] >= x["minimum_useful_gain_pp"] and x["action_reversible"] == 1 and x["assignment_feasible"] == 1 and x["valuation_scenario_prespecified"] == 1 and x["risk_probability_model_declared"] == 1)
        return {"local_net_screen_eur": net, "anticipated_gain_pp": x["anticipated_gain_pp"], "minimum_useful_gain_pp": x["minimum_useful_gain_pp"], "passes_local_screen": feasible, "value_horizon_days": x["value_horizon_days"]}, "local_nonuniversal_governance_screen_not_voi_or_effect_estimate"
    if page_id == "MSC-P-012":
        p0, p1 = x["baseline_rate"], x["target_rate"]
        if not (0 < p0 < 1 and 0 < p1 < 1 and p0 != p1 and 0 < x["alpha_two_sided"] < 1 and 0.5 < x["power"] < 1 and 0 <= x["attrition_rate"] < 1 and x["design_effect"] >= 1):
            raise ValueError("invalid sample-size inputs")
        z_alpha = NormalDist().inv_cdf(1 - x["alpha_two_sided"] / 2)
        z_power = NormalDist().inv_cdf(x["power"])
        pbar = (p0 + p1) / 2
        numerator = z_alpha * math.sqrt(2 * pbar * (1 - pbar)) + z_power * math.sqrt(p0 * (1 - p0) + p1 * (1 - p1))
        raw = numerator * numerator / ((p1 - p0) ** 2)
        adjusted = math.ceil(raw * x["design_effect"] / (1 - x["attrition_rate"]))
        return {"raw_n_per_arm": raw, "planned_n_per_arm": float(adjusted), "z_alpha_two_sided": z_alpha, "z_power": z_power}, "normal_approximation_equal_allocation_quantiles_computed_from_alpha_and_power_round_up"
    if page_id == "MSC-P-014":
        if x["standard_error"] <= 0 or x["z_critical"] <= 0:
            raise ValueError("geo illustration requires positive supplied SE and critical value")
        effect = x["treated_geo_post_outcome"] - x["counterfactual_post_outcome"]
        margin = x["z_critical"] * x["standard_error"]
        return {"conditional_incremental_outcome": effect, "ci_lower": effect - margin, "ci_upper": effect + margin}, "illustration_with_supplied_counterfactual_and_se_not_geo_experiment_fit"
    if page_id == "MSC-P-015":
        if x["standard_error"] <= 0 or x["z_critical"] <= 0:
            raise ValueError("DiD illustration requires positive supplied SE and critical value")
        effect = (x["treated_post"] - x["treated_pre"]) - (x["control_post"] - x["control_pre"])
        margin = x["z_critical"] * x["standard_error"]
        return {"att_did": effect, "ci_lower": effect - margin, "ci_upper": effect + margin}, "supplied_cluster_robust_se_parallel_trends_and_no_anticipation_required"
    if page_id == "MSC-P-017":
        if min(x["assigned_treatment"], x["assigned_control"]) <= 0:
            raise ValueError("assigned counts must be positive")
        if not (0 <= x["observed_treatment"] <= x["assigned_treatment"] and 0 <= x["observed_control"] <= x["assigned_control"] and 0 <= x["exposed_treatment"] <= x["assigned_treatment"] and 0 <= x["exposed_control"] <= x["assigned_control"]):
            raise ValueError("observed and exposed counts must lie within assigned counts")
        attr_t = 1 - x["observed_treatment"] / x["assigned_treatment"]
        attr_c = 1 - x["observed_control"] / x["assigned_control"]
        exposure_t = x["exposed_treatment"] / x["assigned_treatment"]
        contamination_c = x["exposed_control"] / x["assigned_control"]
        return {"attrition_treatment": attr_t, "attrition_control": attr_c, "differential_attrition": attr_t - attr_c, "treatment_exposure": exposure_t, "control_contamination": contamination_c}, "diagnostics_do_not_repair_bias"
    if page_id == "MSC-P-019":
        if x["residual_sd"] <= 0 or x["sample_size"] <= x["parameter_count"] + 1 or x["parameter_count"] < 1 or x["cluster_count"] < 2 or min(x["maximum_absolute_standardized_residual"], x["maximum_leverage"], x["maximum_cooks_distance"], x["holdout_rmse"]) < 0 or x["maximum_leverage"] > 1:
            raise ValueError("invalid regression diagnostic inputs")
        return {"residual_mean": x["residual_mean"], "residual_sd": x["residual_sd"], "maximum_absolute_standardized_residual": x["maximum_absolute_standardized_residual"], "maximum_leverage": x["maximum_leverage"], "maximum_cooks_distance": x["maximum_cooks_distance"], "cluster_count": x["cluster_count"], "holdout_rmse": x["holdout_rmse"]}, "descriptive_inspection_only_no_universal_cutoff_influence_conclusion_requires_case_deletion_refit_sensitivity"
    if page_id == "MSC-P-023":
        if x["price_ratio"] <= 0 or x["baseline_price_eur"] <= 0 or x["baseline_volume"] <= 0 or x["variable_cost_eur"] < 0 or x["variable_cost_eur"] >= x["baseline_price_eur"]:
            raise ValueError("invalid price scenario inputs")
        new_price = x["baseline_price_eur"] * x["price_ratio"]
        new_volume = x["baseline_volume"] * x["price_ratio"] ** x["elasticity"]
        baseline_contribution = (x["baseline_price_eur"] - x["variable_cost_eur"]) * x["baseline_volume"]
        scenario_contribution = (new_price - x["variable_cost_eur"]) * new_volume - x["fixed_cost_change_eur"]
        return {"new_price_eur": new_price, "conditional_volume": new_volume, "conditional_volume_change": new_volume / x["baseline_volume"] - 1, "baseline_contribution_eur": baseline_contribution, "scenario_contribution_eur": scenario_contribution, "incremental_contribution_eur": scenario_contribution - baseline_contribution}, "conditional_scenario_using_supplied_elasticity_not_demand_estimation_or_causal_effect"
    if page_id == "MSC-P-028":
        if min(x["predicted_transactions_period_1"], x["predicted_transactions_period_2"], x["predicted_transactions_period_3"], x["mean_transaction_value_eur"]) < 0 or not (0 <= x["contribution_margin_rate"] <= 1 and 0 <= x["discount_rate_per_period"] < 1 and -1 <= x["frequency_value_correlation"] <= 1) or x["independence_diagnostic_completed"] != 1 or x["monetary_model_calibrated"] != 1:
            raise ValueError("invalid CLV aggregation inputs")
        contribution = x["mean_transaction_value_eur"] * x["contribution_margin_rate"]
        flows = [x[f"predicted_transactions_period_{index}"] * contribution / ((1 + x["discount_rate_per_period"]) ** index) for index in range(1, 4)]
        return {"mean_contribution_eur": contribution, "discounted_period_1_eur": flows[0], "discounted_period_2_eur": flows[1], "discounted_period_3_eur": flows[2], "expected_discounted_clv_eur": sum(flows), "frequency_value_correlation": x["frequency_value_correlation"]}, "aggregation_only_after_declared_independence_diagnostic_and_monetary_calibration_low_correlation_is_not_proof"
    if page_id == "MSC-P-029":
        risks = [x[f"predicted_risk_{index}"] for index in range(1, 9)]
        outcomes = [x[f"outcome_{index}"] for index in range(1, 9)]
        if any(not 0 < risk < 1 for risk in risks) or any(value not in {0, 1} for value in outcomes) or x["temporal_holdout_declared"] != 1:
            raise ValueError("holdout risks must be open probabilities with binary outcomes")
        brier = sum((risk - outcome) ** 2 for risk, outcome in zip(risks, outcomes)) / len(risks)
        log_loss = -sum(outcome * math.log(risk) + (1 - outcome) * math.log1p(-risk) for risk, outcome in zip(risks, outcomes)) / len(risks)
        positives = sum(outcomes)
        if positives == 0 or positives == len(outcomes):
            raise ValueError("average precision requires both outcome classes")
        true_positives = 0.0
        predicted_positives = 0
        average_precision = 0.0
        for threshold in sorted(set(risks), reverse=True):
            group = [outcome for risk, outcome in zip(risks, outcomes) if risk == threshold]
            group_positives = sum(group)
            true_positives += group_positives
            predicted_positives += len(group)
            average_precision += (group_positives / positives) * (true_positives / predicted_positives)
        gap = sum(risks) / len(risks) - sum(outcomes) / len(outcomes)
        return {"sample_size": float(len(risks)), "mean_predicted_risk": sum(risks) / len(risks), "observed_event_rate": sum(outcomes) / len(outcomes), "mean_predicted_minus_observed_gap": gap, "brier_score": brier, "log_loss": log_loss, "threshold_grouped_average_precision": average_precision}, "average_precision_is_threshold_grouped_not_generic_pr_auc_tiny_synthetic_holdout_not_deployment_validation_or_causal_effect"
    if page_id == "MSC-P-031":
        silhouettes = []
        for index in range(1, 4):
            a, b = x[f"within_distance_{index}"], x[f"nearest_distance_{index}"]
            if a < 0 or b < 0 or max(a, b) == 0:
                raise ValueError("per-observation silhouette distances must be nonnegative and nondegenerate")
            silhouettes.append((b - a) / max(a, b))
        if x["cluster_count"] < 2:
            raise ValueError("at least two clusters are required")
        return {"cluster_count_in_parent_partition": x["cluster_count"], "sampled_observation_count": float(len(silhouettes)), "sample_mean_silhouette": sum(silhouettes) / len(silhouettes), "sample_minimum_silhouette": min(silhouettes), "sample_maximum_silhouette": max(silhouettes), "initialization_seed": x["initialization_seed"]}, "three_sampled_points_from_larger_partition_not_full_partition_mean_stability_and_actionability_still_required"
    if page_id == "MSC-P-032":
        values = [x[f"jaccard_{index}"] for index in range(1, 6)]
        if any(not 0 <= value <= 1 for value in values) or not 0 <= x["dissolution_threshold"] <= 1 or x["resample_count"] != len(values):
            raise ValueError("Jaccard series must match declared resample count and [0,1] domain")
        dissolved = sum(value < x["dissolution_threshold"] for value in values) / len(values)
        return {"mean_jaccard": sum(values) / len(values), "minimum_jaccard": min(values), "maximum_jaccard": max(values), "dissolved_resample_share": dissolved, "resample_count": x["resample_count"]}, "labels_aligned_before_clusterwise_resample_distribution_summary"
    if page_id == "MSC-P-033":
        train = [x[f"train_y_{index}"] for index in range(1, 6)]
        errors = [x[f"forecast_abs_error_{index}"] for index in range(1, 5)]
        period = int(x["seasonal_period"])
        if not 1 <= period < len(train) or any(value < 0 for value in errors) or x["total_observations"] != len(errors) or not 0 <= x["covered_observations"] <= x["total_observations"] or not 0 < x["nominal_coverage"] < 1:
            raise ValueError("invalid MASE or coverage inputs")
        naive_mae = sum(abs(train[index] - train[index - period]) for index in range(period, len(train))) / (len(train) - period)
        if naive_mae <= 0:
            raise ValueError("in-sample seasonal naive MAE must be positive")
        forecast_mae = sum(errors) / len(errors)
        mase = forecast_mae / naive_mae
        coverage = x["covered_observations"] / x["total_observations"]
        return {"forecast_mae": forecast_mae, "in_sample_seasonal_naive_mae": naive_mae, "mase": mase, "empirical_coverage": coverage, "coverage_gap": coverage - x["nominal_coverage"]}, "mase_scaled_by_declared_in_sample_seasonal_naive_error_rolling_origin_still_required"
    if page_id == "MSC-P-035":
        decay = x["adstock_decay"]
        if not 0 <= decay < 1 or min(x["current_spend"], x["previous_adstock"]) < 0 or min(x["saturation_alpha"], x["saturation_beta"], x["saturation_gamma"]) <= 0:
            raise ValueError("invalid adstock or saturation parameters")
        adstock_level = x["current_spend"] + decay * x["previous_adstock"]
        half_life = 0.0 if decay == 0 else math.log(0.5) / math.log(decay)
        level_beta = adstock_level ** x["saturation_beta"]
        response = x["saturation_alpha"] * level_beta / (x["saturation_gamma"] ** x["saturation_beta"] + level_beta)
        return {"adstock_level": adstock_level, "geometric_half_life_periods": half_life, "saturated_response": response}, "single_recurrence_and_shape_illustration_transform_order_initialization_and_identification_required"
    if page_id == "MSC-P-039":
        if min(x["sd_a"], x["sd_b"], x["n_a"], x["n_b"]) <= 0 or min(x["n_a"], x["n_b"]) <= 1:
            raise ValueError("invalid Welch inputs")
        va, vb = x["sd_a"] ** 2 / x["n_a"], x["sd_b"] ** 2 / x["n_b"]
        se = math.sqrt(va + vb)
        df = (va + vb) ** 2 / (va * va / (x["n_a"] - 1) + vb * vb / (x["n_b"] - 1))
        if not 0 < x["confidence_level"] < 1:
            raise ValueError("confidence level must be in (0,1)")
        tcrit = student_t_quantile((1 + x["confidence_level"]) / 2, df)
        effect = x["mean_a"] - x["mean_b"]
        return {"mean_difference": effect, "standard_error": se, "welch_df": df, "student_t_critical": tcrit, "ci_lower": effect - tcrit * se, "ci_upper": effect + tcrit * se}, "exact_student_quantile_estimand_and_sampling_design_choose_test_not_normality_alone"
    raise ValueError(f"no explicit branch for {page_id}")


def main() -> None:
    args = parse_args()
    values, slice_hash, data_status = load(args.page_id, args.dataset.resolve())
    metrics, diagnostic = compute(args.page_id, values)
    print(f"page_id={args.page_id}")
    print(f"branch_id={args.page_id.lower()}-v1")
    print(f"engine_version={ENGINE_VERSION}")
    print("bundle_contract_complete=true")
    print(f"slice_sha256={slice_hash}")
    for key in sorted(metrics):
        print(f"metric.{key}={metrics[key]:.6f}")
    print(f"diagnostic={diagnostic}")
    print(f"data_status={data_status}")


if __name__ == "__main__":
    main()
