#!/usr/bin/env python3
"""Recount all public A10 batching summary rows; no network or private raw replay.
Usage: python3 full-model-search-batching-recompute.py full-model-search-batching.zip
The original producer replay supplies score grades; this checks the complete
public projection, cross-file count joins, training summaries and both orders.
"""
import csv,hashlib,io,json,sys,zipfile
from pathlib import Path
SHA='907f1c350be269c32b6f592b59329507d5d0d0346df3130cff64a849702ab19e'
ARMS=['compiled:yield-poll','compiled:bounded-poll','compiled:driver-wait','native:yield-poll','native:bounded-poll','native:driver-wait','compiled:bounded-poll:expire','compiled:batch-1','compiled:batch-2','compiled:batch-4','native:batch-1','native:batch-2','native:batch-4']

def recount(path):
    raw=Path(path).read_bytes()
    if len(raw)!=39809 or hashlib.sha256(raw).hexdigest()!=SHA:raise ValueError('Original public package differs')
    with zipfile.ZipFile(io.BytesIO(raw))as z:
        if set(z.namelist())!={'README.md','batch-arrival-rates.csv','batch-result-status.json','independent-customer-summary.json','independent-selected-outcomes.json'} or len(z.infolist())!=5:raise ValueError('Original member census differs')
        selected=json.loads(z.read('independent-selected-outcomes.json'));status=json.loads(z.read('batch-result-status.json'))
        summary=json.loads(z.read('independent-customer-summary.json'));rates=list(csv.DictReader(io.StringIO(z.read('batch-arrival-rates.csv').decode())))
    if status['run']!=44675936308 or not all(status[k]is True for k in ('physical_runtime_qualified','qualified_both_orders')) or status['replay_disposition']!='replayed':raise ValueError('Original replay status')
    if selected['status']!='recount_complete'or selected['full_suite_qualified']is not True or selected['producer_replay_qualified']is not True:raise ValueError('Selected qualification')
    cells={(c['order'],c['arm']):c for c in selected['cells']}
    if len(cells)!=30 or len(selected['cells'])!=30:raise ValueError('Unique cell census')
    if set(cells)!={(o,a)for o in (0,1)for a in ['solo','arrival-observer']+ARMS}:raise ValueError('Complete original arms')
    for (o,a),c in cells.items():
        if c['producer_disposition']!='complete'or not all(c[k]is True for k in ('owner_clean','training_exact','training_time_pass','eligible')):raise ValueError('Complete training-qualified cell')
        if c['training_state_sha256']!=cells[o,'solo']['training_state_sha256']or c['training_elapsed_ns']>1.05*cells[o,'solo']['training_elapsed_ns']:raise ValueError('Original training summary')
    index={}
    fields={'offered':'planned','timely':'within_1ms','eventual':'correct','incorrect':'incorrect','within_100us':'within_100us','overflow':'queue_full','expired':'intentional_expired','unfinished':'unfinished_accepted','not_released':'not_released'}
    for row in rates:
        key=int(row['order']),row['arm'],int(row['rate']);o,a,rate=key
        if key in index or a not in ARMS or rate not in (500,1000,1500,2000):raise ValueError('Rate identity')
        original=dict(cells[o,a]['per_rate'][str(rate)])
        if ':batch-' in a:
            # The batch projection uses accepted/returned rather than legacy queue
            # expiry/unfinished counters. No expiry policy exists in these arms.
            if 'intentional_expired' in original or 'unfinished_accepted' in original:raise ValueError('Unexpected batch counter schema')
            if original['accepted']<original['returned']:raise ValueError('Batch completion exceeds admissions')
            original['intentional_expired']=0
            original['unfinished_accepted']=original['accepted']-original['returned']
        for csvkey,originalkey in fields.items():
            if int(row[csvkey])!=original[originalkey]:raise ValueError('Cross-file count differs')
        if int(row['offered'])!=rate*2 or int(row['incorrect'])!=0 or row['eligible']!='True':raise ValueError('Workload or eligibility')
        if int(row['offered'])!=sum(int(row[k])for k in ('eventual','overflow','expired','unfinished','not_released')):raise ValueError('Every offer accounted')
        if float(row['elapsed_training_s'])!=cells[o,a]['training_elapsed_ns']/1e9:raise ValueError('Training denominator')
        index[key]={k:int(row[k])for k in fields}
    if len(rates)!=104 or len(index)!=104:raise ValueError('Full rate census')
    sm={(r['order'],r['arm']):r for r in summary['cells']}
    totals=[]
    for a in ARMS:
        total={k:sum(index[o,a,rate][k]for o in (0,1)for rate in (500,1000,1500,2000))for k in fields}
        for o in (0,1):
            if any(sm[o,a][k]!=sum(index[o,a,r][k]for r in (500,1000,1500,2000))for k in ('timely','eventual','incorrect')):raise ValueError('Independent aggregate differs')
        totals.append(dict(arm=a,**total))
    peak=all(index[o,'compiled:batch-4',2000]['timely']>=3200 for o in (0,1))
    original_peak=next(r for r in selected['peak_targets']if r['arm']=='compiled:batch-4')
    for row in original_peak['orders']:
        actual=index[row['order'],'compiled:batch-4',2000]
        if row['timely']!=actual['timely']or row['eventual']!=actual['eventual']or row['timely80_percent']!=(actual['timely']>=3200):raise ValueError('Registered peak target differs')
    if {r['cell']:r['status']for r in status['cells']}!={c['cell']:c['producer_disposition']for c in selected['cells']}:raise ValueError('Original cell dispositions differ')
    paired=[dict(order=o,rate=r,cap4=index[o,'compiled:batch-4',r],cap1=index[o,'compiled:batch-1',r],expiry=index[o,'compiled:bounded-poll:expire',r],fifo=index[o,'compiled:bounded-poll',r])for o in (0,1)for r in (500,1000,1500,2000)]
    return dict(run=44675936308,complete_cells=30,rate_rows=104,totals=totals,paired=paired,training_summary_passed=True,raw_scores_replayed_here=False,loss_trajectories_replayed_here=False,peak_eighty_percent_target_met=peak,scope='Public selected projection; private original preservation and raw replay are separately tracked.')

if __name__=='__main__':print(json.dumps(recount(sys.argv[1]),indent=2,sort_keys=True))
