"""The portfolio listing must return EVERYTHING, not the first page.

On 2026-08-15 the live maker posted 81 then 111 duplicate orders. Root cause:
/portfolio/orders is cursor-paginated and get_open_orders() made a single call,
so with 111 orders resting it reported 55. The duplicate guard compared against
that halved number and could not fire; neither could the "too many resting"
abort, because the count it checked was also half.

Two things fixed it: following the cursor, and asking for 200 per page. The
second one MASKS the first at current caps -- MAX_CONCURRENT_ORDERS is 60, so a
real run never exceeds one page and the cursor code is never exercised. This
test forces a tiny page size so the cursor path actually runs, and checks the
paginated result against the single-page truth.

Read-only. Places nothing, cancels nothing.
"""
import sys
sys.path.insert(0, r'E:\soccer\main')
import kalshi_trader as kt
import kalshi_maker as km

fails = []


def check(label, cond, extra=''):
    print(f'  [{"pass" if cond else "FAIL"}] {label}{("  " + extra) if extra else ""}')
    if not cond:
        fails.append(label)


for path, key, params in (
        ('/portfolio/orders', 'orders', {'status': 'resting'}),
        ('/portfolio/positions', 'market_positions', {}),
        ('/portfolio/fills', 'fills', {})):
    name = path.rsplit('/', 1)[-1]
    print(f'=== {name} ===')
    truth = kt._get_all(path, key, dict(params, limit=500))
    t_items = truth[key]
    if not t_items:
        print(f'  (nothing to page through -- {name} is empty, skipped)')
        continue

    def ident(o):
        for k in ('order_id', 'fill_id', 'ticker'):
            if o.get(k):
                return o[k]
        return repr(sorted(o.items()))

    t_ids = {ident(o) for o in t_items}
    paged = kt._get_all(path, key, dict(params, limit=7))
    p_items = paged[key]
    p_ids = {ident(o) for o in p_items}

    if len(t_items) <= 7:
        print(f'  (only {len(t_items)} items -- cannot force a second page, '
              f'boundary checks skipped)')
        continue

    check(f'{name}: cursor path actually ran', paged['pages'] > 1,
          f'{paged["pages"]} pages at limit=7 for {len(t_items)} items')
    # NO cross-fetch equality assert. The portfolio mutates while we page --
    # orders fill and cancel between the two calls -- so demanding the sets
    # match is testing the market, not the cursor. It failed exactly that way
    # first time round: 53 vs 54, because one order filled mid-test. What must
    # hold is that a single paginated walk is internally sound and covers
    # essentially the same ground.
    check(f'{name}: no item returned twice in one walk',
          len(p_items) == len(p_ids),
          f'{len(p_items) - len(p_ids)} raw dupes, {paged.get("deduped", 0)} '
          f'removed by _get_all')
    overlap = len(t_ids & p_ids)
    ref = max(1, min(len(t_ids), len(p_ids)))
    check(f'{name}: paginated walk covers the same population',
          overlap >= ref * 0.95,
          f'{overlap}/{ref} shared ({len(t_ids ^ p_ids)} differ -- live churn)')

print('\n=== the cap that currently hides all this ===')
print(f'  MAX_CONCURRENT_ORDERS = {km.MAX_CONCURRENT_ORDERS}, per-page limit = 200')
check('order cap stays below the page size, so a real run cannot truncate',
      km.MAX_CONCURRENT_ORDERS < 200,
      'raise the cap above 200 and the cursor path becomes load-bearing')

print('\n' + ('ALL PASSED' if not fails else f'FAILURES: {fails}'))
sys.exit(1 if fails else 0)
