"""Сборка raw.csv, raw_buy.csv и summary.json из events*.jsonl. Числа на сайт идут только из summary.json.
Раунд = платный doSpin (баланс упал) и все ответы до следующего платного. Выигрыш = баланс после раунда минус баланс после списания.
Сверка: выигрыш по балансу должен совпасть с tw финального ответа (na=c). Неполный последний раунд исключается и считается."""
import json, csv, sys, glob, statistics, pathlib, datetime
D = pathlib.Path(__file__).resolve().parent
BASE_BET = 0.20
num = lambda s: float(s.replace(',', '')) if s else None
iso = lambda ts: datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')

def rounds_from(files, mode, run_prefix):
    out, bad, incomplete = [], [], 0
    for fi, fn in enumerate(sorted(files)):
        ev = [e for e in (json.loads(l) for l in open(fn)) if 'action' in e]
        run_id = f'{run_prefix}{chr(97+fi)}' if len(files) > 1 else run_prefix
        prev_bal = None; cur = None; rs = []
        for e in ev:
            bal = num(e['balance'])
            if e['paid']:
                if cur: rs.append(cur)
                cur = {'start_prev': prev_bal, 'start_bal': bal, 'events': [e], 'ts': e['ts']}
            elif cur: cur['events'].append(e)
            if bal is not None: prev_bal = bal
        if cur: rs.append(cur)
        for k, r in enumerate(rs, 1):
            last = r['events'][-1]
            done = last['action'] == 'doCollect' or (len(r['events']) == 1 and last['na'] == 's' and (num(last['tw'] or '0') == 0) and last['fs'] is None)
            if not done:
                if k == len(rs): incomplete += 1; continue
                bad.append((run_id, k, 'не завершён, но не последний')); continue
            end_bal = num(last['balance'])
            win = round(end_bal - r['start_bal'], 2)
            cost = round(r['start_prev'] - r['start_bal'], 2)
            finals = [num(x['tw']) for x in r['events'] if x['na'] == 'c' and x['tw'] is not None]
            tw = finals[-1] if finals else 0.0
            if abs(tw - win) > 0.005: bad.append((run_id, k, f'win {win} != tw {tw}'))
            out.append({'run_id': run_id, 'round_no': k, 'timestamp_utc': iso(r['ts']), 'mode': mode, 'bet': cost, 'total_win': win,
                        'multiplier': round(win / BASE_BET, 2), 'free_spins_triggered': int(any(x['fs'] is not None for x in r['events'])),
                        'steps': len(r['events']), 'balance_after': end_bal, 'req_c': r['events'][0]['req_c']})
    return out, bad, incomplete

def write(rows, name):
    keys = ['run_id', 'round_no', 'timestamp_utc', 'mode', 'bet', 'total_win', 'multiplier', 'free_spins_triggered', 'steps', 'balance_after']
    with open(D / name, 'w', newline='') as f:
        w = csv.writer(f); w.writerow(keys)
        for r in rows: w.writerow([r[k] for k in keys])

base, bad_b, inc_b = rounds_from(glob.glob(str(D / 'events.jsonl')), 'base', 'base')
buy, bad_u, inc_u = rounds_from(glob.glob(str(D / 'events_buy_*.jsonl')), 'buy_free_spins', 'buy')
write(base, 'raw.csv'); write(buy, 'raw_buy.csv')

BUCKETS = [(0, 0, '0x (no win)'), (0.0001, 1, 'under 1x'), (1, 2, '1x to under 2x'), (2, 5, '2x to under 5x'), (5, 20, '5x to under 20x'), (20, 100, '20x to under 100x'), (100, 1e18, '100x and above')]
def buckets(vals):
    res = []
    for lo, hi, name in BUCKETS:
        n = sum(1 for v in vals if (v == 0 if hi == 0 else lo <= v < hi))
        res.append({'bucket': name, 'rounds': n, 'share': round(100 * n / len(vals), 1) if vals else None})
    return res

PRICE_BUCKETS = [(0, 0.5, 'under 0.5x the price'), (0.5, 1, '0.5x to under 1x the price'), (1, 2, '1x to under 2x the price'), (2, 5, '2x to under 5x the price'), (5, 1e18, '5x the price and above')]
def price_buckets(vals, price):
    res = []
    for lo, hi, name in PRICE_BUCKETS:
        n = sum(1 for v in vals if lo * price <= v < hi * price)
        res.append({'bucket': name, 'rounds': n, 'share': round(100 * n / len(vals), 1) if vals else None})
    return res

def summ(rows, price_mult):
    m = [r['multiplier'] for r in rows]
    return {'rounds': len(rows), 'no_win_rounds': sum(1 for v in m if v == 0), 'fs_rounds': sum(r['free_spins_triggered'] for r in rows),
            'max_x_base_bet': max(m) if m else None, 'median_x_base_bet': statistics.median(m) if m else None,
            'buckets': buckets(m), 'bet_values': sorted({r['bet'] for r in rows}), 'req_c': sorted({r['req_c'] for r in rows}),
            'first_ts': rows[0]['timestamp_utc'] if rows else None, 'last_ts': rows[-1]['timestamp_utc'] if rows else None,
            **({'purchase_price_x_base_bet': price_mult, 'below_price_rounds': sum(1 for v in m if v < price_mult),
                'median_x_price': round(statistics.median(m) / price_mult, 2) if m else None, 'max_x_price': round(max(m) / price_mult, 2) if m else None,
                'price_buckets': price_buckets(m, price_mult)} if price_mult else {})}
out = {'checked_at': '2026-11-02', 'base_bet_eur': BASE_BET, 'base': summ(base, None), 'buy': summ(buy, 100) if buy else None,
       'excluded_incomplete': {'base': inc_b, 'buy': inc_u}, 'balance_check_failures': bad_b + bad_u}
(D / 'summary.json').write_text(json.dumps(out, indent=1))
if not (bad_b or bad_u) and base:   # данные для страницы: только если сверка баланса чистая
    (D.parents[3] / 'content' / 'data' / 'test-log.json').write_text(json.dumps(out, indent=1))
print(json.dumps({k: (v if k not in ('base', 'buy') else {kk: vv for kk, vv in (v or {}).items() if kk != 'buckets'}) for k, v in out.items()}, indent=1))
