"""exsdk 1.1.2 example. Requires EXSDK_TOKEN; no credentials are embedded."""
import os
import argparse
import time
from exsdk import ExApi, CtpAccount

def ctp_account():
    return CtpAccount(
        broker_id=os.environ["CTP_BROKER_ID"],
        user_id=os.environ["CTP_USER_ID"],
        password=os.environ["CTP_PASSWORD"],
        front_url=os.environ["CTP_FRONT_URL"],
        app_id=os.environ["CTP_APP_ID"],
        auth_code=os.environ["CTP_AUTH_CODE"],
    )

def wait_ready(api):
    deadline = time.time() + 60
    while api.trading_status() != "READY":
        if not api.wait_update(deadline=deadline):
            raise TimeoutError("CTP synchronization timed out")

parser = argparse.ArgumentParser(description="Explicit opt-in example: sends a REAL limit order")
parser.add_argument("--execute", action="store_true", help="Actually submit an order")
parser.add_argument("--symbol")
parser.add_argument("--price", type=float)
parser.add_argument("--volume", type=int, default=1)
parser.add_argument("--direction", choices=["BUY", "SELL"], default="BUY")
parser.add_argument("--offset", choices=["OPEN", "CLOSE"], default="OPEN")
args = parser.parse_args()
if not args.execute:
    print("No order submitted. Read the example, then opt in with --execute --symbol ... --price ...")
    raise SystemExit(0)
if not args.symbol or args.price is None:
    parser.error("--symbol and --price are required with --execute")
with ExApi(os.environ["EXSDK_TOKEN"], ctp_account()) as api:
    orders = api.watch_order()
    wait_ready(api)
    results = api.insert_order(args.symbol, args.direction, args.offset, args.volume, args.price)
    pending = set()
    for result in results:
        print(result.status, result.order_id, result.message)
        if result.status in {"SUBMITTED", "UNKNOWN"} and result.order_id:
            pending.add(result.order_id)
    # UNKNOWN must never cause an automatic resend.
    deadline = time.time() + 120
    while pending and api.wait_update(deadline=deadline):
        if api.trading_status() != "READY":
            continue
        snapshot = orders.data()
        for order_id in list(pending):
            order = snapshot.get(order_id)
            if order:
                print(order_id, order.status, order.volume_traded, order.status_msg)
                if order.status in {"FILLED", "CANCELLED", "REJECTED"}:
                    pending.remove(order_id)
    if pending:
        print("Unresolved orders:", pending, "Closing the SDK does NOT cancel them. Reconcile with your broker.")
