"""Generate synthetic cash-out accounting examples, using exact decimal arithmetic.

Python 3.11+, standard library only. Run in any folder; outputs go beside this file.
No network, app data, hand evaluation or randomness is used.
"""
import csv
import json
from decimal import Decimal as D, ROUND_HALF_UP
from pathlib import Path

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


def fixed(value, places=4):
    return format(value.quantize(D(1).scaleb(-places)), 'f')


def quote(value):
    return format(value.quantize(D('.01'), rounding=ROUND_HALF_UP), '.2f')


def write_csv(name, rows):
    with (ROOT / name).open('w', newline='', encoding='utf-8') as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator='\n')
        writer.writeheader()
        writer.writerows(rows)


def main():
    rows = []
    for equity in ['.2', '.5', '.8']:
        for fee in ['.01', '.02', '.05']:
            e, f = D(equity), D(fee)
            value = D(100) * e
            rows.append(dict(id=f'e{int(e*100)}-f{int(f*100)}', gross_pot='104.00', rake='4.00',
                             win_probability=fixed(e), tie_probability='0.0000', equity=fixed(e),
                             fee_rate=fixed(f), hand_value=quote(value), fee=quote(value*f),
                             quote=quote(value*(1-f))))
    rows.append(dict(id='tie-share', gross_pot='104.00', rake='4.00', win_probability='0.4000',
                     tie_probability='0.2000', equity='0.5000', fee_rate='0.0200',
                     hand_value='50.00', fee='1.00', quote='49.00'))
    rounding = []
    for e in map(D, ['.5951', '.6000', '.6049']):
        raw = D(100) * e * D('.98')
        displayed = (e*100).quantize(D(1), rounding=ROUND_HALF_UP)
        shown_quote = D(quote(raw))
        naive = (1-shown_quote/displayed)*100
        rounding.append(dict(equity=fixed(e), displayed_equity_percent=str(displayed),
                             fee_rate='0.0200', raw_quote=fixed(raw), quote=quote(raw),
                             inferred_fee_percent=fixed(naive, 2)))
    write_csv('scenarios.csv', rows)
    write_csv('rounding.csv', rounding)
    result = dict(method='Synthetic single-pot heads-up award accounting; ties split equally.',
                  currency='USD for examples only', rounding='Nearest cent, half up; worksheet convention only.',
                  samples=10, rounding_examples=3, seed=None, scenarios=rows, precision_examples=rounding)
    (ROOT / 'results.json').write_text(json.dumps(result, indent=2, ensure_ascii=False)+'\n', encoding='utf-8', newline='\n')
    print('Generated 10 exact accounting rows and 3 rounded-input examples.')


if __name__ == '__main__':
    main()
