#!/usr/bin/env python3
"""Original synthetic Week 10 lab: within-source identification versus transport.

Standard library only. This is not a replication of Allcott (2015) or any
personnel study. Population, potential outcomes, contexts, and numbers are
invented. Student estimators use only observed rows and pretreatment weights.
Instructor audits use potential outcomes in a separate output directory.
"""
from __future__ import annotations

import argparse
import csv
import hashlib
import itertools
import json
import math
import random
import statistics
import sys
from pathlib import Path
from typing import Any

DEFAULT_SEED = 20260922
PROVENANCE = "SYNTHETIC_TEACHING_CONSTRUCTION_NOT_PUBLISHED_REPLICATION"
MODE = "original_synthetic_design_reconstruction"
GENERATED_FILES = ('data/teaching/source_sites.csv', 'data/teaching/target_frame.csv', 'data/teaching/teaching-schema.csv', 'data/instructor/source_potential_outcomes.csv', 'data/instructor/design_audit.csv', 'data/instructor/recomputed-potential-outcome-distribution.csv', 'output/reproduced/pair_contrasts.csv', 'output/reproduced/stratum_estimates.csv', 'output/reproduced/estimates.csv', 'output/reproduced/target_weights.csv', 'output/reproduced/global_sharp_null_distribution.csv', 'output/reproduced/source-mode-ledger.csv', 'output/reproduced/reproduction_status.json', 'output/diagnose/transport_scenarios.csv', 'output/diagnose/transport_sensitivity.csv', 'output/diagnose/unsupported_context.json', 'output/diagnose/worker_followup_bounds.json', 'output/diagnose/worker_followup_bounds.csv', 'output/diagnose/incidence.json', 'output/diagnose/weighting_target.csv', 'output/diagnose/measurement_worlds.csv', 'output/diagnose/selective_stayers.json', 'output/diagnose/selective_success_story.json', 'output/diagnose/pilot_vs_rollout.json', 'output/diagnose/mechanism_underidentification.json', 'output/transfer/claim_card.md', 'output/results.md', 'checks.json', 'run_summary.json', 'validation.json')
SOURCE_MASS = {"high": 2.0 / 3.0, "low": 1.0 / 3.0}
TARGET_MASS = {"high": 0.25, "low": 0.75}


def mean(values: list[float]) -> float:
    if not values:
        raise ValueError("Cannot take a mean of an empty list.")
    return math.fsum(values) / len(values)


def check_close(a: float, b: float, atol: float = 1e-9) -> bool:
    return math.isclose(a, b, rel_tol=1e-10, abs_tol=atol)


class Audit:
    def __init__(self) -> None:
        self.items: list[dict[str, Any]] = []

    def add(self, name: str, passed: bool) -> None:
        if any(x["name"] == name for x in self.items):
            raise AssertionError("Duplicate test name: " + name)
        self.items.append({"name": name, "passed": bool(passed)})
        if not passed:
            raise AssertionError(name)

    def close(self, name: str, a: float, b: float) -> None:
        self.add(name, check_close(a, b))


def write_json(path: Path, value: Any) -> None:
    if isinstance(value, dict):
        value = {"provenance": PROVENANCE, "mode": MODE, "empirical_replication": False, **value}
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8")


def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
    if not rows:
        raise ValueError("Empty CSV has no explicit schema: " + str(path))
    path.parent.mkdir(parents=True, exist_ok=True)
    rows = [{"provenance": PROVENANCE, **row} for row in rows]
    fields = list(rows[0])
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n")
        writer.writeheader()
        for row in rows:
            if set(row) != set(fields):
                raise ValueError("Inconsistent CSV schema")
            writer.writerow({k: format(v, ".12g") if isinstance(v, float) else v for k, v in row.items()})


def build_population(seed: int) -> list[dict[str, Any]]:
    rng = random.Random(seed)
    pairs = [("high", x) for x in (-0.75, -0.25, 0.25, 0.75)]
    pairs += [("low", x) for x in (-0.5, 0.5)]
    rows: list[dict[str, Any]] = []
    for p, (context, effect_offset) in enumerate(pairs):
        common_change = 2.0 + rng.uniform(-3.0, 3.0)
        for position in (0, 1):
            baseline = 100.0 + (20.0 if context == "high" else 0.0) + rng.uniform(-6.0, 6.0)
            untreated_change = common_change + rng.uniform(-2.0, 2.0)
            tau = (8.0 if context == "high" else 2.0) + effect_offset + (-0.2 if position == 0 else 0.2)
            rows.append({
                "site_id": f"S{2*p+position+1:02d}", "pair_id": p + 1,
                "context": context, "position": position, "baseline": baseline,
                "post_y0": baseline + untreated_change,
                "post_y1": baseline + untreated_change + tau,
                "effect": tau,
            })
    return rows


def realize(population: list[dict[str, Any]], bits: tuple[int, ...]) -> list[dict[str, Any]]:
    if len(bits) != 6 or not all(b in (0, 1) for b in bits):
        raise ValueError("Assignment must have one bit for each of six pairs")
    result = []
    for row in population:
        z = int(row["position"] == bits[row["pair_id"] - 1])
        post = row["post_y1"] if z else row["post_y0"]
        result.append({
            "site_id": row["site_id"], "pair_id": row["pair_id"],
            "context": row["context"], "position": row["position"],
            "assigned": z, "baseline": row["baseline"], "post": post,
            "change": post - row["baseline"],
        })
    return result


def pair_contrasts(observed: list[dict[str, Any]], bits: tuple[int, ...] | None = None) -> list[dict[str, Any]]:
    """For RI, bits change labels only: keep observed changes fixed."""
    rows = []
    for p in range(1, 7):
        group = [r for r in observed if r["pair_id"] == p]
        if len(group) != 2 or group[0]["context"] != group[1]["context"]:
            raise ValueError("Each pair must contain two sites of the same context")
        treated = [r for r in group if (r["assigned"] == 1 if bits is None else r["position"] == bits[p-1])]
        control = [r for r in group if r not in treated]
        if len(treated) != 1 or len(control) != 1:
            raise ValueError("One treated and one control per pair required")
        rows.append({"pair_id": p, "context": group[0]["context"],
                     "contrast": treated[0]["change"] - control[0]["change"]})
    return rows


def estimate(pairs: list[dict[str, Any]], masses: dict[str, float]) -> tuple[float, float]:
    if set(masses) != {"high", "low"} or not check_close(sum(masses.values()), 1.0):
        raise ValueError("Context masses must cover high/low and sum to one")
    estimate_value = 0.0
    estimated_variance = 0.0
    for context in ("high", "low"):
        values = [r["contrast"] for r in pairs if r["context"] == context]
        if len(values) < 2:
            raise ValueError("Need at least two independent pairs per context for this variance summary")
        a = masses[context]
        estimate_value += a * mean(values)
        estimated_variance += a*a*statistics.variance(values)/len(values)
    return estimate_value, estimated_variance


def true_effect(population: list[dict[str, Any]], masses: dict[str, float]) -> float:
    return math.fsum(masses[c] * mean([r["effect"] for r in population if r["context"] == c]) for c in masses)


def bounds(observed_share: float, observed_mean: float, lower: float, upper: float) -> tuple[float, float]:
    if not 0 <= observed_share <= 1 or not lower <= observed_mean <= upper:
        raise ValueError("Invalid outcome-bound inputs")
    return (observed_share*observed_mean+(1-observed_share)*lower,
            observed_share*observed_mean+(1-observed_share)*upper)


def original_diagnostics(out: Path, audit: Audit) -> None:
    scenarios = [
        {"scenario": "source_mix", "high_share": 2/3, "high_effect": 8.0, "low_effect": 2.0, "effect": 6.0},
        {"scenario": "target_stable", "high_share": .25, "high_effect": 8.0, "low_effect": 2.0, "effect": 3.5},
        {"scenario": "target_changed_implementation", "high_share": .25, "high_effect": 5.0, "low_effect": -1.0, "effect": .5},
    ]
    for r in scenarios:
        audit.close(r["scenario"]+"_arithmetic", r["effect"], r["high_share"]*r["high_effect"]+(1-r["high_share"])*r["low_effect"])
    write_csv(out/"output/diagnose/transport_scenarios.csv", scenarios)
    sensitivity = [{"unobserved_shift": d, "source_standardized_prediction": 3.5,
                    "true_target_effect_under_assumed_shift": 3.5-d} for d in (-2.0, 0.0, 1.0, 3.0, 5.0)]
    write_csv(out/"output/diagnose/transport_sensitivity.csv", sensitivity)
    audit.close("implementation_shift_error", 3.5-.5, 3.0)
    audit.add("perfect_recorded_support_does_not_imply_stability", scenarios[1]["high_share"] == scenarios[2]["high_share"] and scenarios[1]["effect"] != scenarios[2]["effect"])
    support_bounds = (.8*3.5+.2*(-20), .8*3.5+.2*5)
    audit.close("unsupported_lower", support_bounds[0], -1.2)
    audit.close("unsupported_upper", support_bounds[1], 3.8)
    audit.add("unsupported_range_crosses_zero", support_bounds[0]<0<support_bounds[1])
    write_json(out/"output/diagnose/unsupported_context.json", {
        "supported_mass": .8, "supported_effect": 3.5, "assumed_unsupported_effect_bounds": [-20,5],
        "whole_target_identification_range": list(support_bounds),
        "warning": "Conditional identification range, not a confidence interval or data-estimated bound."})
    t = bounds(.5,70,0,100); c = bounds(.9,60,0,100)
    diff = (t[0]-c[1],t[1]-c[0])
    for name,a,b in [("treated_mean_lower",t[0],35),("treated_mean_upper",t[1],85),
                     ("control_mean_lower",c[0],54),("control_mean_upper",c[1],64),
                     ("attrition_difference_lower",diff[0],-29),("attrition_difference_upper",diff[1],31)]:
        audit.close(name,a,b)
    write_json(out/"output/diagnose/worker_followup_bounds.json", {
        "scale": [0,100], "observed_difference": 10,
        "treated_full_mean_range": t, "control_full_mean_range": c,
        "difference_identification_range": diff,
        "warning": "Invented bounded outcome; arbitrary missingness; no sampling interval supplied."})
    incidence={"verified_output_value":12,"setup_resources":4,"operating_resources":2,
               "pay_transfer":2,"worker_effort_cost":3,"worker_amenity_value":1,
               "firm_change":4,"worker_change":0,"joint_change":4}
    audit.close("firm_accounting",12-4-2-2,incidence["firm_change"])
    audit.close("worker_accounting",2+1-3,incidence["worker_change"])
    audit.close("joint_transfer_cancellation",12-4-2+1-3,incidence["joint_change"])
    audit.close("sum_incidence",incidence["firm_change"]+incidence["worker_change"],incidence["joint_change"])
    write_json(out/"output/diagnose/incidence.json", {**incidence,"warning":"Separate invented monetary example; the main lab outcome is not automatically monetized welfare."})
    unit_weights=[{"population":"establishment_weighted","effect":(1+9)/2},
                  {"population":"initial_worker_weighted","effect":(900*1+100*9)/1000}]
    audit.close("site_weighted_example",unit_weights[0]["effect"],5)
    audit.close("worker_weighted_example",unit_weights[1]["effect"],1.8)
    write_csv(out/"output/diagnose/weighting_target.csv",unit_weights)
    measurement=[{"world":"real_output","recorded_change":10,"audited_change":10,"measurement_rule_change":0},
                 {"world":"recording_only","recorded_change":10,"audited_change":0,"measurement_rule_change":10}]
    audit.add("observational_equivalence_record",measurement[0]["recorded_change"] == measurement[1]["recorded_change"])
    audit.add("audit_distinguishes_worlds",measurement[0]["audited_change"] != measurement[1]["audited_change"])
    write_csv(out/"output/diagnose/measurement_worlds.csv",measurement)
    prior=[80,40]; later=[80]
    audit.close("stayer_mean_increase",mean(later)-mean(prior),20)
    audit.close("total_production_drop",sum(later)-sum(prior),-40)
    write_json(out/"output/diagnose/selective_stayers.json",{"baseline":prior,"later_stayers":later,"mean_change":20,"total_change":-40,"no_individual_improvement":True})
    # A fixed constructed list illustrates maximization, not a publication-bias estimate.
    reported=[-4,-1,0,1,4,12]
    audit.close("constructed_all_pilot_mean",mean(reported),2)
    audit.close("constructed_selected_best",max(reported),12)
    write_json(out/"output/diagnose/selective_success_story.json",{"six_invented_estimates":reported,"mean_all":2,"selected_maximum":12,"independent_holdout_example":2,"warning":"Arithmetic illustration, not an estimated publication-bias correction."})
    # Explicit interference counterexample; not the no-interference main experiment.
    def spill(z: int,e: float) -> float: return 100+4*z-3*e
    audit.close("direct_fixed_exposure",spill(1,.5)-spill(0,.5),4)
    audit.close("full_rollout_effect",spill(1,1)-spill(0,0),1)
    write_json(out/"output/diagnose/pilot_vs_rollout.json",{"direct_fixed_exposure":4,"all_treated_vs_none":1,"warning":"Separate invented interference model; not identified by the main experiment."})
    # Matrix-free design rank: perfect co-adoption cannot distinguish components.
    cells=[{"regime":"none","tool":0,"redesign":0,"effect":0},
           {"regime":"bundle","tool":1,"redesign":1,"effect":12}]
    audit.add("two_component_worlds_same_bundle", 0+0+12 == -4+3+13)
    write_json(out/"output/diagnose/mechanism_underidentification.json",{"observed_cells":cells,"world1":[0,0,12],"world2":[-4,3,13],"component_order":["tool","redesign","interaction"]})


def run(out: Path, seed: int) -> dict[str, Any]:
    if out.is_symlink() or (out.exists() and (not out.is_dir() or any(out.iterdir()))):
        raise FileExistsError("Refusing to overwrite a nonempty output path: " + str(out))
    out.mkdir(parents=True, exist_ok=True)
    audit=Audit()
    population=build_population(seed)
    rng=random.Random(seed+917)
    bits=tuple(rng.randrange(2) for _ in range(6))
    assignments=list(itertools.product((0,1),repeat=6))
    observed=realize(population,bits)
    target=[{"site_id":f"T{i+1:02d}","context":"high" if i<5 else "low","baseline_target_weight":.05} for i in range(20)]
    write_csv(out/"data/teaching/source_sites.csv",observed)
    write_csv(out/"data/teaching/target_frame.csv",target)
    write_csv(out/"data/instructor/source_potential_outcomes.csv",population)
    audit.add("source_twelve_sites",len(observed)==12)
    audit.add("six_pairs",len({r["pair_id"] for r in observed})==6)
    audit.add("target_twenty_sites",len(target)==20)
    audit.add("target_five_high_sites",sum(r["context"]=="high" for r in target)==5)
    audit.close("target_mass_sums_one",sum(r["baseline_target_weight"] for r in target),1)
    audit.add("assignment_support_64",len(assignments)==64 and bits in assignments)
    audit.add("six_treated",sum(r["assigned"] for r in observed)==6)
    audit.add("no_latent_fields_in_observed",not {"effect","post_y0","post_y1"}.intersection(observed[0]))
    audit.add("no_outcomes_in_target_frame",not {"post","effect","post_y0","post_y1"}.intersection(target[0]))
    for p in range(1,7):
        group=[r for r in observed if r["pair_id"]==p]
        audit.add(f"pair_{p}_one_treated",sum(r["assigned"] for r in group)==1)
    audit.close("high_truth",mean([r["effect"] for r in population if r["context"]=="high"]),8)
    audit.close("low_truth",mean([r["effect"] for r in population if r["context"]=="low"]),2)
    audit.close("source_truth",true_effect(population,SOURCE_MASS),6)
    audit.close("stable_target_truth",true_effect(population,TARGET_MASS),3.5)
    weights=[{"site_id":r["site_id"],"context":r["context"],"density_ratio":TARGET_MASS[r["context"]]/SOURCE_MASS[r["context"]]} for r in observed]
    w=[r["density_ratio"] for r in weights]
    ess=sum(w)**2/sum(x*x for x in w)
    audit.close("weight_sum",sum(w),12)
    audit.close("high_weight",weights[0]["density_ratio"],.375)
    audit.close("low_weight",weights[-1]["density_ratio"],2.25)
    audit.close("weight_ess",ess,144/21.375)
    audit.add("weight_ess_less_than_rows",ess<12)
    write_csv(out/"output/reproduced/target_weights.csv",weights)
    pairs=pair_contrasts(observed)
    write_csv(out/"output/reproduced/pair_contrasts.csv",pairs)
    strata=[{"context":c,"pair_count":sum(r["context"]==c for r in pairs),"estimate":mean([r["contrast"] for r in pairs if r["context"]==c])} for c in ("high","low")]
    write_csv(out/"output/reproduced/stratum_estimates.csv",strata)
    estimate_rows=[]; ri_rows=[]; audit_rows=[]
    oracle_rows=[]
    for name,masses in [("source",SOURCE_MASS),("target_standardized",TARGET_MASS)]:
        est,var=estimate(pairs,masses)
        null_values=[]; actual_values=[]; actual_vars=[]
        for k,b in enumerate(assignments):
            null_stat,_=estimate(pair_contrasts(observed,b),masses)
            null_values.append(null_stat)
            actual_est,actual_var=estimate(pair_contrasts(realize(population,b)),masses)
            actual_values.append(actual_est);actual_vars.append(actual_var)
            oracle_rows.append({"estimand":name,"assignment_index":k,"assignment":"".join(map(str,b)),"recomputed_estimate":actual_est,"variance_estimator":actual_var})
            ri_rows.append({"estimand":name,"assignment_index":k,"assignment":"".join(map(str,b)),"global_sharp_null_statistic":null_stat})
        pvalue=sum(abs(x)>=abs(est)-1e-10 for x in null_values)/len(null_values)
        truth=true_effect(population,masses)
        design_var=mean([(x-truth)**2 for x in actual_values])
        audit.close(name+"_design_unbiased",mean(actual_values),truth)
        audit.close(name+"_null_symmetry",mean(null_values),0)
        audit.close(name+"_observed_in_null_support",null_values[assignments.index(bits)],est)
        audit.add(name+"_valid_exact_pvalue",0<pvalue<=1 and check_close(pvalue*64,round(pvalue*64)))
        audit.add(name+"_nonnegative_variance",var>=0 and design_var>=0)
        audit.add(name+"_expected_variance_conservative",mean(actual_vars)>=design_var-1e-9)
        estimate_rows.append({"estimand":name,"estimate":est,"paired_stratified_se":math.sqrt(var),"global_sharp_null_p":pvalue,"independent_pairs":6,"normal_ci_provided":False})
        audit_rows.append({"estimand":name,"finite_population_truth":truth,"mean_over_design":mean(actual_values),"exact_design_variance":design_var,"expected_variance_estimator":mean(actual_vars)})
    write_csv(out/"output/reproduced/estimates.csv",estimate_rows)
    write_csv(out/"output/reproduced/global_sharp_null_distribution.csv",ri_rows)
    write_csv(out/"data/instructor/design_audit.csv",audit_rows)
    # Estimation is rechecked after serializing observed data; instructor fields are absent.
    with (out/"data/teaching/source_sites.csv").open(newline="",encoding="utf-8") as f:
        loaded=list(csv.DictReader(f))
    for row in loaded:
        for k in ("pair_id","position","assigned"):row[k]=int(row[k])
        for k in ("baseline","post","change"):row[k]=float(row[k])
    for name,masses in [("source",SOURCE_MASS),("target_standardized",TARGET_MASS)]:
        e,_=estimate(pair_contrasts(loaded),masses)
        audit.close(name+"_observed_csv_only_parity",e,next(r["estimate"] for r in estimate_rows if r["estimand"]==name))
    original_diagnostics(out,audit)
    (out/"output/transfer").mkdir(parents=True,exist_ok=True)
    (out/"output/transfer/claim_card.md").write_text("# Capstone claim card\n\nSYNTHETIC_TEACHING_CONSTRUCTION_NOT_PUBLISHED_REPLICATION\n\nDecision and labor margin:\n\nInitially eligible population:\n\nAssignment versus receipt:\n\nOutcome, unit, denominator, horizon:\n\nTwo competing mechanisms and distinguishing observations:\n\nSource-to-target assumptions and missing support:\n\nWorker/firm accounting:\n\nChecked versus pending data access:\n\nStrongest supported claim:\n\nTempting unsupported claim:\n\nSmallest useful next step:\n\nUse the distributed full memo template and review rubric for the final proposal. All lab data are original synthetic examples.\n",encoding="utf-8")
    summary={"mode":"original_synthetic_design_reconstruction","seed":seed,"sites":12,"independent_pairs":6,"target_sites":20,"permitted_assignments":64,"weight_effective_sample_size":ess,"assertion_count":len(audit.items),"all_assertions_pass":True,"estimates":estimate_rows,"no_original_microdata_used":True,"warning":"RI concerns a source global sharp null, not target transport validity. SEs are small-design summaries, not automatic normal-inference guarantees."}
    write_json(out/"checks.json",{"passed":True,"count":len(audit.items),"checks":audit.items})
    write_json(out/"run_summary.json",summary)
    write_csv(out/"data/instructor/recomputed-potential-outcome-distribution.csv",oracle_rows)
    fields={
        "site_id":("string","invented site identifier","Primary key within the source or target frame"),
        "pair_id":("integer","1..6","Source matched pair; four high-support and two low-support pairs"),
        "context":("category","high/low","Pretreatment implementation resources; not statistical common support"),
        "position":("integer","0/1","Site position used by the fixed pair-assignment algorithm"),
        "assigned":("binary","0/1","One reform recipient per source pair"),
        "baseline":("number","productivity units","Observed fixed pretreatment baseline"),
        "post":("number","productivity units","Complete observed source follow-up under realized assignment"),
        "change":("number","productivity units","Post minus baseline; student estimators use this observed field"),
        "baseline_target_weight":("number","equal site mass .05","Predetermined target weight; no target outcomes supplied"),
        "provenance":("string","synthetic marker","Invented teaching records, not original empirical data")}
    write_csv(out/"data/teaching/teaching-schema.csv",[
        {"file":file,"field":field,"type":fields[field][0],"units_or_support":fields[field][1],"meaning":fields[field][2],"key":"site_id"}
        for file,rows in [("source_sites.csv",observed),("target_frame.csv",target)]
        for field in ["provenance"]+list(rows[0])])
    followup=json.loads((out/"output/diagnose/worker_followup_bounds.json").read_text())
    write_csv(out/"output/diagnose/worker_followup_bounds.csv",[
        {"object":"treated_full_mean","response_rate":.5,"respondent_mean":70,"lower":followup["treated_full_mean_range"][0],"upper":followup["treated_full_mean_range"][1]},
        {"object":"control_full_mean","response_rate":.9,"respondent_mean":60,"lower":followup["control_full_mean_range"][0],"upper":followup["control_full_mean_range"][1]},
        {"object":"treated_minus_control","response_rate":"","respondent_mean":"","lower":followup["difference_identification_range"][0],"upper":followup["difference_identification_range"][1]}])
    write_csv(out/"output/reproduced/source-mode-ledger.csv",[
        {"object":"source experiment, target frame and all scenarios","source":"native original Week10 teaching starter","status":MODE,"empirical_replication":False,"original_data_downloaded":False},
        {"object":"original empirical study replication","source":"Allcott; Bloom–Han–Liang; DellaVigna–Linos intellectual anchors","status":"NOT RUN; no original archive contents inspected","empirical_replication":False,"original_data_downloaded":False}])
    write_json(out/"output/reproduced/reproduction_status.json",{
        "seed":seed,"starter_assertions_passed":len(audit.items),"source_sites":12,"independent_pairs":6,"target_sites":20,"legal_allocations":64,
        "original_data_downloaded":False,"original_programs_executed":False,
        "command":f"python src/offline_lab.py --out NEW_EMPTY_DIRECTORY --seed {seed}",
        "generated_artifacts_excluding_manifest":len(GENERATED_FILES),
        "scope":"Original synthetic reconstruction; observed source outcomes and outcome-free target frame.",
        "null_warning":"Both statistics test the global source sharp no-effect null with observed changes and weights fixed; neither tests transport.",
        "variance_warning":"Source and target use different context masses in a paired/context-stratified variance summary; no normal CI supplied.",
        "oracle_warning":"Recomputed potential outcomes and variance are instructor truth, not empirical uncertainty."})
    (out/"validation.json").write_bytes((out/"checks.json").read_bytes())
    result_rows="\n".join(f"| {r['estimand']} | {r['estimate']:.9f} | {r['paired_stratified_se']:.9f} | {r['global_sharp_null_p']:.6f} |" for r in estimate_rows)
    (out/"output/results.md").write_text(f"""# Week 10 generated results

{PROVENANCE}

Mode: `{MODE}`; empirical replication: **false**. No original microdata or estimation programs executed.
Seed {seed}; twelve source sites, six independent pairs, 64 equal assignments; twenty target sites with no outcomes.

| Source-data statistic | Observed estimate | Paired/context-stratified SE | Source global-sharp-null p |
|---|---:|---:|---:|
{result_rows}

Both estimators use observed source changes. Target masses (.25,.75) standardize source context effects;
an interpretation as an unobserved target effect additionally requires stability, compatible regimes/outcomes and overlap.
The exact test fixes observed source changes and predetermined weights. Its target-weighted statistic does not test transport.
There are four high-support and two low-support pairs. Weight ESS {ess:.9f} measures concentration, not independent assignments.
Source and target SEs use their respective context weights. No normal interval is supplied.
The separate instructor audit recomputes potential outcomes: source truth 6 and stable-target truth 3.5.
The invented changed-implementation scenario is .5; no target observations identify it.
Arbitrary-missingness ranges and unsupported-context ranges are not confidence intervals or Lee bounds.
All {len(audit.items)} native assertions pass, including observed-CSV-only parity.
""",encoding="utf-8")
    files={name:hashlib.sha256((out/name).read_bytes()).hexdigest() for name in GENERATED_FILES}
    write_json(out/"manifest.json",{"seed":seed,"sha256":files})
    return summary


def main() -> int:
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out",type=Path,required=True,help="Fresh output directory; nonempty paths are refused.")
    parser.add_argument("--seed",type=int,default=DEFAULT_SEED)
    args=parser.parse_args()
    try:
        summary=run(args.out,args.seed)
    except (FileExistsError,ValueError) as exc:
        print(str(exc),file=sys.stderr)
        return 2
    print(json.dumps(summary,indent=2,sort_keys=True))
    return 0


if __name__=="__main__":
    raise SystemExit(main())
