"""
数据分析与智能筛选模块
- 批量爬取
- Excel 导出
- LLM 智能筛选
- 综述生成
"""

import json
import asyncio
from pathlib import Path
from typing import List, Optional, Dict, Any
from datetime import datetime

from .models import ProjectInfo, SearchResults


class DataExporter:
    """数据导出器"""
    
    @staticmethod
    def to_excel(results: SearchResults, filepath: str) -> str:
        """导出为 Excel 文件"""
        try:
            import openpyxl
            from openpyxl.styles import Font, Alignment, PatternFill
        except ImportError:
            raise ImportError("请安装 openpyxl: pip install openpyxl")
        
        wb = openpyxl.Workbook()
        ws = wb.active
        if ws is None:
            ws = wb.create_sheet("国自然项目")
        else:
            ws.title = "国自然项目"
        
        # 表头
        headers = [
            "序号", "项目名称", "负责人", "依托单位", "项目类别",
            "资助金额(万)", "批准年度", "结题年度", "关键词", "中文摘要", "结题摘要"
        ]
        
        # 表头样式
        header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
        header_font = Font(color="FFFFFF", bold=True)
        
        for col, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col, value=header)
            cell.fill = header_fill
            cell.font = header_font
            cell.alignment = Alignment(horizontal="center")
        
        # 数据行
        for idx, proj in enumerate(results.projects, 1):
            ws.cell(row=idx+1, column=1, value=idx)
            ws.cell(row=idx+1, column=2, value=proj.project_name)
            ws.cell(row=idx+1, column=3, value=proj.project_leader)
            ws.cell(row=idx+1, column=4, value=proj.institution)
            ws.cell(row=idx+1, column=5, value=proj.project_type or "")
            ws.cell(row=idx+1, column=6, value=proj.funding_amount or "")
            ws.cell(row=idx+1, column=7, value=proj.approval_year or "")
            ws.cell(row=idx+1, column=8, value=proj.end_year or "")
            ws.cell(row=idx+1, column=9, value=proj.keywords or "")
            ws.cell(row=idx+1, column=10, value=proj.abstract_cn or "")
            ws.cell(row=idx+1, column=11, value=proj.conclusion_abstract or "")
        
        # 调整列宽
        ws.column_dimensions['A'].width = 6
        ws.column_dimensions['B'].width = 50
        ws.column_dimensions['C'].width = 10
        ws.column_dimensions['D'].width = 30
        ws.column_dimensions['E'].width = 15
        ws.column_dimensions['F'].width = 12
        ws.column_dimensions['G'].width = 10
        ws.column_dimensions['H'].width = 10
        ws.column_dimensions['I'].width = 40
        ws.column_dimensions['J'].width = 60
        ws.column_dimensions['K'].width = 60
        
        wb.save(filepath)
        return filepath
    
    @staticmethod
    def to_csv(results: SearchResults, filepath: str) -> str:
        """导出为 CSV 文件"""
        import csv
        
        with open(filepath, 'w', encoding='utf-8-sig', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([
                "序号", "项目名称", "负责人", "依托单位", "项目类别",
                "资助金额(万)", "批准年度", "结题年度", "关键词", "中文摘要", "结题摘要"
            ])
            
            for idx, proj in enumerate(results.projects, 1):
                writer.writerow([
                    idx,
                    proj.project_name,
                    proj.project_leader,
                    proj.institution,
                    proj.project_type or "",
                    proj.funding_amount or "",
                    proj.approval_year or "",
                    proj.end_year or "",
                    proj.keywords or "",
                    proj.abstract_cn or "",
                    proj.conclusion_abstract or ""
                ])
        
        return filepath


class DataAnalyzer:
    """数据分析器"""
    
    @staticmethod
    def analyze(results: SearchResults) -> Dict[str, Any]:
        """分析项目数据，返回统计信息"""
        projects = results.projects
        
        if not projects:
            return {"error": "无数据"}
        
        # 按年度统计
        year_dist = {}
        for p in projects:
            year = p.approval_year or "未知"
            year_dist[year] = year_dist.get(year, 0) + 1
        
        # 按单位统计
        inst_dist = {}
        for p in projects:
            inst = p.institution
            inst_dist[inst] = inst_dist.get(inst, 0) + 1
        
        # 按类别统计
        type_dist = {}
        for p in projects:
            ptype = p.project_type or "未知"
            type_dist[ptype] = type_dist.get(ptype, 0) + 1
        
        # 关键词提取
        all_keywords = []
        for p in projects:
            if p.keywords:
                kws = [k.strip() for k in p.keywords.replace("；", ";").split(";")]
                all_keywords.extend(kws)
        
        keyword_freq = {}
        for kw in all_keywords:
            if kw:
                keyword_freq[kw] = keyword_freq.get(kw, 0) + 1
        
        # 排序
        top_keywords = sorted(keyword_freq.items(), key=lambda x: x[1], reverse=True)[:20]
        top_institutions = sorted(inst_dist.items(), key=lambda x: x[1], reverse=True)[:10]
        
        return {
            "total_projects": len(projects),
            "year_distribution": dict(sorted(year_dist.items())),
            "type_distribution": type_dist,
            "top_institutions": top_institutions,
            "top_keywords": top_keywords,
        }
    
    @staticmethod
    def print_analysis(analysis: Dict[str, Any]):
        """打印分析结果"""
        print("\n" + "=" * 50)
        print("  数据分析报告")
        print("=" * 50)
        
        print(f"\n📊 项目总数: {analysis.get('total_projects', 0)}")
        
        print("\n📅 年度分布:")
        for year, count in analysis.get('year_distribution', {}).items():
            print(f"   {year}: {count} 项")
        
        print("\n📁 类别分布:")
        for ptype, count in analysis.get('type_distribution', {}).items():
            print(f"   {ptype}: {count} 项")
        
        print("\n🏛️ Top 10 依托单位:")
        for inst, count in analysis.get('top_institutions', []):
            print(f"   {inst}: {count} 项")
        
        print("\n🔑 Top 20 关键词:")
        for kw, count in analysis.get('top_keywords', []):
            print(f"   {kw}: {count} 次")
