"""
Worked out after the pause test's result (pause_test_results.txt), from records only: no simulation.

The pause test found that picking up again changes the gap at the very first put-back after the pick-up (paused at
t = 180, first gap difference at t = 185). If the two paused batches parted from today's runs because of their pauses,
each start's first gap difference marks its first pause, 5 units earlier. Each piece ran for at most 230 s (the nudge
test's LYAP_BUDGET), so a start's first pause came after about 230 s of running, settling included. Its first gap
difference then implies how fast it ran in its first piece, and that can be set beside the running time its saved file
records.

A correction found on the way: the nudge test's long run (old starts 1 to 6) ran as six tasks of one start each, not
as one task of six (nudge_test.py: LYAP_SPLIT = {4000: 6}, the same at the commits before and after that run; the
lyapunov-long command runs one task per start). Its file records only the six tasks' running times added together.

This is a check of consistency, set after the result, not a test.
"""
import json
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
GROWTH = HERE.parent / "coherence-growth-2026-10-11"
NUDGE = HERE.parent / "nudge-test-2026-10-10"
BUDGET, SETTLE, LENGTH, EVERY = 230.0, 300.0, 6300.0, 5.0


def spearman(a, b):
    ra, rb = np.argsort(np.argsort(a)), np.argsort(np.argsort(b))
    return float(np.corrcoef(ra, rb)[0, 1])


def main():
    first = {}
    for record in json.loads((HERE / "machine_check.json").read_text())["checks"]:
        for r in record["results"]:
            if "saved" in r and r["saved"].get("first_gap_interval") is not None:
                first[r["start"]] = EVERY * (r["saved"]["first_gap_interval"] + 1)
    with np.load(NUDGE / "sim_lyapunov4000_long.npz") as d:
        total_1_6 = float(d["seconds"][0])
    with np.load(GROWTH / "sim_fresh4000.npz") as d:
        totals_7_12 = dict(zip((d["starts"] + 1).tolist(), d["seconds"].tolist()))
    rows = []
    for s in range(1, 13):
        pause = first[s] - EVERY
        speed = (pause + SETTLE) / BUDGET                      # time units per second in the first piece
        rows.append(dict(start=s, first_gap_difference=first[s], implied_first_pause=pause,
                         implied_first_piece_speed=speed, implied_total_at_that_speed=LENGTH / speed,
                         recorded_total=totals_7_12.get(s), recorded_average_speed=(LENGTH / totals_7_12[s]
                                                                                   if s in totals_7_12 else None)))
    batch1 = [r for r in rows if r["start"] <= 6]
    batch2 = [r for r in rows if r["start"] >= 7]
    result = dict(
        title="Pause test follow-up: first gap differences against recorded running times (after the result)",
        rows=rows,
        batch_1_to_6=dict(implied_total=sum(r["implied_total_at_that_speed"] for r in batch1), recorded_total=total_1_6,
                          recorded_average_speed=6 * LENGTH / total_1_6,
                          implied_mean_speed=float(np.mean([r["implied_first_piece_speed"] for r in batch1]))),
        batch_7_to_12=dict(rank_correlation_departure_with_speed=spearman(
            [r["first_gap_difference"] for r in batch2], [r["recorded_average_speed"] for r in batch2])))
    (HERE / "pause_test_followup.json").write_text(json.dumps(result, indent=1) + "\n")
    b1, b2 = result["batch_1_to_6"], result["batch_7_to_12"]
    lines = [result["title"], "",
             "If a start's first gap difference marks its first pause, it ran at (pause + 300) / 230 time units per"
             " second in its first piece.", "",
             "start  first gap diff  implied 1st-piece speed  implied total  recorded total (average speed)"]
    for r in rows:
        rec = (f"{r['recorded_total']:,.0f} s ({r['recorded_average_speed']:.1f}/s)" if r["recorded_total"]
               else "with starts 1-6")
        lines.append(f"{r['start']:>5}  {r['first_gap_difference']:>14,.0f}  {r['implied_first_piece_speed']:>17.1f}/s"
                     f"  {r['implied_total_at_that_speed']:>11,.0f} s  {rec}")
    lines += ["",
              f"Starts 1 to 6 (six tasks; their file records only the sum): at the implied speeds they would have run"
              f" {b1['implied_total']:,.0f} s in all; their file records {b1['recorded_total']:,.0f} s (average"
              f" {b1['recorded_average_speed']:.1f} units/s; implied {b1['implied_mean_speed']:.1f}).",
              f"Starts 7 to 12: the slower a start ran overall, the earlier it parted (rank correlation of first gap"
              f" difference with average speed {b2['rank_correlation_departure_with_speed']:+.2f}). Starts 7 and 8"
              " would have needed a first piece slower than their own average ("
              + " and ".join(f"{r['implied_first_piece_speed']:.1f}" for r in batch2[:2]) + " against "
              + " and ".join(f"{r['recorded_average_speed']:.1f}" for r in batch2[:2]) + " units/s).",
              "", "A consistency check worked out after the result, not a test: the pause points were not recorded."]
    (HERE / "pause_test_followup.txt").write_text("\n".join(lines) + "\n")
    print("\n".join(lines))


if __name__ == "__main__":
    main()
