#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
账号可信度评估模块 (Account Credibility Evaluator)

评估社交媒体账号的可信度
"""

from typing import Dict, List, Any
from enum import Enum


class AccountType(Enum):
    """账号类型"""
    PERSONAL = "个人账号"
    MEDIA = "媒体账号"
    OFFICIAL = "官方账号"
    ORGANIZATION = "组织账号"
    BOT = "机器人账号"
    UNKNOWN = "未知"


class AccountEvaluator:
    """账号可信度评估器"""

    def __init__(self):
        # 不同平台的认证标识
        self.verification_indicators = {
            'twitter': ['verified', 'blue_verified'],
            'facebook': ['verified', 'page_verified'],
            'instagram': ['verified'],
            'youtube': ['verified'],
            'tiktok': ['verified'],
            'weibo': ['verified', 'v'],
            'bilibili': ['official']
        }

    async def evaluate(self, account_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        评估账号可信度

        Args:
            account_info: 账号信息

        Returns:
            Dict: 评估结果
        """
        if not account_info:
            return {
                "account_type": AccountType.UNKNOWN.value,
                "credibility_score": 0.0,
                "verification_status": "未知",
                "risk_factors": [],
                "trust_indicators": []
            }

        # 1. 识别账号类型
        account_type = self._identify_account_type(account_info)

        # 2. 计算可信度分数
        credibility_score = self._calculate_credibility_score(account_info)

        # 3. 确定认证状态
        verification_status = self._check_verification_status(account_info)

        # 4. 识别风险因素
        risk_factors = self._identify_risk_factors(account_info)

        # 5. 识别信任指标
        trust_indicators = self._identify_trust_indicators(account_info)

        result = {
            "account_type": account_type.value,
            "credibility_score": round(credibility_score, 2),
            "verification_status": verification_status,
            "risk_factors": risk_factors,
            "trust_indicators": trust_indicators,
            "account_details": {
                "name": account_info.get('name', 'Unknown'),
                "followers": account_info.get('followers', 0),
                "following": account_info.get('following', 0),
                "posts_count": account_info.get('posts_count', 0),
                "account_age_days": account_info.get('account_age_days', 0)
            }
        }

        return result

    def _identify_account_type(self, account_info: Dict[str, Any]) -> AccountType:
        """
        识别账号类型

        Args:
            account_info: 账号信息

        Returns:
            AccountType: 账号类型
        """
        name = account_info.get('name', '').lower()
        username = account_info.get('username', '').lower()
        bio = account_info.get('bio', '').lower()
        followers = account_info.get('followers', 0)
        posts_count = account_info.get('posts_count', 0)

        # 机器人账号特征
        bot_indicators = ['bot', '自动', 'auto', 'official bot', 'news bot']
        if any(indicator in name or indicator in username for indicator in bot_indicators):
            return AccountType.BOT

        # 媒体账号特征
        media_indicators = [
            'news', '媒体', '新闻', 'media', 'press',
            'daily', 'times', 'post', 'reporter'
        ]
        if any(indicator in name or indicator in bio for indicator in media_indicators):
            return AccountType.MEDIA

        # 官方账号特征
        official_indicators = [
            'official', '官方', 'gov', 'government',
            'ministry', 'department', 'agency'
        ]
        if any(indicator in name or indicator in bio for indicator in official_indicators):
            return AccountType.OFFICIAL

        # 组织账号特征
        org_indicators = [
            'corp', 'corporation', 'inc', 'llc', 'ltd',
            'company', 'org', 'organization', '机构', '公司'
        ]
        if any(indicator in name or indicator in bio for indicator in org_indicators):
            return AccountType.ORGANIZATION

        # 高粉丝量可能是媒体账号
        if followers > 100000:
            return AccountType.MEDIA

        # 默认为个人账号
        return AccountType.PERSONAL

    def _calculate_credibility_score(self, account_info: Dict[str, Any]) -> float:
        """
        计算可信度分数（0-1）

        评估维度：
        1. 认证状态（0-0.3）
        2. 粉丝数与互动比（0-0.2）
        3. 账号年龄（0-0.2）
        4. 发帖频率和数量（0-0.1）
        5. 账号类型（0-0.2）
        """
        score = 0.0

        # 1. 认证状态
        if account_info.get('verified', False):
            score += 0.3

        # 2. 粉丝数与互动比
        followers = account_info.get('followers', 0)
        avg_likes = account_info.get('avg_likes_per_post', 0)
        avg_comments = account_info.get('avg_comments_per_post', 0)

        if followers > 0:
            engagement_rate = (avg_likes + avg_comments) / followers
            # 合理的互动率（1%-5%）给予高分
            if 0.01 <= engagement_rate <= 0.05:
                score += 0.2
            elif engagement_rate > 0.005:
                score += 0.1

        # 3. 账号年龄
        account_age_days = account_info.get('account_age_days', 0)
        if account_age_days >= 365:  # 1年以上
            score += 0.2
        elif account_age_days >= 180:  # 半年以上
            score += 0.1

        # 4. 发帖频率和数量
        posts_count = account_info.get('posts_count', 0)
        if posts_count >= 1000:
            score += 0.1
        elif posts_count >= 100:
            score += 0.05

        # 5. 账号类型
        account_type = self._identify_account_type(account_info)
        if account_type in [AccountType.OFFICIAL, AccountType.MEDIA]:
            score += 0.2
        elif account_type == AccountType.BOT:
            score -= 0.3  # 机器人扣分

        # 截断在0-1之间
        return max(0.0, min(1.0, score))

    def _check_verification_status(self, account_info: Dict[str, Any]) -> str:
        """
        检查认证状态

        Args:
            account_info: 账号信息

        Returns:
            str: 认证状态
        """
        # 直接检查verified字段
        if account_info.get('verified', False):
            return "已认证"

        # 检查其他认证相关字段
        platform = account_info.get('platform', '').lower()
        indicators = self.verification_indicators.get(platform, [])

        for indicator in indicators:
            if account_info.get(indicator, False):
                return f"已认证（{indicator}）"

        # 检查blue_verified（Twitter Blue）
        if account_info.get('blue_verified', False):
            return "已认证（蓝V）"

        return "未认证"

    def _identify_risk_factors(self, account_info: Dict[str, Any]) -> List[str]:
        """
        识别风险因素

        Args:
            account_info: 账号信息

        Returns:
            List[str]: 风险因素列表
        """
        risk_factors = []

        followers = account_info.get('followers', 0)
        following = account_info.get('following', 0)
        posts_count = account_info.get('posts_count', 0)
        account_age_days = account_info.get('account_age_days', 0)
        bio = account_info.get('bio', '').lower()
        name = account_info.get('name', '').lower()
        username = account_info.get('username', '').lower()

        # 新账号
        if account_age_days < 30:
            risk_factors.append("新账号（创建不足30天）")

        # 极低粉丝数但大量发帖
        if followers < 100 and posts_count > 1000:
            risk_factors.append("低粉丝高发帖")

        # 粉丝数与关注数异常比例
        if followers > 0 and following > 0:
            ratio = followers / following
            if ratio < 0.1:  # 关注数远大于粉丝数
                risk_factors.append("关注数远大于粉丝数")
            elif ratio > 1000:  # 粉丝数远大于关注数
                risk_factors.append("粉丝数远大于关注数（可能是购买的粉丝）")

        # 账号名/用户名可疑
        suspicious_patterns = ['random', 'numbers123', 'user', 'temp']
        if any(pattern in username for pattern in suspicious_patterns):
            risk_factors.append("用户名格式可疑")

        # 简介空或过短
        if len(bio) < 10:
            risk_factors.append("个人简介空或过短")

        # 机器人特征
        bot_indicators = ['bot', '自动', 'auto']
        if any(indicator in name or indicator) in bot_indicators for indicator in username:
            risk_factors.append("疑似机器人账号")

        return risk_factors

    def _identify_trust_indicators(self, account_info: Dict[str, Any]) -> List[str]:
        """
        识别信任指标

        Args:
            account_info: 账号信息

        Returns:
            List[str]: 信任指标列表
        """
        trust_indicators = []

        followers = account_info.get('followers', 0)
        posts_count = account_info.get('posts_count', 0)
        account_age_days = account_info.get('account_age_days', 0)
        bio = account_info.get('bio', '')
        name = account_info.get('name', '')
        location = account_info.get('location', '')
        website = account_info.get('website', '')

        # 认证账号
        if account_info.get('verified', False):
            trust_indicators.append("平台认证")

        # 老账号
        if account_age_days >= 365:
            trust_indicators.append(f"账号存续{account_age_days // 365}年以上")

        # 高粉丝数
        if followers >= 10000:
            trust_indicators.append(f"拥有{followers}粉丝")

        # 活跃发帖
        if posts_count >= 1000:
            trust_indicators.append(f"发布{posts_count}条内容")

        # 完整资料
        if bio and len(bio) >= 50:
            trust_indicators.append("个人简介详细")

        if location:
            trust_indicators.append("设置了地理位置")

        if website:
            trust_indicators.append("提供了个人网站")

        if name:
            trust_indicators.append("设置了真实姓名")

        return trust_indicators
