"""
账户信息查询相关的API端点。

包括余额、持仓、当日成交、当日委托和单个订单查询。
"""
from flask import Blueprint, jsonify, abort

from core.app_state import get_trader, is_real_mode, logger

account_bp = Blueprint('account_routes', __name__, url_prefix='/yu')

def _check_trader_availability():
    """辅助函数，检查交易实例是否可用，如果不可用则 abort(503)。"""
    trader = get_trader()
    if not trader:
        logger.error("Trader instance not available for account request.")
        abort(503, description="Trader not available. System may be initializing or in a failed state.")
    
    if is_real_mode() and not trader.is_available():
        logger.warning(f"Account info request when trader is not available: {trader.connection_error_message}")
        abort(503, description=trader.connection_error_message or "交易系统连接失败，请稍后再试")
    return trader

@account_bp.route("/balance", methods=["GET"])
def get_balance_route(): # Renamed to avoid conflict with get_balance from app_state if imported directly
    """获取账户余额信息。"""
    logger.info("Received balance request")
    try:
        trader = _check_trader_availability()
        balance = trader.get_balance()
        return jsonify(balance), 200
    except Exception as e:
        logger.error(f"Error processing balance request: {str(e)}", exc_info=True)
        abort(500, description="Internal server error during balance request")

@account_bp.route("/positions", methods=["GET"])
def get_positions_route(): # Renamed
    """获取账户持仓信息。"""
    logger.info("Received positions request")
    try:
        trader = _check_trader_availability()
        positions = trader.get_positions()
        return jsonify(positions), 200
    except Exception as e:
        logger.error(f"Error processing positions request: {str(e)}", exc_info=True)
        abort(500, description="Internal server error during positions request")

@account_bp.route("/todaytrades", methods=["GET"])
def get_today_trades_route(): # Renamed
    """获取当日成交信息。"""
    logger.info("Received today trades request")
    try:
        trader = _check_trader_availability()
        trades = trader.get_today_trades()
        return jsonify(trades), 200
    except Exception as e:
        logger.error(f"Error processing today trades request: {str(e)}", exc_info=True)
        abort(500, description="Internal server error during today trades request")

@account_bp.route("/todayorders", methods=["GET"])
def get_today_orders_route(): # Renamed
    """获取当日委托信息。"""
    logger.info("Received today orders request")
    try:
        trader = _check_trader_availability()
        orders = trader.get_today_orders()
        return jsonify(orders), 200
    except Exception as e:
        logger.error(f"Error processing today orders request: {str(e)}", exc_info=True)
        abort(500, description="Internal server error during today orders request")

@account_bp.route("/order/<order_id>", methods=["GET"])
def get_order_route(order_id: str): # Renamed
    """根据订单ID获取订单信息。"""
    logger.info(f"Received order request for order {order_id}")
    try:
        trader = _check_trader_availability()
        order_info = trader.get_order(order_id)
        if order_info is None or (isinstance(order_info, dict) and not order_info): # Handle case where order not found
            logger.warning(f"Order not found for ID: {order_id}")
            abort(404, description=f"Order with ID {order_id} not found.")
        return jsonify(order_info), 200
    except Exception as e:
        logger.error(f"Error processing order request for {order_id}: {str(e)}", exc_info=True)
        abort(500, description=f"Internal server error during order request for {order_id}") 