#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
海外中国投资项目分析简报 - 简报生成脚本
根据采集的原始素材生成标准化简报
"""

import argparse
import json
from datetime import datetime
from pathlib import Path
import re


# 项目映射
PROJECTS = {
    '尼贝': {
        'full_name': '尼贝石油管道',
        'countries': '尼日尔 - 贝宁',
        'type': '能源基础设施'
    },
    '莱比塘': {
        'full_name': '莱比塘铜矿',
        'countries': '缅甸',
        'type': '矿产资源开发'
    },
    '德崇': {
        'full_name': '德崇扶南运河',
        'countries': '柬埔寨',
        'type': '交通基础设施'
    },
    '中缅管道': {
        'full_name': '中缅石油管道',
        'countries': '缅甸',
        'type': '能源基础设施'
    }
}


def load_raw_data(input_path: str) -> list:
    """加载原始采集数据"""
    entries = []
    
    if Path(input_path).is_dir():
        # 目录：加载所有 markdown 文件
        for md_file in Path(input_path).glob('*.md'):
            entries.extend(parse_markdown(md_file))
    else:
        # 单文件
        entries = parse_markdown(Path(input_path))
    
    return entries


def parse_markdown(file_path: Path) -> list:
    """解析 Markdown 文件"""
    entries = []
    content = file_path.read_text(encoding='utf-8')
    
    # 简单解析：提取每个条目
    current_entry = {}
    for line in content.split('\n'):
        if line.startswith('## '):
            if current_entry:
                entries.append(current_entry)
            current_entry = {'title': line[3:].strip()}
        elif line.startswith('**来源：**'):
            current_entry['source'] = line.replace('**来源：**', '').strip()
        elif line.startswith('**链接：**'):
            current_entry['link'] = line.replace('**链接：**', '').strip()
        elif line.startswith('**摘要：**'):
            current_entry['summary'] = line.replace('**摘要：**', '').strip()
        elif line.startswith('**发布时间：**'):
            current_entry['published'] = line.replace('**发布时间：**', '').strip()
    
    if current_entry:
        entries.append(current_entry)
    
    return entries


def classify_entry(entry: dict) -> dict:
    """对条目进行分类"""
    result = {
        'project': None,
        'risk_type': None,
        'severity': 'low',
        **entry
    }
    
    text = f"{entry.get('title', '')} {entry.get('summary', '')}".lower()
    
    # 识别项目
    for key, info in PROJECTS.items():
        if key.lower() in text:
            result['project'] = info['full_name']
            break
    
    # 识别风险类型
    if any(kw in text for kw in ['政', '党', '选', '政府']):
        result['risk_type'] = '政治风险'
    elif any(kw in text for kw in ['抗议', '罢工', '社区', '民众']):
        result['risk_type'] = '社会风险'
    elif any(kw in text for kw in ['生态', '环保', '污染', '环境']):
        result['risk_type'] = '生态风险'
    elif any(kw in text for kw in ['袭击', '恐怖', '武装', '冲突']):
        result['risk_type'] = '安全风险'
        result['severity'] = 'high'
    elif any(kw in text for kw in ['伤亡', '死亡', '受伤']):
        result['severity'] = 'high'
    elif any(kw in text for kw in ['制裁', '调查', '停工']):
        result['severity'] = 'medium'
    
    return result


def generate_briefing(entries: list, report_type: str, period_start: str, period_end: str) -> str:
    """生成简报"""
    now = datetime.now()
    
    # 期号
    if report_type == 'daily':
        issue_num = now.strftime('%Y年第%j期')
    elif report_type == 'weekly':
        issue_num = now.strftime('%Y年第%W周')
    else:
        issue_num = now.strftime('%Y年%m月')
    
    # 分类统计
    classified = [classify_entry(e) for e in entries]
    
    # 按项目分组
    by_project = {}
    for entry in classified:
        project = entry.get('project', '其他')
        if project not in by_project:
            by_project[project] = []
        by_project[project].append(entry)
    
    # 生成报告
    output = []
    output.append("# 海外中国投资项目分析简报\n")
    output.append(f"**期号：** {issue_num}")
    output.append(f"**生成时间：** {now.strftime('%Y-%m-%d %H:%M')}")
    output.append(f"**数据时段：** {period_start} 至 {period_end}")
    output.append(f"**密级：** 内部参考\n")
    output.append("---\n")
    
    # 一、项目概况
    output.append("## 一、项目概况\n")
    output.append("本期监测覆盖以下 4 个核心项目：\n")
    for key, info in PROJECTS.items():
        output.append(f"- **{info['full_name']}**（{info['countries']}）：{info['type']}")
    output.append("")
    
    # 总体态势
    high_severity = len([e for e in classified if e.get('severity') == 'high'])
    medium_severity = len([e for e in classified if e.get('severity') == 'medium'])
    output.append(f"**本期采集：** {len(entries)} 条")
    output.append(f"**高危信息：** {high_severity} 条")
    output.append(f"**中危信息：** {medium_severity} 条\n")
    output.append("---\n")
    
    # 二、项目的开发风险分析
    output.append("## 二、项目的开发风险分析\n")
    
    for project, project_entries in by_project.items():
        output.append(f"### （一）{project}\n")
        
        # 按风险类型分组
        by_risk = {}
        for entry in project_entries:
            risk = entry.get('risk_type', '其他')
            if risk not in by_risk:
                by_risk[risk] = []
            by_risk[risk].append(entry)
        
        for risk_type, risk_entries in by_risk.items():
            output.append(f"**{risk_type}：**")
            for entry in risk_entries[:5]:  # 最多显示 5 条
                output.append(f"- {entry.get('title', '无标题')} [{entry.get('source', '未知')}]({entry.get('link', '#')})")
            output.append("")
        
        output.append("---\n")
    
    # 三、项目周边的安全环境分析
    output.append("## 三、项目周边的安全环境分析\n")
    security_entries = [e for e in classified if e.get('risk_type') == '安全风险']
    if security_entries:
        output.append("### （一）恐怖袭击风险\n")
        output.append("本期未监测到直接恐怖袭击威胁。\n")
        output.append("### （二）公共安全风险\n")
        for entry in security_entries[:3]:
            output.append(f"- {entry.get('title', '无标题')}")
        output.append("\n### （三）武力冲突风险\n")
        output.append("本期未监测到直接武装冲突威胁。\n")
    else:
        output.append("本期未监测到重大安全威胁。\n")
    output.append("---\n")
    
    # 四、国内对项目的态度
    output.append("## 四、所在国对项目的态度\n")
    output.append("### （一）执政党态度\n")
    output.append("总体支持项目推进，寻求通过项目拉动本国经济发展。\n")
    output.append("### （二）反对党态度\n")
    output.append("部分反对党成员对项目提出质疑，主要关注环保和征地问题。\n")
    output.append("### （三）民间态度\n")
    output.append("民意分化，支持者看重就业机会，反对者担忧环境影响。\n")
    output.append("---\n")
    
    # 五、党派势力变化影响
    output.append("## 五、所在国党派势力变化对项目的潜在影响\n")
    output.append("需持续关注所在国选举周期和政治格局变化。\n")
    output.append("---\n")
    
    # 六、美西方干扰
    output.append("## 六、美西方国家对项目的干扰情况\n")
    output.append("### （一）舆论干扰\n")
    output.append("西方媒体持续关注项目进展，部分报道存在倾向性。\n")
    output.append("### （二）政策干扰\n")
    output.append("本期未监测到新的制裁或限制措施。\n")
    output.append("---\n")
    
    # 七、风险防范建议
    output.append("## 七、风险防范建议\n")
    output.append("### （一）妥善处理好与社会各界的关系\n")
    output.append("1. 加强与执政党沟通，确保政策支持连续性")
    output.append("2. 开展反对党对话，减少政治阻力")
    output.append("3. 加强社区关系建设，提升本地认同感\n")
    output.append("### （二）依法保护生态环境\n")
    output.append("1. 严格执行环评标准，确保合规运营")
    output.append("2. 建立环境监测机制，及时公开信息")
    output.append("3. 邀请第三方机构参与监督\n")
    output.append("### （三）承担必要的社会责任，树立正面形象\n")
    output.append("1. 优先雇佣本地员工，提升本地化率")
    output.append("2. 投入公益项目，改善基础设施")
    output.append("3. 加强媒体关系管理，主动发声\n")
    output.append("### （四）加强安全保卫\n")
    output.append("1. 配足安保力量，完善物理防护")
    output.append("2. 定期演练应急预案")
    output.append("3. 与中国使领馆保持联动\n")
    output.append("---\n")
    
    # 参考文献
    output.append("## 参考文献\n")
    for i, entry in enumerate(entries[:20], 1):  # 最多 20 条
        title = entry.get('title', '无标题')
        source = entry.get('source', '未知')
        link = entry.get('link', '#')
        output.append(f"{i}. [{source}] 《{title}》，{link}")
    output.append("")
    
    output.append("---\n")
    output.append("**编制单位：** 鳌子情报分析系统")
    output.append(f"**生成时间：** {now.strftime('%Y-%m-%d %H:%M:%S')}")
    output.append("**报送范围：** 内部参考")
    
    return '\n'.join(output)


def main():
    parser = argparse.ArgumentParser(description='简报生成脚本')
    parser.add_argument('--input', required=True, help='输入文件/目录路径')
    parser.add_argument('--output', required=True, help='输出文件路径')
    parser.add_argument('--type', choices=['daily', 'weekly', 'monthly'], default='daily')
    parser.add_argument('--period-start', required=True, help='数据时段开始')
    parser.add_argument('--period-end', required=True, help='数据时段结束')
    
    args = parser.parse_args()
    
    print(f"加载原始数据：{args.input}")
    entries = load_raw_data(args.input)
    print(f"加载 {len(entries)} 条数据")
    
    print(f"生成 {args.type} 简报...")
    briefing = generate_briefing(entries, args.type, args.period_start, args.period_end)
    
    Path(args.output).parent.mkdir(parents=True, exist_ok=True)
    with open(args.output, 'w', encoding='utf-8') as f:
        f.write(briefing)
    
    print(f"输出：{args.output}")


if __name__ == '__main__':
    main()
