"""Regenerate the Tukey lookup tables with SciPy 1.18.1.

Run from any directory after installing scipy==1.18.1 into your Python environment.
The script computes quantiles; it does not download or transcribe a published table.
UI interpolation and the worked example are maintained separately.
"""
from pathlib import Path
import json
import math
import re
import scipy
from scipy.stats import studentized_range, t, norm

if scipy.__version__ != '1.18.1':
    raise RuntimeError('Install scipy==1.18.1 to reproduce the published table')

page = Path(__file__).with_name('index.html')
text = page.read_text(encoding='utf-8')
dfs = list(range(1, 21)) + [24, 30, 40, 60, 120, math.inf]
for name, alpha in [('Q_005', .05), ('Q_001', .01), ('Q_010', .10)]:
    rows = []
    for df in dfs:
        row = [round(float(studentized_range.ppf(1-alpha, k, df)), 6) for k in range(2, 21)]
        assert all(math.isfinite(q) and q > 0 for q in row)
        assert all(a < b for a, b in zip(row, row[1:]))
        independent = math.sqrt(2) * (norm.ppf(1-alpha/2) if math.isinf(df) else t.ppf(1-alpha/2, df))
        assert abs(row[0] - independent) < 1e-5
        rows.append(row)
    table = '[\n' + ',\n'.join('  '+json.dumps(row) for row in rows) + '\n]'
    text, count = re.subn(r'var '+name+r' = \[[\s\S]*?\];', 'var '+name+' = '+table+';', text)
    assert count == 1
page.write_text(text, encoding='utf-8')
print(f'Regenerated 1,482 quantiles with SciPy {scipy.__version__}; k=2 identity checked for every row.')
