import math
from typing import Dict, Tuple



class TrafficFactorB12Calculator:
    """流量因子B12计算器"""
    
    def __init__(self):
        """初始化计算器"""
        pass
    
    def calculate_traffic_factor_b12(self,
                                   search_index_s1: float,
                                   industry_average_s2: float,
                                   social_media_spread_s3: float) -> float:
        """
        计算流量因子B12

        流量因子B12 = ln(近30天搜索指数S1/行业均值S2) × 0.3 + 社交媒体传播度S3 × 0.7
        
        args:
            search_index_s1: 近30天搜索指数S1 (API获取)
            industry_average_s2: 行业均值S2 (系统配置)
            social_media_spread_s3: 社交媒体传播度S3 (API获取)
            
        returns:
            float: 流量因子B12
        """
        # 避免除零和对数计算错误
        if industry_average_s2 <= 0:
            raise ValueError("行业均值S2必须大于0")
        
        if search_index_s1 <= 0:
            # 如果搜索指数为0或负数，使用最小值避免对数计算错误
            search_index_s1 = 1.0
        
        # ，不进行任何拆分
        traffic_factor = (math.log(search_index_s1 / industry_average_s2) * 0.3 + 
                         social_media_spread_s3 * 0.7)
        
        return traffic_factor


    
    def calculate_social_media_spread_s3(self,
                                       interaction_index: float,
                                       coverage_index: float,
                                       conversion_efficiency: float) -> float:
        """
        计算社交媒体传播度S3

        社交媒体传播度S3 = 互动量指数 × 0.4 + 覆盖人群指数 × 0.3 + 转化效率 × 0.3

        args:
            interaction_index: 互动量指数 (API获取)
            coverage_index: 覆盖人群指数 (API获取)
            conversion_efficiency: 转化效率 (用户填写)

        returns:
            float: 社交媒体传播度S3
        """
        #
        social_media_spread = (interaction_index * 0.4 +
                              coverage_index * 0.3 +
                              conversion_efficiency * 0.3)

        return social_media_spread
    
    def calculate_interaction_index(self,
                                 likes: int,
                                 comments: int,
                                 shares: int) -> float:
        """
        计算互动量指数

        互动量指数 = (点赞 + 评论 + 转发) / 1000
        
        args:
            likes: 点赞数 (API获取)
            comments: 评论数 (API获取)
            shares: 转发数 (API获取)
            
        returns:
            float: 互动量指数
        """
        # 
        interaction_index = (likes + comments + shares) / 1000.0
        
        return interaction_index
    
    def calculate_coverage_index(self, followers: int) -> float:
        """
        计算覆盖人群指数

        覆盖人群指数 = 粉丝数 / 10000
        
        args:
            followers: 粉丝数 (API获取)
            
        returns:
            float: 覆盖人群指数
        """
        # 
        coverage_index = followers / 10000.0
        
        return coverage_index
    
    def calculate_conversion_efficiency(self,
                                      click_count: int,
                                      view_count: int) -> float:
        """
        计算转化效率
        
        ：
        转化效率 = 商品链接点击量 / 内容浏览量
        
        args:
            click_count: 商品链接点击量 (用户填写)
            view_count: 内容浏览量 (用户填写)
            
        returns:
            float: 转化效率
        """
        if view_count == 0:
            return 0.0
        
        # 
        conversion_efficiency = click_count / view_count
        
        return conversion_efficiency


class PlatformDataProcessor:
    """平台数据处理类"""
    
    @staticmethod
    def parse_platform_accounts(platform_data: str) -> Dict[str, str]:
        """
        解析平台账号数据
        
        输入格式：B站：12345678\n抖音：22334455
        
        args:
            platform_data: 平台账号数据字符串 (用户填写)
            
        returns:
            Dict[str, str]: 平台账号字典
        """
        accounts = {}
        lines = platform_data.strip().split('\n')
        
        for line in lines:
            if '：' in line or ':' in line:
                separator = '：' if '：' in line else ':'
                parts = line.split(separator, 1)
                if len(parts) == 2:
                    platform = parts[0].strip()
                    account = parts[1].strip()
                    accounts[platform] = account
        
        return accounts
    
    @staticmethod
    def calculate_multi_platform_interaction(platform_data: Dict[str, Dict]) -> Tuple[float, float]:
        """
        计算多平台互动数据
        
        args:
            platform_data: 平台数据字典，格式为 {平台名: {likes: int, comments: int, shares: int, followers: int}} (API获取)
            
        returns:
            Tuple[float, float]: (互动量指数, 覆盖人群指数)
        """
        total_interactions = 0
        total_followers = 0
        
        for platform, data in platform_data.items():
            # 计算互动量
            interactions = data.get('likes', 0) + data.get('comments', 0) + data.get('shares', 0)
            total_interactions += interactions
            
            # 计算粉丝数
            followers = data.get('followers', 0)
            total_followers += followers
        
        # 计算指数
        calculator = TrafficFactorB12Calculator()
        interaction_index = calculator.calculate_interaction_index(
            total_interactions, 0, 0  # 已经包含了所有互动数据
        )
        coverage_index = calculator.calculate_coverage_index(total_followers)
        
        return interaction_index, coverage_index


# 热度评分相关函数
def calculate_heat_score(daily_views: float, favorites: int) -> float:
    """
    计算热度分
    
    热度评分标准：
    - 高热度：近7日日均浏览量 > 1000，或收藏数 > 100 → 1.0
    - 中热度：近7日日均浏览量 ∈ [100, 1000]，或收藏数 ∈ [20, 100] → 0.6
    - 低热度：近7日日均浏览量 < 100，且收藏数 < 20 → 0.2
    - 无数据：无任何浏览与互动数据 → 0.0
    
    args:
        daily_views: 近7日日均浏览量 (API获取)
        favorites: 收藏数 (API获取)
        
    returns:
        float: 热度分
    """
    if daily_views > 1000 or favorites > 100:
        return 1.0
    elif (daily_views >= 100 and daily_views <= 1000) or (favorites >= 20 and favorites <= 100):
        return 0.6
    elif daily_views < 100 and favorites < 20:
        return 0.2
    else:
        return 0.0

# 30天搜索指数S1
def calculate_search_index_s1(baidu_index: float,
                              wechat_index: float,
                              weibo_index: float) -> float:
    """
    计算近30天搜索指数S1

    近30天搜索指数S1 = 百度搜索指数 × 0.4 + 微信搜索指数 × 0.3 + 微博搜索指数 × 0.3

    args:
        baidu_index: 百度搜索指数 (API获取)
        wechat_index: 微信搜索指数 (API获取)
        weibo_index: 微博搜索指数 (API获取)

    returns:
        float: 近30天搜索指数S1
    """
    #
    search_index = (baidu_index * 0.4 +
                    wechat_index * 0.3 +
                    weibo_index * 0.3)

    return search_index
# 示例使用
if __name__ == "__main__":
    # 创建计算器实例
    calculator = TrafficFactorB12Calculator()
    processor = PlatformDataProcessor()
    
    # 示例数据
    # 搜索指数数据 (API获取)
    baidu_index = 6000.0
    wechat_index = 4500.0
    weibo_index = 3000.0
    
    # 行业均值 (系统配置)
    industry_average = 5000.0
    
    # 平台账号数据 (用户填写)
    platform_accounts = "B站：12345678\n抖音：22334455"
    accounts = processor.parse_platform_accounts(platform_accounts)
    
    # 平台互动数据 (API获取)
    platform_data = {
        "B站": {
            "likes": 1000,
            "comments": 200,
            "shares": 50,
            "followers": 50000
        },
        "抖音": {
            "likes": 2000,
            "comments": 300,
            "shares": 100,
            "followers": 30000
        }
    }
    
    # 转化效率数据 (用户填写)
    click_count = 20
    view_count = 200
    
    # 计算各项指标
    search_index_s1 = calculator.calculate_search_index_s1(baidu_index, wechat_index, weibo_index)
    interaction_index, coverage_index = processor.calculate_multi_platform_interaction(platform_data)
    conversion_efficiency = calculator.calculate_conversion_efficiency(click_count, view_count)
    social_media_spread_s3 = calculator.calculate_social_media_spread_s3(
        interaction_index, coverage_index, conversion_efficiency
    )
    
    # 计算流量因子B12
    traffic_factor = calculator.calculate_traffic_factor_b12(
        search_index_s1, industry_average, social_media_spread_s3
    )
    
    print(f"近30天搜索指数S1: {search_index_s1:.2f}")
    print(f"行业均值S2: {industry_average:.2f}")
    print(f"互动量指数: {interaction_index:.4f}")
    print(f"覆盖人群指数: {coverage_index:.4f}")
    print(f"转化效率: {conversion_efficiency:.4f}")
    print(f"社交媒体传播度S3: {social_media_spread_s3:.4f}")
    print(f"流量因子B12: {traffic_factor:.4f}")