"""Three hypothetical settlement replays on the existing synthetic CSV.

No observed device delays or casino transactions. One unit per round, initial
balance10,000 units, target reached at equality, no fees. Standard library only.
Usage: python cashout_models.py [dataset.csv]
"""
import argparse
import csv
from decimal import Decimal
import hashlib
import json
import logging
from pathlib import Path


def replay(path):
    expected = '0f3341c5dc53667e4e7b36c80998461ad0d215ce8608dded2d72c27d9bf7ab10'
    if hashlib.sha256(path.read_bytes()).hexdigest() != expected:
        raise ValueError('File differs from the documented synthetic corpus')
    with path.open(encoding='utf-8', newline='') as stream:
        rounds = list(csv.DictReader(stream))
    output = []
    for name, threshold, payout_cents in [
        ('target2_paid2', Decimal('2.00'), 200),
        ('arrival2.1_paid2', Decimal('2.10'), 200),
        ('arrival2.1_paid2.1', Decimal('2.10'), 210),
    ]:
        balance = 1000000
        wins = gross = 0
        for row in rounds:
            if balance < 100:
                raise ValueError('Next one-unit stake cannot be funded')
            won = Decimal(row['multiplier']) >= threshold
            paid = payout_cents if won else 0
            balance += paid - 100
            gross += paid
            wins += won
        turnover = len(rounds) * 100
        assert balance == 1000000 + gross - turnover
        output.append(dict(model=name, rounds=len(rounds), wins=wins,
                           turnoverCents=turnover, grossCents=gross,
                           netCents=gross-turnover, finalBalanceCents=balance))
    return dict(scope='One synthetic path, not a live latency experiment',
                datasetSha256=expected, startingBalanceCents=1000000, results=output)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('dataset', nargs='?', type=Path,
                        default=Path(__file__).with_name('crashmath_10000_rounds_dataset.csv'))
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logging.info(json.dumps(replay(parser.parse_args().dataset), indent=2))
