#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
海外中国投资项目分析简报 - 警报检测脚本
检测是否触发红/橙/黄三级警报
"""

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


# 警报关键词
RED_ALERT_TERMS = [
    '伤亡', '死亡', '袭击', '政变', '内战', '撤离', '征收',
    '武装', '恐怖', '绑架', '3 人以上', '多人死亡'
]

ORANGE_ALERT_TERMS = [
    '抗议', '罢工', '停工', '制裁', '调查', '反对',
    '大规模', '百人', '百人以上的', '重要官员', '负面表态'
]

YELLOW_ALERT_TERMS = [
    '纠纷', '争议', '环保', '征地', '负面报道',
    '汇率', '政策变动', '小规模'
]


def detect_alert_level(text: str) -> str:
    """检测警报级别"""
    text_lower = text.lower()
    
    for term in RED_ALERT_TERMS:
        if term.lower() in text_lower:
            return 'red'
    
    for term in ORANGE_ALERT_TERMS:
        if term.lower() in text_lower:
            return 'orange'
    
    for term in YELLOW_ALERT_TERMS:
        if term.lower() in text_lower:
            return 'yellow'
    
    return 'none'


def generate_alert(entry: dict, level: str, output_dir: str) -> str:
    """生成警报文件"""
    now = datetime.now()
    timestamp = now.strftime('%Y%m%d_%H%M%S')
    
    level_names = {
        'red': '🔴 红色警报',
        'orange': '🟠 橙色警报',
        'yellow': '🟡 黄色警报'
    }
    
    response_times = {
        'red': '立即上报',
        'orange': '2 小时内上报',
        'yellow': '日报汇总'
    }
    
    alert_content = f"""# {level_names.get(level, '警报')}

**生成时间：** {now.strftime('%Y-%m-%d %H:%M:%S')}
**警报级别：** {level}
**响应时限：** {response_times.get(level, '未知')}

---

## 警报内容

**标题：** {entry.get('title', '无标题')}

**来源：** {entry.get('source', '未知')}

**链接：** {entry.get('link', '#')}

**发布时间：** {entry.get('published', '未知')}

**摘要：** {entry.get('summary', '无摘要')}

---

## 处置建议

"""
    
    if level == 'red':
        alert_content += """1. 立即上报主管部门和使领馆
2. 启动应急预案
3. 核实信息真实性
4. 评估人员安全状况
5. 准备撤离方案（如必要）
"""
    elif level == 'orange':
        alert_content += """1. 2 小时内上报主管部门
2. 密切关注事态发展
3. 加强安保措施
4. 准备应对方案
"""
    else:
        alert_content += """1. 记录在案
2. 纳入日报汇总
3. 持续跟踪
"""
    
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    
    filename = f"alert_{level}_{timestamp}.md"
    output_file = output_path / filename
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(alert_content)
    
    return str(output_file)


def main():
    parser = argparse.ArgumentParser(description='警报检测脚本')
    parser.add_argument('--keywords', required=True, help='项目关键词（逗号分隔）')
    parser.add_argument('--alert-terms', required=True, help='警报关键词（逗号分隔）')
    parser.add_argument('--output', required=True, help='输出目录')
    
    args = parser.parse_args()
    
    keywords = [k.strip() for k in args.keywords.split(',')]
    alert_terms = [t.strip() for t in args.alert_terms.split(',')]
    
    print(f"监测关键词：{keywords}")
    print(f"警报关键词：{alert_terms}")
    
    # 这里可以添加实际的采集逻辑
    # 目前作为框架，实际使用时需要集成到采集流程中
    
    print("警报检测完成")


if __name__ == '__main__':
    main()
