"""Reproduce one paper-only calculation. Does not estimate AI performance.
Usage: python calculation.py audit-log.csv
Standard library only; no network calls or wager execution.
"""
import csv,json,sys
from decimal import Decimal

def calculate(path):
    with open(path,encoding='utf-8-sig',newline='') as f:
        rows=list(csv.DictReader(f))
    examples=[]
    for r in rows:
        if r['row_type']!='retrospective_evidence_example':
            raise ValueError('This script accepts only labeled retrospective examples')
        if r['captured_before_race']!='false' or r['actual_bet_placed']!='false':
            raise ValueError('Example must not be relabeled as prospective or an actual bet')
        stake=Decimal(r['hypothetical_stake_usd']);base=Decimal(r['official_payoff_base_usd'])
        payoff=Decimal(r['official_win_payoff_usd'])
        if not all(x.is_finite() for x in [stake,base,payoff]) or stake<=0 or base<=0 or payoff<0:
            raise ValueError('Invalid monetary input')
        matched=(r['prediction_program_number']==r['official_winner_program_number'] and r['prediction_horse']==r['official_winner_horse'])
        gross=stake/base*payoff if matched else Decimal(0)
        net=gross-stake
        examples.append({'race':r['track']+' '+r['race_date']+' R'+r['race_number'],'historical_identity_match':matched,'hypothetical_stake_usd':str(stake),'hypothetical_gross_usd':str(gross.quantize(Decimal('.01'))),'hypothetical_net_usd':str(net.quantize(Decimal('.01'))),'hypothetical_single_wager_net_roi_percent':str((100*net/stake).quantize(Decimal('.01')))})
    return {'warning':'Historical selected example; no actual bet; no prospective AI performance estimate.','prospectively_captured_records':0,'strategy_accuracy':None,'strategy_roi':None,'examples':examples}

if __name__=='__main__':
    if len(sys.argv)!=2:raise SystemExit('Usage: python calculation.py audit-log.csv')
    print(json.dumps(calculate(sys.argv[1]),indent=2))
