"""Offline historical-candle planning and reconciliation examples.
Run: python3 kalshi-history-checks.py
No network/account/order functions. Inputs are Unix SECONDS, not milliseconds.
Adjacent query windows intentionally share inclusive endpoints.
"""
from decimal import Decimal, InvalidOperation
import copy
import json


def plan_windows(start, end, interval_minutes, max_periods=5000):
    if type(start) is not int or type(end) is not int or start < 0 or end <= start:
        raise ValueError('integer second timestamps with end after start required')
    if type(interval_minutes) is not int or interval_minutes not in (1, 60, 1440):
        raise ValueError('interval must be1,60or1440minutes')
    if type(max_periods) is not int or not 1 <= max_periods <= 5000:
        raise ValueError('positive period limit at most5000required')
    span = interval_minutes * 60 * max_periods
    windows = []
    cursor = start
    while cursor < end:
        stop = min(cursor + span, end)
        windows.append((cursor, stop))
        cursor = stop
    return windows


def dollar_or_none(value):
    if value is None:
        return None
    if not isinstance(value, str):
        raise ValueError('expected decimal dollar string or null')
    try:
        result = Decimal(value)
    except InvalidOperation as error:
        raise ValueError('invalid decimal string') from error
    if not result.is_finite() or result < 0:
        raise ValueError('finite nonnegative dollar amount required')
    return result


def reconcile(pages, market_ticker, interval_minutes):
    """One declared market/interval only; synthetic pages, not full API validation.
    Returns copies so original page fixtures are preserved. Conflicting duplicates
    raise instead of silently choosing one provider observation.
    """
    if not isinstance(market_ticker, str) or not market_ticker or interval_minutes not in (1, 60, 1440):
        raise ValueError('declared market and supported interval required')
    records = {}
    for page in pages:
        if not isinstance(page, list):
            raise ValueError('page fixture must be a list')
        for row in page:
            if not isinstance(row, dict) or type(row.get('end_period_ts')) is not int or row['end_period_ts'] < 0:
                raise ValueError('integer end_period_ts required')
            if not isinstance(row.get('price'), dict) or 'close' not in row['price']:
                raise ValueError('price.close required, with null preserved')
            dollar_or_none(row['price']['close'])
            key = (market_ticker, interval_minutes, row['end_period_ts'])
            if key in records and records[key] != row:
                raise ValueError('conflicting duplicate candle')
            records[key] = copy.deepcopy(row)
    return [records[key] for key in sorted(records)]


def checks():
    start = 1789945200
    end = start + 30 * 86400
    windows = plan_windows(start, end, 1)
    assert len(windows) == 9
    assert windows[0][0] == start and windows[-1][1] == end
    assert all(b - a <= 5000 * 60 for a, b in windows)
    assert all(left[1] == right[0] for left, right in zip(windows, windows[1:]))
    assert sum(b - a for a, b in windows) == end - start
    # Independently count interval boundaries with integer range chunks.
    boundaries = list(range(0, 43200, 5000)) + [43200]
    assert [((a-start)//60, (b-start)//60) for a,b in windows] == list(zip(boundaries, boundaries[1:]))
    a = {'end_period_ts': start + 60, 'price': {'close': '0.4000'}}
    b = {'end_period_ts': start + 120, 'price': {'close': None}}
    c = {'end_period_ts': start + 180, 'price': {'close': '0.6000'}}
    pages = [[a,b],[b,c]]
    original = json.dumps(pages, sort_keys=True)
    merged = reconcile(pages, 'FICTIONAL-MARKET', 1)
    assert len(merged) == 3 and len(pages[0]) + len(pages[1]) == 4
    assert merged[1]['price']['close'] is None
    assert json.dumps(pages, sort_keys=True) == original
    assert dollar_or_none(None) is None and dollar_or_none('0.0000') == 0
    conflict = copy.deepcopy(b)
    conflict['price']['close'] = '0.5000'
    try:
        reconcile([[b],[conflict]], 'FICTIONAL-MARKET', 1)
    except ValueError:
        pass
    else:
        raise AssertionError('conflict silently overwritten')
    for value in ['NaN', 'Infinity', '-0.1', 'garbage', True, .4]:
        try:
            dollar_or_none(value)
        except ValueError:
            pass
        else:
            raise AssertionError('invalid price accepted')
    for args in [(1,1,1), (2,1,1), (0,100,5), (True,100,1), (0,100,1,5001)]:
        try:
            plan_windows(*args)
        except ValueError:
            pass
        else:
            raise AssertionError('invalid plan accepted')
    print('30-day one-minute range:', len(windows), 'bounded requests; no download performed')
    print('Four fixture rows -> three unique candles; null retained; conflicting duplicate rejected')
    print('Window continuity, span, boundary and decimal checks passed')


if __name__ == '__main__':
    checks()
