#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
行为模式识别模块 - 人物画像技能
分析行为在时间线上的规律

创建时间：2026-04-03
开发者：瞰宇 (Kàn Yǔ)
"""

import json
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
from collections import defaultdict
from datetime import datetime


@dataclass
class ActionPattern:
    """行动模式"""
    radical_degree: str  # 激进程度（低/中/高）
    confrontational: bool  # 对抗性
    exposure_preference: str  # 曝光偏好（低调/高调）
    cooperation_style: str  # 合作模式（共赢/零和）


@dataclass
class Adaptation:
    """适应性分析"""
    failure_response: str  # 面对失败的反应
    success_response: str  # 面对成功的反应
    criticism_response: str  # 面对批评的反应


class BehaviorAnalyzer:
    """
    行为模式识别器
    分析行为在时间线上的规律
    """
    
    def __init__(self):
        """初始化行为模式识别器"""
        self.behaviors = []
        self.decisions = []
        self.crisis_responses = []
    
    def load_behaviors(self, behaviors: List[Dict]):
        """
        加载行为记录
        
        Args:
            behaviors: 行为记录列表
        """
        self.behaviors = behaviors
    
    def load_decisions(self, decisions: List[Dict]):
        """
        加载决策案例
        
        Args:
            decisions: 决策案例列表
        """
        self.decisions = decisions
    
    def load_crisis_responses(self, responses: List[Dict]):
        """
        加载危机应对记录
        
        Args:
            responses: 危机应对记录列表
        """
        self.crisis_responses = responses
    
    def analyze_action_patterns(self) -> ActionPattern:
        """
        分析行动模式
        
        Returns:
            ActionPattern对象
        """
        if not self.behaviors:
            return ActionPattern("中", False, "高调", "共赢")
        
        # 统计激进程度
        radical_count = sum(
            1 for b in self.behaviors 
            if "激进" in b.get("description", "") or "突破" in b.get("description", "")
        )
        moderate_count = sum(
            1 for b in self.behaviors 
            if "渐进" in b.get("description", "") or "稳健" in b.get("description", "")
        )
        
        # 判断激进程度
        if radical_count > moderate_count:
            radical_degree = "高"
        elif moderate_count > radical_count:
            radical_degree = "低"
        else:
            radical_degree = "中"
        
        # 判断对抗性
        confrontational_keywords = ["对抗", "冲突", "抵制", "强硬"]
        confrontational_count = sum(
            1 for b in self.behaviors
            if any(kw in b.get("description", "") for kw in confrontational_keywords)
        )
        confrontational = confrontational_count > len(self.behaviors) * 0.4
        
        # 判断曝光偏好
        high_profile_keywords = ["演讲", "声明", "社媒", "采访", "发布会"]
        high_profile_count = sum(
            1 for b in self.behaviors
            if any(kw in b.get("type", "") for kw in high_profile_keywords)
        )
        exposure_preference = "高调" if high_profile_count > len(self.behaviors) * 0.5 else "低调"
        
        # 判断合作模式
        cooperation_keywords = ["合作", "协商", "妥协", "双赢"]
        zero_sum_keywords = ["击败", "赢", "胜利", "压制"]
        
        cooperation_count = sum(
            1 for b in self.behaviors
            if any(kw in b.get("description", "") for kw in cooperation_keywords)
        )
        zero_sum_count = sum(
            1 for b in self.behaviors
            if any(kw in b.get("description", "") for kw in zero_sum_keywords)
        )
        
        if zero_sum_count > cooperation_count:
            cooperation_style = "零和"
        else:
            cooperation_style = "共赢"
        
        return ActionPattern(
            radical_degree=radical_degree,
            confrontational=confrontational,
            exposure_preference=exposure_preference,
            cooperation_style=cooperation_style
        )
    
    def analyze_adaptation(self) -> Adaptation:
        """
        分析适应性
        
        Returns:
            Adaptation对象
        """
        if not self.crisis_responses:
            return Adaptation("数据不足", "数据不足", "数据不足")
        
        # 面对失败的反应
        failure_responses = [
            r for r in self.crisis_responses 
            if r.get("outcome") == "failure" or "失败" in r.get("outcome", "")
        ]
        
        if failure_responses:
            # 分析归因模式
            external_blame_count = sum(
                1 for r in failure_responses
                if "他人" in r.get("response", "") or "外部" in r.get("response", "")
            )
            
            if external_blame_count > len(failure_responses) * 0.6:
                failure_response = "外归因（归咎于他人）"
            else:
                failure_response = "自我反思或承担"
        else:
            failure_response = "数据不足"
        
        # 面对成功的反应
        success_responses = [
            r for r in self.crisis_responses
            if r.get("outcome") == "success" or "成功" in r.get("outcome", "")
        ]
        
        if success_responses:
            self_attribution_count = sum(
                1 for r in success_responses
                if "我" in r.get("response", "") or "个人" in r.get("response", "")
            )
            
            if self_attribution_count > len(success_responses) * 0.6:
                success_response = "自归因（归功于个人）"
            else:
                success_response = "团队归因"
        else:
            success_response = "数据不足"
        
        # 面对批评的反应
        criticism_responses = [
            r for r in self.crisis_responses
            if "批评" in r.get("context", "") or "质疑" in r.get("context", "")
        ]
        
        if criticism_responses:
            confrontational_count = sum(
                1 for r in criticism_responses
                if "反击" in r.get("response", "") or "否认" in r.get("response", "")
            )
            
            if confrontational_count > len(criticism_responses) * 0.5:
                criticism_response = "对抗性回应"
            else:
                criticism_response = "协调性回应或忽略"
        else:
            criticism_response = "数据不足"
        
        return Adaptation(
            failure_response=failure_response,
            success_response=success_response,
            criticism_response=criticism_response
        )
    
    def generate_behavior_report(self) -> Dict:
        """
        生成行为模式识别报告
        
        Returns:
            分析报告字典
        """
       
        
        # 分析行动模式
        action_patterns = self.analyze_action_patterns()
        
        # 分析适应性
        adaptation = self.analyze_adaptation()
        
        report = {
            "行动模式": {
                "激进程度": action_patterns.radical_degree,
                "对抗性": "是" if action_patterns.confrontational else "否",
                "曝光偏好": action_patterns.exposure_preference,
                "合作模式": action_patterns.cooperation_style
            },
            "适应性分析": {
                "面对失败的反应": adaptation.failure_response,
                "面对成功的反应": adaptation.success_response,
                "面对批评的反应": adaptation.criticism_response
            },
            "决策案例分析": [
                {
                    "决策": d.get("description", ""),
                    "时间": d.get("date", ""),
                    "影响": d.get("impact", "")
                }
                for d in self.decisions[:5]
            ]
        }
        
        return report


def main():
    """测试行为模式识别器"""
    analyzer = BehaviorAnalyzer()
    
    # 示例行为数据
    behaviors = [
        {"type": "演讲", "description": "发表突破性改革演讲", "date": "2024-01-01"},
        {"type": "声明", "description": "对抗性声明，强硬回应", "date": "2024-02-15"},
        {"type": "行动", "description": "渐进式政策调整", "date": "2024-03-10"}
    ]
    
    # 示例危机应对数据
    crisis_responses = [
        {
            "context": "政策失败",
            "outcome": "failure",
            "response": "归咎于前政府和外部环境"
        },
        {
            "context": "项目成功",
            "outcome": "success",
            "response": "这是我的功劳，我领导了整个项目"
        },
        {
            "context": "遭到媒体批评",
            "outcome": "neutral",
            "response": "反击媒体，称其为假新闻"
        }
    ]
    
    analyzer.load_behaviors(behaviors)
    analyzer.load_crisis_responses(crisis_responses)
    
    # 生成报告
    print("=== 行为模式识别报告 ===")
    report = analyzer.generate_behavior_report()
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
