"""Re-run the rail example with the Python standard library."""
from decimal import Decimal
from pathlib import Path
import json

record = json.loads(Path(__file__).with_name("checks.json").read_text(encoding="utf-8"))
case = record["historical_case"]
base = Decimal(case["base_gbp_m"])
rows = {r["percentile"]: r for r in case["levels"]}

def total(uplift):
    return base * (1 + Decimal(uplift) / 100)

for level, row in rows.items():
    value = total(row["uplift_pct"])
    printed = row["worked_total_gbp_m"]
    print(f"P{level}: {row['uplift_pct']}% → £{value:g}m; worked total: {printed}")

assert total(rows[50]["uplift_pct"]) == rows[50]["worked_total_gbp_m"]
p80 = rows[80]
printed = Decimal(p80["worked_total_gbp_m"])
assert total(p80["uplift_pct"]) == 471 and printed - total(p80["uplift_pct"]) == 33
assert (printed / base - 1) * 100 == rows[90]["uplift_pct"] == 68
assert rows[90]["worked_total_gbp_m"] is None
lo, hi = (total(Decimal(p80["uplift_pct"]) + delta) for delta in (Decimal("-0.5"), Decimal("0.5")))
assert (lo, hi) == (Decimal("469.5"), Decimal("472.5")) and not lo <= printed <= hi
sample = case["reference_class"]
assert sample["uk"] + sample["other"] == sample["rail_projects"] == 46
assert [(r["code"], total(r["uplift_pct"])) for r in record["later_comparison"]["stages"]] == [
    ("SOBC", 663), ("OBC", 531), ("FBC", 480)]
for check in record["checks"]:
    assert all(s in record["source_versions"] for s in check["sources"])
print("P80 discrepancy £33m. Rounding envelope £469.5m–£472.5m. 2021 comparison £663m / £531m / £480m at a fixed illustrative £300m base.")
