from typing import Dict, List, Optional
import sys
import os
import asyncio
import logging

# 添加当前目录到Python路径，确保能正确导入子模块
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.append(current_dir)

try:
    # 相对导入（当作为包使用时）
    from .sub_formulas.market_bidding_c1 import MarketBiddingC1Calculator
    from .sub_formulas.heat_coefficient_c2 import HeatCoefficientC2Calculator
    from .sub_formulas.scarcity_multiplier_c3 import ScarcityMultiplierC3Calculator
    from .sub_formulas.temporal_decay_c4 import TemporalDecayC4Calculator
    from .market_data_analyzer import market_data_analyzer
except ImportError:
    # 绝对导入（当直接运行时）
    from sub_formulas.market_bidding_c1 import MarketBiddingC1Calculator
    from sub_formulas.heat_coefficient_c2 import HeatCoefficientC2Calculator
    from sub_formulas.scarcity_multiplier_c3 import ScarcityMultiplierC3Calculator
    from sub_formulas.temporal_decay_c4 import TemporalDecayC4Calculator
    from market_data_analyzer import market_data_analyzer

logger = logging.getLogger(__name__)


class MarketValueCCalculator:
    """市场估值C计算器"""
    
    def __init__(self):
        """初始化计算器"""
        self.market_bidding_calculator = MarketBiddingC1Calculator()
        self.heat_coefficient_calculator = HeatCoefficientC2Calculator()
        self.scarcity_multiplier_calculator = ScarcityMultiplierC3Calculator()
        self.temporal_decay_calculator = TemporalDecayC4Calculator()
    
    async def _get_dynamic_default_price(self, input_data: Dict) -> float:
        """
        获取动态默认价格
        
        Args:
            input_data: 输入数据字典
            
        Returns:
            float: 动态计算的默认价格（万元）
        """
        try:
            # 尝试获取近一个月的交易数据中间值
            median_price = await market_data_analyzer.get_recent_transaction_median(30)
            
            # 根据资产特征调整默认值
            scarcity_level = input_data.get('issuance_level', '限量')
            adaptive_price = market_data_analyzer.calculate_adaptive_default_value(
                asset_type=None,  # 可以从input_data中获取资产类型
                scarcity_level=scarcity_level
            )
            
            # 取两者的平均值作为最终默认值，确保既考虑历史数据又考虑资产特征
            final_default_price = (median_price + adaptive_price) / 2
            
            logger.info(f"动态默认价格计算: 历史中间值={median_price}万元, 自适应价格={adaptive_price}万元, 最终默认价格={final_default_price}万元")
            
            return final_default_price
            
        except Exception as e:
            logger.error(f"获取动态默认价格失败: {e}")
            # 出错时使用保守的固定默认值
            return 10000.0
    
    def calculate_market_value_c(self,
                                market_bidding_c1: float,
                                heat_coefficient_c2: float,
                                scarcity_multiplier_c3: float,
                                temporal_decay_c4: float) -> float:
        """
        计算市场估值C
        
        
        市场估值C = 市场竞价C1 × 热度系数C2 × 稀缺性乘数C3 × 时效性衰减C4
        
        args:
            market_bidding_c1: 市场竞价C1 (系统计算)
            heat_coefficient_c2: 热度系数C2 (系统计算)
            scarcity_multiplier_c3: 稀缺性乘数C3 (系统计算)
            temporal_decay_c4: 时效性衰减C4 (系统计算)
            
        return:
            float: 市场估值C
        """
        market_value = (market_bidding_c1 * heat_coefficient_c2 * 
                       scarcity_multiplier_c3 * temporal_decay_c4)
        
        return market_value
    
    async def calculate_complete_market_value_c(self, input_data: Dict) -> Dict:
        """
        计算完整的市场估值C，包含所有子公式
        
        args:
            input_data: 输入数据字典，包含所有必要的参数
                参数来源标记（用户填写/系统配置/API获取/系统计算）：
                - average_transaction_price: 系统计算(基于用户填写/API获取)
                - market_activity_coefficient: 系统计算(基于用户填写)
                - daily_browse_volume: API获取/系统估算
                - collection_count: API获取/系统估算
                - issuance_level: 用户填写
                - recent_market_activity: 用户填写
                - issuance_scarcity/circulation_scarcity/uniqueness_scarcity: 系统配置/系统计算（保留向后兼容）
            
        return:
            Dict: 包含所有中间计算结果和最终结果的字典
        """
        # 计算市场竞价C1
        market_bidding_c1 = self.market_bidding_calculator.calculate_market_bidding_c1(
            transaction_data={'weighted_average_price': input_data.get('weighted_average_price', 0)},
            manual_bids=input_data.get('manual_bids', []),
            expert_valuations=input_data.get('expert_valuations', [])
        )

        # 计算热度系数C2
        heat_coefficient_c2 = self.heat_coefficient_calculator.calculate_heat_coefficient_c2(
            input_data.get('daily_browse_volume', 500.0),
            input_data.get('collection_count', 50)
        )
        
        # 计算稀缺性乘数C3
        scarcity_multiplier_c3 = self.scarcity_multiplier_calculator.calculate_scarcity_multiplier_c3(
            input_data.get('issuance_level', '限量')
        )
        
        # 计算时效性衰减C4
        temporal_decay_c4 = self.temporal_decay_calculator.calculate_temporal_decay_c4(
            input_data.get('recent_market_activity', '2024-01-15')
        )
        
        # 计算市场估值C
        market_value_c = self.calculate_market_value_c(
            market_bidding_c1,
            heat_coefficient_c2,
            scarcity_multiplier_c3,
            temporal_decay_c4
        )
        
        return {
            'market_bidding_c1': market_bidding_c1,
            'heat_coefficient_c2': heat_coefficient_c2,
            'scarcity_multiplier_c3': scarcity_multiplier_c3,
            'temporal_decay_c4': temporal_decay_c4,
            'market_value_c': market_value_c
        }


# 示例使用
if __name__ == "__main__":
    # 创建计算器实例
    calculator = MarketValueCCalculator()
    
    # 示例数据
    input_data = {
        # 市场竞价C1相关参数
        'average_transaction_price': 50000.0,  # 平均交易价格
        'manual_bids': [48000.0, 50000.0, 52000.0],  # 手动收集的竞价
        'expert_valuations': [49000.0, 51000.0, 50000.0],  # 专家估值
        
        # 热度系数C2相关参数
        'daily_browse_volume': 500.0,          # 近7日日均浏览量
        'collection_count': 50,                # 收藏数
        
        # 稀缺性乘数C3相关参数
        'issuance_level': '限量',              # 资产发行等级
        
        # 时效性衰减C4相关参数
        'recent_market_activity': '2024-01-15'  # 最近市场活动时间
    }
    
    # 计算市场估值C
    result = calculator.calculate_complete_market_value_c(input_data)
    
    print("市场估值C计算结果:")
    print(f"市场竞价C1: {result['market_bidding_c1']:.2f}")
    print(f"热度系数C2: {result['heat_coefficient_c2']:.4f}")
    print(f"稀缺性乘数C3: {result['scarcity_multiplier_c3']:.4f}")
    print(f"时效性衰减C4: {result['temporal_decay_c4']:.4f}")
    print(f"市场估值C: {result['market_value_c']:.2f}")


