#!/usr/bin/env python3
"""compare.py — a reading against a frozen prediction. The 420 Code.

    python3 compare.py            # prints every comparison, and writes compare.json beside this file

It never touches a frozen script. It runs each one as it is served here, reads the predictions from what the script
prints, and reads each later reading from readings.json, where every reading names its source. It shows both errors
where both are given, and how they are combined (in quadrature). Where a row's condition needs judgement ("as the data
settle it", "confirmed", "credible"), it gives no verdict: it says the row waits for G's ruling. Nothing it writes goes
public without G's word.

Needs mpmath, as the scripts do. Zero-Clause BSD or MIT, at your choice. Studio G, 20 November 2026.
"""
import hashlib, json, math, os, re, subprocess, sys, datetime

HERE = os.path.dirname(os.path.abspath(__file__))
SCRIPTS = ['verify_cosmology.py', 'verify_family.py']


def stop(msg):
    sys.stderr.write('compare.py: STOP — ' + msg + '\n')
    sys.exit(1)


def run(name):
    env = dict(os.environ, PYTHONUTF8='1', PYTHONIOENCODING='utf-8')      # the scripts print in UTF-8 on every system
    r = subprocess.run([sys.executable, os.path.join(HERE, name)], capture_output=True, text=True, cwd=HERE, encoding='utf-8', env=env)
    if r.returncode != 0:
        stop(f'{name} did not run: {r.stderr[-300:]}')
    return r.stdout


def grab(text, pattern, what):
    m = re.search(pattern, text, re.M)
    if not m:
        stop(f'the frozen script no longer prints {what}')
    return m


def bar_of(r):
    """The bar a reading is read on: its total, or its two errors combined in quadrature."""
    if r.get('total') is not None:
        return r['total'], f"± {r['total']} ({r.get('error_note', 'as given')})"
    s, y = r.get('stat'), r.get('sys')
    if s is None or y is None:
        stop(f"reading {r['id']} gives neither a total bar nor both errors")
    return math.hypot(s, y), f'± {s} (stat) ± {y} (syst), combined in quadrature: ± {math.hypot(s, y):.4g}'


out = {name: run(name) for name in SCRIPTS}
cos, fam = out['verify_cosmology.py'], out['verify_family.py']

# the predictions, as the frozen scripts print them
share = float(grab(cos, r'predicted 1/21 = ([\d.]+) %', "the visible share's prediction").group(1))
column = float(grab(cos, r'^\s+A\s+Ob = ob_h2/h\^2\s+([\d.]+) %', "the named column's visible share").group(1))
share_bar = float(grab(cos, r'midpoint [\d.]+ \+/- ([\d.]+)', "the visible share's bar").group(1))
m = grab(fam, r'H0 = H0t0 / cycle\s+= ([\d.]+) km/s/Mpc;\s+window ([\d.]+) to ([\d.]+)', 'the closure and its window')
h0, lo, hi = float(m.group(1)), float(m.group(2)), float(m.group(3))
m = grab(fam, r'Cepheid ladder \(JWST, SH0ES\) ([\d.]+) \+/- ([\d.]+)', 'the Cepheid ladder')
ladder, ladder_bar = float(m.group(1)), float(m.group(2))

rows = {}

# the visible share, on the column its registration names (the dated note of 20 November 2026)
gap = (share - column) / share_bar
rel = share_bar / column
rows['vis'] = {
    'prediction': share, 'reading': column, 'bar': share_bar, 'unit': '%',
    'reading_label': 'Planck 2018, TT,TE,EE+lowE+lensing+BAO, Ω_b h² over h², not renormalised',
    'source': "the registration's own column (2026-08-02-visible-fraction-KS41.1, §3), as verify_cosmology.py prints it",
    'bars': gap, 'error_pct': (share - column) / column * 100,
    'condition': 'KS-41.1: a bar below half a per cent of the share, and a centre above 4.81 %',
    'condition_met': (rel < 0.005 and column > 4.81),
    'condition_reading': f'bar {share_bar} points, {rel * 100:.2f} % of the share; centre {column} %',
}

# the expansion rate: each later reading, inside the window or not; none called the first; KS-ASM.1 needs judgement
h0rows = []
R = json.load(open(os.path.join(HERE, 'readings.json'), encoding='utf-8'))['readings']
for r in R:
    if r['row'] != 'h0':
        continue
    b, how = bar_of(r)
    h0rows.append({'id': r['id'], 'label': r['label'], 'value': r['value'], 'bar': b, 'bar_shown': how, 'source': r['source'],
                   'source_url': r['source_url'], 'read_on': r['read_on'], 'inside': lo <= r['value'] <= hi,
                   'sigma_from_closure': (h0 - r['value']) / b})
rows['h0'] = {'prediction': h0, 'window': [lo, hi], 'unit': 'km/s/Mpc', 'readings': h0rows,
              'condition': 'KS-ASM.1: the expansion rate, as the data settle it, lands outside the window',
              'verdict': "none: the condition needs judgement, and the row waits for G's ruling"}

# the expansion rate against the Cepheid ladder (the reading the frozen document lists as outside the window)
rows['h0_ladder'] = {'prediction': h0, 'reading': ladder, 'bar': ladder_bar, 'unit': 'km/s/Mpc',
                     'reading_label': 'the Cepheid ladder remeasured with JWST (SH0ES)',
                     'source': 'the frozen document 2026-09-04-H0-KS-ASM.1, its table, as verify_family.py prints it',
                     'sigma': (h0 - ladder) / ladder_bar, 'error_pct': (h0 - ladder) / ladder * 100, 'inside': lo <= ladder <= hi,
                     'window': [lo, hi],
                     'verdict': "none: the switch fires on its registered condition, the window, as the data settle it; the row waits for G's ruling"}

# the baryon density: the work's 1/21 at its own rate, against each later reading
work_obh2 = share / 100 * (h0 / 100) ** 2
ob = []
for r in R:
    if r['row'] != 'obh2':
        continue
    b, how = bar_of(r)
    ob.append({'id': r['id'], 'label': r['label'], 'value': r['value'], 'bar': b, 'bar_shown': how, 'source': r['source'],
               'source_url': r['source_url'], 'read_on': r['read_on'], 'bars': (work_obh2 - r['value']) / b})
rows['obh2'] = {'work': work_obh2, 'how': 'the visible share 1/21 times (H₀/100)², at the closure H₀', 'readings': ob}

try:
    import mpmath
    mpv = mpmath.__version__
except Exception:
    mpv = 'not installed'
result = {
    'made': datetime.date.today().isoformat(),
    'python': sys.version.split()[0], 'mpmath': mpv,
    'scripts': {n: hashlib.sha256(open(os.path.join(HERE, n), 'rb').read()).hexdigest() for n in SCRIPTS},
    'compare.py': hashlib.sha256(open(os.path.abspath(__file__), 'rb').read()).hexdigest(),
    'rows': rows,
}
json.dump(result, open(os.path.join(HERE, 'compare.json'), 'w', encoding='utf-8', newline='\n'), ensure_ascii=False, indent=1)

v = rows['vis']
print(f"visible share: predicted {share} %, the named column {column} % ± {share_bar}: {abs(v['bars']):.2f} bars "
      f"{'below' if v['bars'] < 0 else 'above'}; KS-41.1's condition {'met' if v['condition_met'] else 'not met'} ({v['condition_reading']})")
for x in h0rows:
    print(f"expansion rate: {x['label']}: {x['value']} {x['bar_shown']}: {'inside' if x['inside'] else 'outside'} the window {lo}–{hi}")
L = rows['h0_ladder']
print(f"expansion rate against the Cepheid ladder: {h0} vs {ladder} ± {ladder_bar}: {L['sigma']:+.2f}σ, "
      f"{'inside' if L['inside'] else 'outside'} the window; {L['verdict']}")
for x in ob:
    print(f"baryon density: the work's {work_obh2:.5f} against {x['label']}, {x['value']} {x['bar_shown']}: "
          f"{abs(x['bars']):.1f} bars {'below' if x['bars'] < 0 else 'above'}")
