"""
重要提醒服务模块

提供动态的重要提醒信息生成功能，包括：
1. 行业拥挤度风险提醒
2. 行业持仓占比风险提醒
3. 个股持仓风险提醒
4. 融资融券风险提醒
5. 市场恐贪指数风险提醒
"""

import logging
import requests
from typing import Dict, List, Optional
from datetime import datetime

from .portfolio_analyzer import PortfolioAnalyzer
from .industry_analysis import IndustryAnalyzer
from .eastmoney_rzrq_collector import EastmoneyRzrqCollector
from .fear_greed_index import FearGreedIndexManager

# 配置日志
logger = logging.getLogger("notice_service")


class NoticeService:
    """重要提醒服务类"""

    def __init__(self):
        """初始化提醒服务"""
        self.portfolio_analyzer = PortfolioAnalyzer()
        self.industry_analyzer = IndustryAnalyzer()
        self.rzrq_collector = EastmoneyRzrqCollector()
        self.fear_greed_manager = FearGreedIndexManager()
        logger.info("重要提醒服务初始化完成")

    def get_dynamic_notices(self) -> Dict:
        """
        获取动态的重要提醒列表
        
        Returns:
            包含提醒信息的字典
        """
        try:
            notices = []
            
            # 1. 检查行业拥挤度风险
            crowding_notices = self._check_industry_crowding_risk()
            notices.extend(crowding_notices)
            
            # 2. 检查行业持仓占比风险
            allocation_notices = self._check_industry_allocation_risk()
            notices.extend(allocation_notices)
            
            # 3. 检查个股持仓风险
            stock_notices = self._check_stock_holding_risk()
            notices.extend(stock_notices)
            
            # 4. 检查融资融券风险
            rzrq_notices = self._check_rzrq_risk()
            notices.extend(rzrq_notices)
            
            # 5. 检查市场恐贪指数风险
            fear_greed_notices = self._check_fear_greed_risk()
            notices.extend(fear_greed_notices)
            
            # 如果没有风险提醒，添加一些市场信息
            if not notices:
                notices = self._get_market_info_notices()
            
            return {
                "success": True,
                "data": notices
            }
            
        except Exception as e:
            logger.error(f"获取动态提醒失败: {e}")
            return {
                "success": False,
                "message": f"获取动态提醒失败: {str(e)}",
                "data": []
            }

    def _check_industry_crowding_risk(self) -> List[str]:
        """
        检查行业拥挤度风险
        
        Returns:
            拥挤度风险提醒列表
        """
        notices = []
        
        try:
            # 获取持仓行业数据
            portfolio_result = self.portfolio_analyzer.analyze_portfolio_allocation()
            if not portfolio_result.get("success"):
                return notices
            
            industries = portfolio_result["data"]["industries"]
            
            # 检查每个持仓行业的拥挤度
            for industry_data in industries:
                industry_name = industry_data["industry"]
                
                # 获取行业拥挤度数据
                crowding_result = self.industry_analyzer.get_industry_analysis(
                    industry_name, "pe", None
                )
                
                if crowding_result.get("success") and "crowding" in crowding_result:
                    crowding_data = crowding_result["crowding"]
                    current_percentile = crowding_data["current"]["percentile"]
                    
                    if current_percentile >= 80:
                        notices.append(f"⚠️ {industry_name}拥挤度过高({current_percentile:.1f}%)，建议减仓")
                    elif current_percentile <= 20:
                        notices.append(f"💰 {industry_name}拥挤度较低({current_percentile:.1f}%)，可考虑加仓")
                        
        except Exception as e:
            logger.error(f"检查行业拥挤度风险失败: {e}")
        
        return notices

    def _check_industry_allocation_risk(self) -> List[str]:
        """
        检查行业持仓占比风险
        
        Returns:
            行业持仓占比风险提醒列表
        """
        notices = []
        
        try:
            # 获取持仓行业数据
            portfolio_result = self.portfolio_analyzer.analyze_portfolio_allocation()
            if not portfolio_result.get("success"):
                return notices
            
            industries = portfolio_result["data"]["industries"]
            total_amount = portfolio_result["data"]["total_amount"]
            
            # 检查行业持仓占比
            for industry_data in industries:
                industry_name = industry_data["industry"]
                industry_amount = industry_data["amount"]
                industry_ratio = (industry_amount / total_amount) * 100
                
                if industry_ratio > 50:
                    notices.append(f"⚠️ {industry_name}持仓占比过高({industry_ratio:.1f}%)，建议分散风险")
                    
        except Exception as e:
            logger.error(f"检查行业持仓占比风险失败: {e}")
        
        return notices

    def _check_stock_holding_risk(self) -> List[str]:
        """
        检查个股持仓风险
        
        Returns:
            个股持仓风险提醒列表
        """
        notices = []
        
        try:
            # 获取持仓摘要数据
            summary_result = self.portfolio_analyzer.get_portfolio_summary()
            if not summary_result.get("success"):
                return notices
            
            project_details = summary_result["data"]["project_details"]
            
            # 检查个股保证金金额
            for project in project_details:
                project_name = project["project_name"]
                margin_amount = project["margin_amount"]
                
                if margin_amount > 2000000:  # 200万
                    notices.append(f"⚠️ {project_name}保证金过高({margin_amount/10000:.1f}万)，建议控制仓位")
                    
        except Exception as e:
            logger.error(f"检查个股持仓风险失败: {e}")
        
        return notices

    def _check_rzrq_risk(self) -> List[str]:
        """
        检查融资融券风险
        
        Returns:
            融资融券风险提醒列表
        """
        notices = []
        
        try:
            # 获取融资融券数据
            rzrq_result = self.rzrq_collector.get_chart_data(limit_days=90)
            if not rzrq_result.get("success"):
                return notices
            
            # 计算当前值在历史数据中的百分位
            series_data = rzrq_result["series"]
            if not series_data:
                return notices
            
            main_series = series_data[0]  # 融资融券余额合计
            data_values = main_series["data"]
            
            # 过滤有效数据
            valid_data = [v for v in data_values if v is not None and v != 0]
            if not valid_data:
                return notices
            
            current_value = data_values[-1]
            sorted_data = sorted(valid_data)
            current_index = next((i for i, v in enumerate(sorted_data) if v >= current_value), len(sorted_data))
            percentile = (current_index / len(sorted_data)) * 100
            
            if percentile >= 80:
                notices.append(f"⚠️ 融资融券余额处于高位({percentile:.1f}%)，市场情绪过热")
            elif percentile <= 20:
                notices.append(f"💰 融资融券余额处于低位({percentile:.1f}%)，市场情绪低迷")
                
        except Exception as e:
            logger.error(f"检查融资融券风险失败: {e}")
        
        return notices

    def _check_fear_greed_risk(self) -> List[str]:
        """
        检查市场恐贪指数风险
        
        Returns:
            市场恐贪指数风险提醒列表
        """
        notices = []
        
        try:
            # 获取恐贪指数数据
            fear_greed_result = self.fear_greed_manager.get_index_data(None, None, 180)
            if not fear_greed_result.get("success"):
                return notices
            
            values = fear_greed_result["values"]
            if not values:
                return notices
            
            current_value = values[-1]
            
            if current_value >= 80:
                notices.append(f"⚠️ 市场恐贪指数过高({current_value:.1f})，市场情绪贪婪")
            elif current_value <= 20:
                notices.append(f"💰 市场恐贪指数过低({current_value:.1f})，市场情绪恐惧")
                
        except Exception as e:
            logger.error(f"检查市场恐贪指数风险失败: {e}")
        
        return notices

    def _get_market_info_notices(self) -> List[str]:
        """
        获取市场信息提醒（当没有风险提醒时使用）
        
        Returns:
            市场信息提醒列表
        """
        return [
            "📈 上证指数突破3200点，市场情绪回暖",
            "💰 北向资金今日净流入85.6亿元",
            "📊 科技板块PE估值处于历史低位",
            "🔥 新能源概念股集体上涨，涨幅超3%",
            "⚠️ 医药板块回调，建议关注低吸机会",
            "📈 融资融券余额连续三日增长",
            "💰 消费板块资金流入明显",
            "📊 市场恐贪指数回升至65",
            "🤖 机器人概念板块技术面突破",
            "📦 先进封装概念获政策支持"
        ] 