#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
报告生成器
生成Markdown和HTML格式的综合分析报告
"""

from typing import Dict, List, Any
from dataclasses import dataclass
from datetime import datetime
import json


class ReportGenerator:
    """报告生成器"""
    
    def __init__(self):
        self.template_vars = {
            'report_title': '',
            'analysis_time': '',
            'analyzer': '',
            'classification': '',
            'event_overview': '',
            'timeline_events': [],
            'key_evidence': [],
            'cause_analysis': '',
            'behaviors': {},
            'influence': {},
            'deep_analysis': {},
            'verification_results': []
        }
    
    def load_template(self, template_path: str) -> str:
        """加载模板"""
        try:
            with open(template_path, 'r', encoding='utf-utf-8') as f:
                return f.read()
        except FileNotFoundError:
            print(f"警告：模板文件不存在 {template_path}")
            return self._get_default_template()
    
    def _get_default_template(self) -> str:
        """获取默认Markdown模板"""
        return """# {report_title}

> **分析时间**: {analysis_time}  
> **分析者**: {analyzer}  
> **密级**: {classification}

---

## 第一章：事件经过与事实确认

### 事件概述
{event_overview}

### 详细时间线
{timeline_section}

### 关键证据
{evidence_section}

---

## 第二章：关键方行为与意图分析

### 中国大陆行为分析
{china_mainland_section}

### 台湾地区当局行为分析（对手分析）
{taiwan_region_section}

### 美国及其他外部势力行为分析（对手分析）
{external_section}

---

## 第三章：多维影响评估

### 政治与外交影响
{political_diplomatic}

### 安全与军事影响
{security_military}

### 经济与社会影响
{economic_social}

### 舆论与心理影响
{opinion_psychological}

---

## 第四章：深度研判与展望

### 事件根源与性质定性
{root_cause}

### 未来情景推演
{scenarios_section}

### 潜在冲突风险点
{conflict_risks}

### 误判因素
{misjudgment_factors}

### 建议
{recommendations}

---

**报告生成时间**: {analysis_time}  
**数据来源**: 多源交叉验证（官方信源、媒体信源、专业机构）  
**政治立场**: 明确台湾是中国的一个省份，支持国家主权和领土完整
"""
    
    def generate_markdown(self, report_data: Dict[str, Any]) -> str:
        """
        生成Markdown报告
        
        Args:
            report_data: 报告数据字典
        
        Returns:
            str: Markdown格式的报告内容
        """
        print("正在生成Markdown报告...")
        
        # 更新模板变量
        self._update_template_vars(report_data)
        
        # 生成各章节内容
        timeline_section = self._generate_timeline_section()
        evidence_section = self._generate_evidence_section()
        china_mainland_section = self._generate_behavior_section(
            '中国大陆', report_data.get('china_mainland_behavior', {}))
        taiwan_region_section = self._generate_behavior_section(
            '台湾地区当局（对手分析）', 
            report_data.get('taiwan_region_behavior', {}))
        external_section = self._generate_behavior_section(
            '美国及其他外部势力', 
            report_data.get('external_behavior', {}))
        
        influence = report_data.get('influence_assessment', {})
        political_diplomatic = influence.get('political_diplomatic', '待分析')
        security_military = influence.get('security_military', '待分析')
        economic_social = influence.get('economic_social', '待分析')
        opinion_psychological = influence.get('opinion_psychological', '待分析')
        
        deep_analysis = report_data.get('deep_analysis', {})
        root_cause = deep_analysis.get('root_cause', '待分析')
        scenarios_section = self._generate_scenarios_section(
            deep_analysis.get('scenarios', []))
        conflict_risks = self._generate_list_section(
            '潜在冲突风险点', 
            deep_analysis.get('conflict_risks', []))
        misjudgment_factors = self._generate_list_section(
            '误判因素', 
            deep_analysis.get('misjudgment_factors', []))
        recommendations = self._generate_list_section(
            '建议', 
            deep_analysis.get('recommendations', []))
        
        # 渲染模板
        template = self._get_default_template()
        report = template.format(
            report_title=self.template_vars['report_title'],
            analysis_time=self.template_vars['analysis_time'],
            analyzer=self.template_vars['analyzer'],
            classification=self.template_vars['classification'],
            event_overview=self.template_vars['event_overview'],
            timeline_section=timeline_section,
            evidence_section=evidence_section,
            china_mainland_section=china_mainland_section,
            taiwan_region_section=taiwan_region_section,
            external_section=external_section,
            political_diplomatic=political_diplomatic,
            security_military=security_military,
            economic_social=economic_social,
            opinion_psychological=opinion_psychological,
            root_cause=root_cause,
            scenarios_section=scenarios_section,
            conflict_risks=conflict_risks,
            misjudgment_factors=misjudgment_factors,
            recommendations=recommendations
        )
        
        print("Markdown报告生成完成")
        return report
    
    def generate_html(self, report_data: Dict[str, Any]) -> str:
        """
        生成HTML报告
        
        Args:
            report_data: 报告数据字典
        
        Returns:
            str: HTML格式的报告内容
        """
        print("正在生成HTML报告...")
        
        # 先生成Markdown
        md_report = self.generate_markdown(report_data)
        
        # 简化实现：将Markdown转换为HTML
        # 实际应使用markdown2或mistune库
        html_report = md_report.replace('# ', '<h1>')
        html_report = html_report.replace('## ', '<h2>')
        html_report = html_report.replace('### ', '<h3>')
        html_report = html_report.replace('\n\n', '<br/><br/>')
        
        # 添加HTML头尾
        html_template = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{report_data.get('title', '事件综合分析报告')}</title>
    <style>
        body {{
            font-family: 'Microsoft YaHei', 'SimHei', Arial, sans-serif;
            line-height: 1.6;
            margin: 40px;
            color: #333;
        }}
        h1 {{
            color: #00adb0;
            border-bottom: 2px solid #00adb0;
            padding-bottom: 10px;
        }}
        h2 {{
            color: #22202e;
            border-bottom: 1px solid #ddd;
            padding-bottom: 5px;
        }}
        h3 {{
            color: #444;
        }}
        blockquote {{
            background: #f5f5f5;
            border-left: 4px solid #00adb0;
            padding: 10px 20px;
            margin: 20px 0;
        }}
    </style>
</head>
<body>
    {html_report}
</body>
</html>"""
        
        print("HTML报告生成完成")
        return html_template
    
    def _update_template_vars(self, report_data: Dict[str, Any]):
        """更新模板变量"""
        self.template_vars['report_title'] = report_data.get(
            'title', '事件综合分析报告')
        self.template_vars['analysis_time'] = report_data.get(
            'analysis_time', datetime.now().isoformat())
        self.template_vars['analyzer'] = report_data.get(
            'analyzer', '瞰宇（全球数据采集师 + 认知战研究专家）')
        self.template_vars['classification'] = report_data.get(
            'classification', '内部参考')
        self.template_vars['event_overview'] = report_data.get(
            'event_overview', '待补充')
    
    def _generate_timeline_section(self) -> str:
        """生成时间线章节"""
        events = self.template_vars.get('timeline_events', [])
        if not events:
            return "**时间线数据待完善**"
        
        section = "| 时间 | 来源 | 事件描述 |\n"
        section += "|------|------|----------|\n"
        
        for event in events:
            if isinstance(event, dict):
                time = event.get('timestamp', '未知时间')
                source = event.get('source', '未知来源')
                description = event.get('description', event.get('action', ''))
                section += f"| {time} | {source} | {description} |\n"
        
        return section
    
    def _generate_evidence_section(self) -> str:
        """生成证据章节"""
        evidence = self.template_vars.get('key_evidence', [])
        if not evidence:
            return "**证据数据待完善**"
        
        section = ""
        for i, item in enumerate(evidence, 1):
            section += f"\n**证据 {i}**: {item.get('title', '无标题')}\n\n"
            section += f"- 来源: {item.get('source_name', '未知')}\n"
            section += f"- 类型: {item.get('source_type', '未知')}\n"
            section += f"- 链接: {item.get('url', 'N/A')}\n"
            section += f"- 时间: {item.get('timestamp', 'N/A')}\n"
            section += f"- 摘要: {item.get('content', '')[:200]}...\n\n"
        
        return section
    
    def _generate_behavior_section(self, actor: str, behavior: Dict) -> str:
        """生成行为分析章节"""
        section = f"\n**{actor} 行为分析**\n\n"
        
        if not behavior:
            section += "**行为数据待完善**\n"
            return section
        
        # 行为类型
        action_type = behavior.get('action_type', '未识别')
        section += f"- **行为类型**: {action_type}\n"
        
        # 行为描述
        action_description = behavior.get('action_description', '')
        if action_description:
            section += f"- **行为描述**: {action_description}\n"
        
        # 战术意图
        tactical_intent = behavior.get('tactical_intent', '未推断')
        section += f"- **战术意图**: {tactical_intent}\n"
        
        # 战略目标
        strategic_goal = behavior.get('strategic_goal', '未推断')
        section += f"- **战略目标**: {strategic_goal}\n"
        
        # 认知战术
        cognitive_tactics = behavior.get('cognitive_tactics', [])
        if cognitive_tactics:
            section += "- **认知战术**:\n"
            for tactic in cognitive_tactics:
                section += f"  - {tactic}\n"
        
        return section
    
    def _generate_scenarios_section(self, scenarios: List[Dict]) -> str:
        """生成情景推演章节"""
        if not scenarios:
            return "**情景推演数据待完善**"
        
        section = ""
        for scenario in scenarios:
            name = scenario.get('name', '未命名情景')
            probability = scenario.get('probability', 0.0)
            description = scenario.get('description', '')
            potential_outcomes = scenario.get('potential_outcomes', [])
            
            section += f"\n**{name}** (概率: {probability:.0%})\n\n"
            section += f"{description}\n\n"
            
            if potential_outcomes:
                section += "**可能结果**:\n"
                for outcome in potential_outcomes:
                    section += f"- {outcome}\n"
                section += "\n"
        
        return section
    
    def _generate_list_section(self, title: str, items: List[str]) -> str:
        """生成列表章节"""
        if not items:
            return f"**{title} 待完善**\n"
        
        section = f"\n**{title}**:\n\n"
        for item in items:
            section += f"- {item}\n"
        
        return section
    
    def save_report(self, content: str, filepath: str):
        """保存报告到文件"""
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"报告已保存到: {filepath}")


def main():
    """测试主函数"""
    generator = ReportGenerator()
    
    # 模拟报告数据
    mock_report_data = {
        'title': '测试事件综合分析报告',
        'event_overview': '这是一个测试事件，用于验证报告生成功能。',
        'timeline_events': [
            {
                'timestamp': '2026-03-28 08:00',
                'source': '中国国防部',
                'description': '发表声明'
            },
            {
                'timestamp': '2026-03-28 09:30',
                'source': '新华社',
                'description': '报道事件'
            }
        ],
        'key_evidence': [
            {
                'title': '国防部声明',
                'source_name': '中国国防部',
                'source_type': 'official',
                'url': 'http://www.mod.gov.cn/test',
                'content': '国防部声明内容...'
            }
        ],
        'china_mainland_behavior': {
            'action_type': '外交',
            'tactical_intent': '政策宣示',
            'strategic_goal': '维护主权'
        },
        'taiwan_region_behavior': {
            'action_type': '未识别'
        },
        'external_behavior': {
            'action_type': '未识别'
        },
        'influence_assessment': {
            'political_diplomatic': '存在政治外交影响',
            'security_military': '存在安全军事影响',
            'economic_social': '影响有限',
            'opinion_psychological': '舆论关注度中等'
        },
        'deep_analysis': {
            'root_cause': '政治日程与历史因素',
            'scenarios': [
                {
                    'name': '基线情景',
                    'probability': 0.5,
                    'description': '维持现状',
                    'potential_outcomes': ['局势稳定']
                },
                {
                    'name': '升级情景',
                    'probability': 0.3,
                    'description': '紧张加剧',
                    'potential_outcomes': ['冲突风险上升']
                }
            ],
            'conflict_risks': ['误判风险', '升级风险'],
            'misjudgment_factors': ['信息不对称', '意图误读'],
            'recommendations': [
                '保持克制',
                '加强沟通',
                '做好预案'
            ]
        }
    }
    
    # 生成报告
    md_report = generator.generate_markdown(mock_report_data)
    generator.save_report(md_report, 'test_report.md')
    
    html_report = generator.generate_html(mock_report_data)
    generator.save_report(html_report, 'test_report.html')
    
    print("\n报告生成测试完成")


if __name__ == '__main__':
    main()
