"""ONE-OFF CAPABILITY PROBE: does Polymarket US accept a resting SELL order?

WHY THIS EXISTS. The three-leg maker strategy means SELLING all three outcomes.
Our Poly-US client has only ever sent ORDER_INTENT_BUY_LONG, so whether the venue
accepts a resting sell is untested -- and it is the last unknown blocking a
Poly-US version of the market maker. Everything else already checks out:

  - three outcome markets per event, each with a real two-sided book
    (Fluminense v Bahia: 0.53/0.54, 0.25/0.27, 0.19/0.21 -- 102c of asks)
  - ORDER_TYPE_LIMIT with a time-in-force, so orders can rest
  - MAKER REBATE of 0.0125*C*p*(1-p) CREDITED to the maker (docs.polymarket.us/fees,
    effective 2026-07-01) versus Kalshi's maker fee of exactly zero. Worth
    +0.76c/contract on the book above, and it drops the break-even gross from
    +2.38c (Kalshi) to +1.42c -- which makes ordinary 2c books profitable
  - taker fee 0.06*p*(1-p), cheaper than Kalshi's 0.07, for forced completions
  - book depth of 7-20 contracts versus Kalshi's 1,749-44,427, so a resting
    order is near the FRONT of the queue instead of behind a wall

WHY IT IS SAFE. Sells YES at 0.98 on a leg trading at ~0.21. Nobody pays 98c for
something worth 21c, so it cannot fill. Even if it somehow did, selling at 0.98
collects 98c against a maximum 100c liability -- max loss 2 CENTS on 1 contract.
The order is cancelled about two seconds later, and the script aborts before
sending anything if the book has moved somewhere unexpected.

This is a DELIBERATE one-off exception to the paper-only rule (both venues have
AUTO_TRADE_ENABLED=False since 2026-07-25). It is a capability probe, not a
trade: no directional view, no edge sought, cancelled immediately.

Run:  python research\\polyus_sell_probe.py
"""
import json
import sys
import time

sys.path.insert(0, r'E:\soccer\main')
import poly_us_prices as P
import poly_us_trader as T

SLUG = 'atc-bra-flu-bah-2026-07-29-bah'   # Bahia leg, trading ~0.21
SELL_PRICE = 0.98
QTY = 1


def main():
    b = P.get_bbo(SLUG)
    if not b or not b.get('bestAsk'):
        print(f'no book for {SLUG} -- market may have closed. Aborting.')
        return 1
    print(f'book: bid {b["bestBid"]} / ask {b["bestAsk"]}  '
          f'(depth {b["bidDepth"]}/{b["askDepth"]})')

    # Abort unless our sell price is far above anything anyone would pay.
    if b['bestAsk'] > 0.60:
        print(f'ask {b["bestAsk"]} unexpectedly high vs sell price {SELL_PRICE} '
              f'-- refusing to send. Aborting.')
        return 1

    print(f'\nplacing SELL_SHORT {QTY} @ {SELL_PRICE} '
          f'(cannot fill; max loss ${QTY*(1-SELL_PRICE):.2f} if it somehow did)')
    try:
        r = T.place_limit_order(SLUG, SELL_PRICE, QTY,
                                intent='ORDER_INTENT_SELL_SHORT')
    except Exception as e:
        print(f'\nREJECTED: {type(e).__name__}: {str(e)[:600]}')
        print('\n=> Poly-US does NOT accept this sell form. The maker strategy '
              'would need the buy-the-other-side construction instead.')
        return 0

    print('\nACCEPTED:', json.dumps(r)[:500])
    oid = r.get('id') or (r.get('order') or {}).get('id')
    print('order id:', oid)

    if not oid:
        print('\n!! no order id in response -- CANCEL MANUALLY in the UI')
        return 1

    time.sleep(2)
    try:
        c = T.cancel_order(oid, SLUG)
        print('CANCELLED:', json.dumps(c)[:300])
    except Exception as e:
        print(f'!! CANCEL FAILED: {e}\n!! CANCEL {oid} MANUALLY IN THE UI')
        return 1

    print('\n=> Poly-US accepts resting sells. A Poly-US market maker is viable, '
          'and on current numbers looks better than Kalshi on every measured axis.')
    return 0


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