"""
结果保存模块
保存分类和切分结果到多种格式
"""

import json
from pathlib import Path
from datetime import datetime
from collections import defaultdict, Counter

try:
    from ..config.config_loader import get_config
except ImportError:
    from config.config_loader import get_config


class ResultSaver:
    """结果保存器"""
    
    def __init__(self):
        self.config = get_config()
    
    def save_all(self, file_path, toc_info, classification_result, chunks, output_dir):
        """
        保存所有结果
        
        参数:
            file_path: 源文件路径
            toc_info: 目录信息
            classification_result: 分类结果
            chunks: 文本块列表
            output_dir: 输出目录
            
        返回:
            dict: 保存的文件路径
        """
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        saved_files = {}
        
        # 保存完整JSON
        json_file = self._save_json(file_path, toc_info, classification_result, chunks, output_dir)
        saved_files['json'] = json_file
        
        # 按类别保存文本块
        print("\n按类别保存文本块:")
        category_files = self._save_by_category(chunks, file_path, output_dir)
        saved_files['category_files'] = category_files
        
        # 创建索引
        index_file = self._create_index(chunks, file_path, output_dir)
        saved_files['index'] = index_file
        
        # 保存统计报告
        report_file = self._save_report(file_path, toc_info, classification_result, chunks, output_dir)
        saved_files['report'] = report_file
        
        return saved_files
    
    def _save_json(self, file_path, toc_info, classification_result, chunks, output_dir):
        """保存完整的分类和切分结果到JSON"""
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        file_name = Path(file_path).stem
        
        json_file = output_path / f"{file_name}_完整结果_{timestamp}.json"
        
        # 构建完整目录列表（提取和校对后的）
        complete_toc_list = []
        for idx, item in enumerate(toc_info['toc_items'], 1):
            toc_entry = {
                'index': idx,
                'title': item['title'],
                'page': item['page'],
                'level': item['level'],  # 目录层级
                'original': item['original']
            }
            complete_toc_list.append(toc_entry)
        
        output_data = {
            'source_file': str(file_path),
            'process_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'toc_summary': {
                'total_items': toc_info['toc_count'],
                'toc_pages': toc_info['toc_pages']
            },
            'complete_toc_list': complete_toc_list,  # 新增：完整目录列表（按顺序，带层级）
            'classification': classification_result,
            'chunks': chunks
        }
        
        with open(json_file, 'w', encoding='utf-8') as f:
            json.dump(output_data, f, ensure_ascii=False, indent=2)
        
        print(f"已保存完整结果JSON: {json_file}")
        return str(json_file)
    
    def _save_by_category(self, chunks, file_path, output_dir):
        """按类别保存文本块到独立的Markdown文件"""
        output_path = Path(output_dir)
        file_name = Path(file_path).stem
        
        # 按类别分组
        category_groups = defaultdict(list)
        for chunk in chunks:
            category = chunk['project_plan_type']
            category_groups[category].append(chunk)
        
        saved_files = {}
        
        # 为每个类别创建子文件夹并保存文件
        for category, category_chunks in category_groups.items():
            category_dir = output_path / self._sanitize_filename(category)
            category_dir.mkdir(parents=True, exist_ok=True)
            
            category_files = []
            
            # 为每个文本块创建一个MD文件
            for i, chunk in enumerate(category_chunks, 1):
                section_label = chunk['section_label']
                safe_label = self._sanitize_filename(section_label)
                
                md_filename = f"{i:03d}_{safe_label}.md"
                md_file = category_dir / md_filename
                
                with open(md_file, 'w', encoding='utf-8') as f:
                    f.write(f"# {section_label}\n\n")
                    f.write(f"**类别**: {category}\n\n")
                    f.write(f"**来源文件**: {chunk['file_name']}\n\n")
                    f.write(f"**页码**: {chunk['element_tag']['page']}\n\n")
                    f.write(f"**块ID**: {chunk['chunk_id']}\n\n")
                    f.write(f"**字符数**: {len(chunk['review_chunk_content'])}\n\n")
                    f.write("---\n\n")
                    f.write(chunk['review_chunk_content'])
                    
                    if not chunk['review_chunk_content'].endswith('\n'):
                        f.write('\n')
                
                category_files.append(str(md_file))
            
            saved_files[category] = category_files
            print(f"  [{category}] 保存了 {len(category_files)} 个文件到: {category_dir}")
        
        return saved_files
    
    def _create_index(self, chunks, file_path, output_dir):
        """创建按类别分组的索引文件"""
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        file_name = Path(file_path).stem
        index_file = output_path / "README.md"
        
        # 按类别分组
        category_groups = defaultdict(list)
        for chunk in chunks:
            category_groups[chunk['project_plan_type']].append(chunk)
        
        with open(index_file, 'w', encoding='utf-8') as f:
            f.write(f"# {file_name} - 分类切分结果索引\n\n")
            f.write(f"**来源文件**: {Path(file_path).name}\n\n")
            f.write(f"**处理时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            f.write(f"**文本块总数**: {len(chunks)}\n\n")
            f.write(f"**类别数量**: {len(category_groups)}\n\n")
            
            # 统计信息
            total_chars = sum(len(chunk['review_chunk_content']) for chunk in chunks)
            f.write(f"**总字符数**: {total_chars}\n\n")
            
            f.write("---\n\n")
            f.write("## 分类统计\n\n")
            
            # 按类别统计
            for category, category_chunks in sorted(category_groups.items()):
                category_chars = sum(len(chunk['review_chunk_content']) for chunk in category_chunks)
                f.write(f"- **{category}**: {len(category_chunks)} 个文本块, {category_chars} 字符\n")
            
            f.write("\n---\n\n")
            f.write("## 详细目录\n\n")
            
            # 按类别输出详细目录
            for category, category_chunks in sorted(category_groups.items()):
                f.write(f"### {category}\n\n")
                
                for i, chunk in enumerate(category_chunks, 1):
                    section_label = chunk['section_label']
                    safe_label = self._sanitize_filename(section_label)
                    category_safe = self._sanitize_filename(category)
                    md_filename = f"{i:03d}_{safe_label}.md"
                    
                    char_count = len(chunk['review_chunk_content'])
                    page = chunk['element_tag']['page']
                    
                    f.write(f"{i}. [{section_label}]({category_safe}/{md_filename}) - 页码: {page}, 字符数: {char_count}\n")
                
                f.write("\n")
        
        print(f"已保存索引文件: {index_file}")
        return str(index_file)
    
    def _save_report(self, file_path, toc_info, classification_result, chunks, output_dir):
        """保存详细的统计报告"""
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        file_name = Path(file_path).stem
        
        report_file = output_path / f"{file_name}_统计报告_{timestamp}.txt"
        
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write("=" * 100 + "\n")
            f.write("文档分类切分统计报告\n")
            f.write("=" * 100 + "\n\n")
            
            f.write(f"源文件: {Path(file_path).name}\n")
            f.write(f"处理时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            
            # 目录统计
            f.write("=" * 100 + "\n")
            f.write("目录提取统计\n")
            f.write("=" * 100 + "\n\n")
            f.write(f"目录项总数: {toc_info['toc_count']}\n")
            f.write(f"目录所在页: {', '.join(map(str, toc_info['toc_pages']))}\n\n")
            
            # 层级统计
            level_counts = Counter([item['level'] for item in toc_info['toc_items']])
            f.write("目录层级分布:\n")
            for level in sorted(level_counts.keys()):
                f.write(f"  {level}级: {level_counts[level]} 项\n")
            f.write("\n")
            
            # 分类统计
            if classification_result:
                f.write("=" * 100 + "\n")
                f.write("分类统计\n")
                f.write("=" * 100 + "\n\n")
                
                category_counts = Counter([item['category'] for item in classification_result['items']])
                f.write(f"已分类项数: {classification_result['total_count']}\n")
                f.write(f"分类数量: {len(category_counts)}\n\n")
                
                f.write("各类别统计:\n")
                for category, count in sorted(category_counts.items(), key=lambda x: x[1], reverse=True):
                    f.write(f"  {category}: {count} 项\n")
                f.write("\n")
            
            # 文本块统计
            f.write("=" * 100 + "\n")
            f.write("文本块切分统计\n")
            f.write("=" * 100 + "\n\n")
            
            f.write(f"文本块总数: {len(chunks)}\n\n")
            
            total_chars = sum(len(chunk['review_chunk_content']) for chunk in chunks)
            avg_chars = total_chars / len(chunks) if chunks else 0
            
            f.write(f"总字符数: {total_chars}\n")
            f.write(f"平均每块字符数: {avg_chars:.1f}\n\n")
            
            # 按类别统计文本块
            category_groups = defaultdict(list)
            for chunk in chunks:
                category_groups[chunk['project_plan_type']].append(chunk)
            
            f.write("按类别统计:\n")
            for category, category_chunks in sorted(category_groups.items()):
                category_chars = sum(len(chunk['review_chunk_content']) for chunk in category_chunks)
                f.write(f"  {category}: {len(category_chunks)} 块, {category_chars} 字符\n")
            f.write("\n")
            
            # 详细列表
            f.write("=" * 100 + "\n")
            f.write("文本块详细列表\n")
            f.write("=" * 100 + "\n\n")
            
            for category, category_chunks in sorted(category_groups.items()):
                f.write(f"\n【{category}】\n")
                f.write("-" * 100 + "\n")
                
                for i, chunk in enumerate(category_chunks, 1):
                    char_count = len(chunk['review_chunk_content'])
                    page = chunk['element_tag']['page']
                    f.write(f"  [{i}] {chunk['section_label']}\n")
                    f.write(f"      页码: {page}, 字符数: {char_count}, 块ID: {chunk['chunk_id']}\n")
        
        print(f"已保存统计报告: {report_file}")
        return str(report_file)
    
    def _sanitize_filename(self, filename):
        """清理文件名，移除或替换不合法字符"""
        invalid_chars = r'<>:"/\|?*'
        for char in invalid_chars:
            filename = filename.replace(char, '_')
        
        filename = filename.strip()
        
        # 从配置读取最大文件名长度
        max_length = self.config.max_filename_length
        if len(filename) > max_length:
            filename = filename[:max_length]
        
        return filename

