"""Connect directly to a CTP broker from localhost and monitor funds, positions, and orders.

Read-only example: does not submit or cancel any orders.

Usage:
    export EXSDK_TOKEN="YOUR_TOKEN"
    export CTP_BROKER_ID="9999"
    export CTP_USER_ID="your_user_id"
    export CTP_PASSWORD="your_password"
    export CTP_FRONT_URL="tcp://host:port"
    export CTP_APP_ID="your_app_id"
    export CTP_AUTH_CODE="your_auth_code"
    python monitor_ctp_account.py
"""

import os
import time
from exsdk import CtpAccount, ExApi


def format_amount(value: float | None) -> str:
    return f"{value:,.2f}" if value is not None else "--"


def print_snapshot(funds_watch, positions_watch, orders_watch) -> None:
    account = funds_watch.data()
    print(
        f"[资金] 权益={format_amount(account.balance)} | "
        f"可用={format_amount(account.available)} | "
        f"保证金={format_amount(account.margin)} | "
        f"持仓盈亏={format_amount(account.position_profit)} | "
        f"平仓盈亏={format_amount(account.close_profit)}"
    )

    active_positions = [
        pos
        for pos in positions_watch.data().values()
        if (pos.pos_long or 0) > 0 or (pos.pos_short or 0) > 0
    ]
    if not active_positions:
        print("[持仓] 当前无持仓")
    else:
        for pos in active_positions:
            print(
                f"[持仓] {pos.symbol} 多={pos.pos_long or 0}(可平 {pos.available_long or 0}) "
                f"空={pos.pos_short or 0}(可平 {pos.available_short or 0})"
            )

    order_map = orders_watch.data()
    print(f"[委托] 当日记录共 {len(order_map)} 笔")
    for order_id, order in order_map.items():
        print(
            f"  - {order_id} {order.symbol} {order.direction} {order.offset} "
            f"价={order.limit_price} 成交={order.volume_traded}/{order.volume_original} 状态={order.status}"
        )


def main() -> None:
    account = 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"],
    )

    with ExApi(token=os.environ["EXSDK_TOKEN"], account=account) as api:
        funds = api.watch_account()
        positions = api.watch_position()
        orders = api.watch_order()

        print("正在直连 CTP 柜台并同步账户数据...")
        while api.trading_status() != "READY":
            api.wait_update()
            if api.trading_status() == "ERROR":
                raise RuntimeError("CTP trading connection entered ERROR state")

        print("CTP 账户已就绪，按 Ctrl+C 停止监控。")
        print_snapshot(funds, positions, orders)

        while True:
            if not api.wait_update(deadline=time.time() + 10):
                continue
            if api.trading_status() != "READY":
                print(f"[状态] 当前交易状态: {api.trading_status()}")
                continue
            if (
                funds.is_changing("updated_at")
                or positions.is_changing()
                or orders.is_changing()
            ):
                print_snapshot(funds, positions, orders)


if __name__ == "__main__":
    main()
