"""Read-only view of every Kalshi subaccount: cash, positions, resting orders.

WHY THIS EXISTS. The Kalshi app's Portfolio screen appears to show the PRIMARY
subaccount only, so money moved to subaccount 1 simply vanishes from it -- on
2026-08-24 a $5 transfer read as a -$4.46 portfolio loss. Anything running on a
non-primary subaccount is invisible in the app and needs a way to be seen.

The reads are subaccount-scoped by the API itself (verified 2026-08-24):
  /portfolio/subaccounts/balances   -> every subaccount
  /portfolio/positions?subaccount=N -> that subaccount only
  /portfolio/orders?subaccount=N    -> that subaccount only
and the DEFAULT for positions/orders is subaccount 0, byte-identical to passing
subaccount=0 -- which is why existing code needed no changes when subaccount 1
was created.

Usage:  python main\\check_subaccounts.py
"""
import sys

sys.path.insert(0, r'E:\soccer\main')
import kalshi_trader as kt


def _f(x, default=0.0):
    try:
        return float(x)
    except (TypeError, ValueError):
        return default


def main():
    try:
        bals = kt._get('/portfolio/subaccounts/balances').get(
            'subaccount_balances', []) or []
    except Exception as e:
        print(f'could not read subaccount balances: {type(e).__name__}: {e}')
        return 1

    grand_cash = 0.0
    for b in sorted(bals, key=lambda x: x.get('subaccount_number', 0)):
        n = b.get('subaccount_number', 0)
        cash = _f(b.get('balance'))
        grand_cash += cash
        label = 'primary' if n == 0 else f'subaccount {n}'
        print(f'\n=== {label} (#{n}) ===')
        print(f'  cash            ${cash:,.2f}')

        try:
            mp = (kt._get('/portfolio/positions', params={'subaccount': n})
                  .get('market_positions') or [])
        except Exception as e:
            print(f'  positions       unreadable: {type(e).__name__}')
            mp = []
        open_pos = [p for p in mp if _f(p.get('position_fp')) != 0]
        print(f'  open positions  {len(open_pos)}')
        for p in open_pos:
            q = _f(p.get('position_fp'))
            # long = bought (xlow shape); short = sold (maker shape)
            kind = 'long ' if q > 0 else 'short'
            print(f'     {kind} {abs(q):>6.2f}  {p.get("ticker","")}')

        try:
            orders = (kt._get('/portfolio/orders',
                              params={'status': 'resting', 'limit': 200,
                                      'subaccount': n}).get('orders') or [])
        except Exception as e:
            print(f'  resting orders  unreadable: {type(e).__name__}')
            orders = []
        buys = [o for o in orders if str(o.get('action')) == 'buy']
        sells = [o for o in orders if str(o.get('action')) == 'sell']
        print(f'  resting orders  {len(orders)}  ({len(buys)} buy, {len(sells)} sell)')

    print()
    print(f'TOTAL CASH ACROSS SUBACCOUNTS  ${grand_cash:,.2f}')
    print('(the app shows subaccount 0 only -- anything above is invisible there)')
    return 0


if __name__ == '__main__':
    sys.exit(main())
