#!/usr/bin/env python3
"""Verify published arithmetic and aggregates; this is not native engine replay."""
import hashlib
import json
from math import isqrt
from pathlib import Path

ROOT = Path(__file__).resolve().parent

def calculate(op, value):
    if op == 'rejection':
        return value['rejection'] >= 45 and value['rejection'] + 5 >= value['positive']
    if op == 'eligibility':
        return value['complete'] == 1 and value['confidence'] >= 60
    if op == 'idf':
        n, f, scale = value['documents'], value['frequency'], value['scale']
        return 1 + ((scale - 1) * (n - f)) // n if n > 0 and f > 0 else 1
    if op == 'cosine':
        left, right = value['left'], value['right']
        assert len(left) == len(right) == 64
        n1 = isqrt(sum(x*x for x in left))
        n2 = isqrt(sum(x*x for x in right))
        dot = sum(x*y for x,y in zip(left,right))
        return min(100, dot*100//(n1*n2)) if n1 > 0 and n2 > 0 and dot > 0 else 0
    if op == 'token_hash':
        data = value['text'].encode('utf-8')
        if not data:
            return 0
        h = 5381
        for byte in data:
            h = (h*131 + byte) & 2147483647
        return h
    raise ValueError(op)

vectors = json.loads((ROOT/'test-vectors.json').read_text())['cases']
for case in vectors:
    assert calculate(case['operation'],case['input']) == case['expected'], case['id']
report = json.loads((ROOT/'evaluation-summary.json').read_text())
parts = report['evaluation']['partitions']
assert sum(pair['candidate']['total'] for pair in parts.values()) == 457
assert parts['holdout']['baseline']['domain_correct'] == 23
assert parts['holdout']['candidate']['domain_correct'] == 27
assert parts['pending']['baseline']['direct_answers'] == 23
assert parts['pending']['candidate']['direct_answers'] == 4
negative = report['evaluation']['negative_partitions']
assert negative['holdout']['baseline']['direct_answers'] == negative['holdout']['candidate']['direct_answers'] == 4
assert report['evaluation']['pending_guard']['pending_new_direct_answers'] == 0
assert report['data_preparation']['review']['accepted_questions'] + report['data_preparation']['review']['rejected_questions'] == 361
assert report['data_preparation']['positive_seed_policy']['domain_seed_representatives'] == 93
assert report['data_preparation']['rejection_partition']['training_representatives'] == 55
release = json.loads((ROOT/'release-verification.json').read_text())
assert release['verification']['post_deployment_nlg_canaries'] == {'passed':8,'total':8}
for line in (ROOT/'checksums.sha256').read_text().splitlines():
    expected, name = line.split('  ',1)
    assert hashlib.sha256((ROOT/name).read_bytes()).hexdigest() == expected, name
print(json.dumps({'synthetic_vectors_passed':len(vectors),'aggregate_consistency':'passed','checksums':'passed','private_engine_replay':False}))
