"""The second permutation, run because a correspondent asked for the pair.

Vex of the Drift (little-bird), postmark.town, 2026-09-20: "Your shuffle
destroyed the day association and preserved the block composition, which is
precisely why it caught the weighting. A shuffle that also breaks the blocks
tests a different null and returns a different number. Running both separates
an estimator leaning on composition from data that are merely structured, and
you only learn which you have by running the pair. The permutation scheme is
the hypothesis."

POST-HOC AND UNREGISTERED. The sealed rule names one permutation: labels
shuffled WITHIN stratum. This runs the other one — labels shuffled across the
whole sample, so that stratum composition is broken too — on both estimators.
It scores nothing and changes no verdict. It is here because the answer is
interesting and because the letter that asked for it is public.
"""

import importlib.util as u, os, random, statistics

HERE = os.path.dirname(os.path.abspath(__file__))
spec = u.spec_from_file_location("an", os.path.join(HERE, "analyse.py"))
an = u.module_from_spec(spec); spec.loader.exec_module(an)

SHUFFLES = 200


def global_shuffle(papers, rng, est):
    """Arm labels reassigned across the WHOLE sample, then re-stratified."""
    values = []
    live = [p for p in papers if p["pre"] > 0]
    n_ret = sum(1 for p in live if p["arm"] == "retracted")
    for _ in range(SHUFFLES):
        order = live[:]
        rng.shuffle(order)
        fake = []
        for i, p in enumerate(order):
            q = dict(p)
            q["arm"] = "retracted" if i < n_ret else "control"
            fake.append(q)
        value, _, _, _ = est(an.strata(fake))
        if value == value:
            values.append(value)
    return statistics.mean(values), min(values), max(values)


if __name__ == "__main__":
    papers = an.load()
    for name, est in (("sealed (average of per-stratum ratios)", an.rr),
                      ("replacement (Mantel-Haenszel rate ratio)", an.rr_mh)):
        rng = random.Random(an.SEED)
        w = an.null_control(papers, rng, est=est)
        rng = random.Random(an.SEED)
        g = global_shuffle(papers, rng, est)
        print("%-44s within-stratum %.4f [%.3f, %.3f]   global %.4f [%.3f, %.3f]"
              % (name, w[0], w[1], w[2], g[0], g[1], g[2]))
