import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from typing import List, Dict, Any
from utils.position_manager import HedgePositionManager
from utils.loader import get_config_loader

# 获取配置加载器
_config = get_config_loader()

def symbol_exposure_check(symbols: List[str], position_manager: HedgePositionManager) -> bool:
    """
    检查 symbol 的敞口是否正常
    如果检查 symbol 的仓位发生了较大敞口，则应该将 symbol 加到 result 中返回
    """
    result = {'exposure': list()}
    if not symbols or len(symbols) <= 0:
        return result
    
    for symbol in symbols:
        pos_0, pos_1 = position_manager.get_hedge_positions(symbol)
        pos_0_size = pos_0.amount
        pos_1_size = pos_1.amount

        pos_size_delta = abs(pos_0_size - pos_1_size)
        threshold = _config.get_global_config()['abnormal_position_exposure_threshold']

        if pos_size_delta / pos_1_size > threshold:
            result['exposure'].append(symbol)
        
    return result

def symbol_notional_exposure_check(symbols: List[str], bbo: List[Dict[str, Any]], position_manager: HedgePositionManager) -> bool:
    """
    检查 symbol 的名义市值敞口是否正常
    如果检查 symbol 的仓位发生了较大敞口，则应该将 symbol 加到 result 中返回
    """
    result = {'exposure': list()}
    if not symbols or not position_manager:
        return result
    
    for symbol in symbols:
        pos_0, pos_1 = position_manager.get_hedge_positions(symbol)
        taker_notional = pos_0.amount * (bbo[0][symbol]['ask_price'] + bbo[0][symbol]['bid_price']) * 0.5
        maker_notional = pos_1.amount * (bbo[1][symbol]['ask_price'] + bbo[1][symbol]['bid_price']) * 0.5
        threshold = _config.get_global_config()['abnormal_position_exposure_threshold']

        if taker_notional / maker_notional - 1 > threshold or maker_notional / taker_notional - 1 > threshold:
            result['exposure'].append(symbol)
    
    return result
    

def symbol_single_leg_check(symbols: List[str], position_manager: HedgePositionManager) -> bool:
    """
    检查 symbol 的单腿是否正常
    如果检查 symbol 发生了单腿，则应该将该 symbol 加到 result 中返回
    """
    result = {'single_leg': list()}
    if not symbols or len(symbols) <= 0:
        return result

    for symbol in symbols:
        pos_0, pos_1 = position_manager.get_hedge_positions(symbol)
        pos_0_size = pos_0.amount
        pos_1_size = pos_1.amount

        if pos_0_size == 0 or pos_1_size == 0:
            result['single_leg'].append(symbol)
    
    return result