"""Standalone numerical replay for evidence.json; requires NumPy, SciPy and numerics.py.

This checks published numbers, not private provider authenticity or calibration.
"""
import argparse
import json
import math
from pathlib import Path
import numpy as np
from numerics import assemble_fmo, train_signs


def replay(data):
    if data.get('schema')!='qb.public-qualification-screen/v1':
        raise ValueError('public screen schema required')
    expected={f'M{i}' for i in range(4)}|{f'D{i}_{j}' for i in range(4) for j in range(i+1,4)}
    matrices=data['restricted_matrices']
    if len(matrices)!=10 or {f['id'] for f in matrices}!=expected:
        raise ValueError('complete distinct restricted matrices required')
    groups=data['numerical_observations']['groups']
    if len(groups)!=2 or {g['kind'] for g in groups}!={'monomer','dimer'}:
        raise ValueError('representative monomer and dimer counts required')
    probabilities={}
    for group in groups:
        width=1 if group['kind']=='monomer' else 2;counts=group['counts'];shots=group['shots']
        if type(shots) is not int or shots<=0 or group['bit_order']!='q0-first':
            raise ValueError('positive shots and frozen bit order required')
        if (any(not isinstance(k,str) or len(k)!=width or set(k)-set('01') for k in counts)
                or any(type(n) is not int or n<0 for n in counts.values()) or sum(counts.values())!=shots):
            raise ValueError('valid counts with exact shot conservation required')
        probabilities[group['kind']]=[counts.get(format(i,f'0{width}b'),0)/shots for i in range(2**width)]
    energies={};refs={}
    for f in matrices:
        kind='monomer' if f['id'].startswith('M') else 'dimer';width=2 if kind=='monomer' else 4
        h=np.asarray(f['hamiltonian'],dtype=float)
        if h.shape!=(width,width) or not np.all(np.isfinite(h)) or not np.allclose(h,h.T,atol=1e-12,rtol=0):
            raise ValueError('finite symmetric restricted matrix required')
        refs[f['id']]=float(np.linalg.eigvalsh(h)[0])
        if not math.isclose(refs[f['id']],f['reference_energy'],abs_tol=1e-10,rel_tol=0):
            raise ValueError('reference differs from retained matrix')
        energies[f['id']]=train_signs(h,probabilities[kind],[0,-2] if kind=='monomer' else [-1,-1,-1])['energy']
    def total(values):
        return assemble_fmo([values[f'M{i}'] for i in range(4)],
                            {(i,j):values[f'D{i}_{j}'] for i in range(4) for j in range(i+1,4)})
    result=total(energies);reference=total(refs)
    stored=data['energy_replay']
    if len(stored['fragments'])!=10:
        raise ValueError('exactly ten published fragment records required')
    saved={f['id']:f['energy_ha'] for f in stored['fragments']}
    if set(saved)!=expected or not all(math.isclose(energies[k],saved[k],abs_tol=1e-10,rel_tol=0) for k in expected):
        raise ValueError('published fragment energies do not replay')
    for f in stored['fragments']:
        if (not math.isclose(refs[f['id']],f['reference_ha'],abs_tol=1e-10,rel_tol=0)
                or not math.isclose(abs(energies[f['id']]-refs[f['id']]),f['absolute_error_ha'],abs_tol=1e-10,rel_tol=0)):
            raise ValueError('published fragment reference/error does not replay')
    if (not math.isclose(result,stored['total_energy_ha'],abs_tol=1e-10,rel_tol=0)
            or not math.isclose(reference,stored['restricted_reference_ha'],abs_tol=1e-10,rel_tol=0)
            or not math.isclose(abs(result-reference),stored['absolute_error_ha'],abs_tol=1e-10,rel_tol=0)):
        raise ValueError('published assembled energy/reference/error does not replay')
    return {'numerical_replay_passed':True,'total_energy_ha':result,'restricted_reference_ha':reference,
            'absolute_error_ha':abs(result-reference),'provider_execution_verified':False,
            'scope':'Matrix/count point-estimate replay only. Does not authenticate private captures, original full-package digest, uncertainty coverage or hardware accuracy.'}


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('evidence',type=Path)
    args=parser.parse_args();print(json.dumps(replay(json.loads(args.evidence.read_text())),indent=2,allow_nan=False))
