#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
数据格式转换器

将现有的一/二/三级分类结果转换为统一文档结构
"""

from typing import Any, Dict, List, Optional

from .document_structure import (
    PrimaryClassification,
    SecondaryClassification,
    TertiaryClassification,
    TertiaryItem,
    UnifiedDocumentStructure,
)


class DocumentStructureConverter:
    """文档结构转换器"""

    @staticmethod
    def from_classification_results(
        primary_result: Dict[str, Any],
        secondary_result: Dict[str, Any],
        chunks: List[Dict[str, Any]],
        document_name: str = "",
        total_pages: int = 0
    ) -> UnifiedDocumentStructure:
        """
        从一/二级分类结果和chunks构建统一文档结构

        Args:
            primary_result: 一级分类结果（hierarchy_classifier 输出）
            secondary_result: 二级分类结果（hierarchy_classifier 输出）
            chunks: 文档切分后的chunks（包含 review_chunk_content）
            document_name: 文档名称
            total_pages: 总页数

        Returns:
            UnifiedDocumentStructure: 统一文档结构
        """
        # 创建一级分类列表
        primary_list = DocumentStructureConverter._parse_primary(primary_result)

        # 创建二级分类列表（从chunks中提取正文内容）
        secondary_list = DocumentStructureConverter._parse_secondary(
            secondary_result, chunks
        )

        # 初始化三级分类列表（为空，待后续填充）
        tertiary_list: List[TertiaryClassification] = []

        return UnifiedDocumentStructure(
            document_name=document_name,
            total_pages=total_pages,
            primary_classifications=primary_list,
            secondary_classifications=secondary_list,
            tertiary_classifications=tertiary_list
        )

    @staticmethod
    def _parse_primary(primary_result: Dict[str, Any]) -> List[PrimaryClassification]:
        """解析一级分类结果"""
        primary_list = []

        items = primary_result.get("items", [])
        for idx, item in enumerate(items, 1):
            primary_list.append(PrimaryClassification(
                first_seq=idx,
                first_code=item.get("category_code", ""),
                first_name=item.get("category", ""),
                page=int(item.get("page", 0)),
                level2_count=item.get("level2_count", 0),
                level2_titles=item.get("level2_titles", []),
                confidence=item.get("confidence", 0.0)
            ))

        return primary_list

    @staticmethod
    def _parse_secondary(
        secondary_result: Dict[str, Any],
        chunks: List[Dict[str, Any]]
    ) -> List[SecondaryClassification]:
        """解析二级分类结果，关联chunks中的正文内容"""
        secondary_list = []

        # 建立chunk索引：section_label -> content
        chunk_content_map = {}
        for chunk in chunks:
            section_label = chunk.get("section_label", "")
            content = chunk.get("review_chunk_content", "")
            if section_label and content:
                chunk_content_map[section_label] = content

        # 处理二级分类结果
        items = secondary_result.get("items", [])
        global_second_seq = 0

        for first_item in items:
            first_code = first_item.get("first_category_code", "")
            first_name = first_item.get("first_category", "")
            # 使用原始标题（如"第一章 编制依据"）来匹配chunks
            original_title = first_item.get("original_title", "") or first_name

            # 查找对应的一级seq
            first_seq = DocumentStructureConverter._get_first_seq(
                first_code, first_item.get("first_category", "")
            )

            classifications = first_item.get("classifications", [])
            for idx, cls in enumerate(classifications, 1):
                global_second_seq += 1

                second_code = cls.get("category_code", "")
                second_name = cls.get("category_name", "")
                title = cls.get("title", "")

                # 构建section_label来查找content（使用原始标题匹配chunks）
                section_label = f"{original_title}->{title}"
                content = chunk_content_map.get(section_label, "")

                secondary_list.append(SecondaryClassification(
                    first_seq=first_seq,
                    first_code=first_code,
                    first_name=first_name,
                    second_seq=global_second_seq,
                    second_code=second_code,
                    second_name=second_name,
                    second_content=content,
                    section_label=section_label,
                    metadata={
                        "raw_title": title,
                        "category_index": cls.get("category_index", 0)
                    }
                ))

        return secondary_list

    @staticmethod
    def _get_first_seq(first_code: str, first_name: str) -> int:
        """根据一级代码或名称获取序号"""
        # 标准顺序映射
        order_map = {
            "basis": 1,      # 编制依据
            "overview": 2,   # 工程概况
            "plan": 3,       # 施工计划
            "technology": 4, # 施工工艺技术
            "safety": 5,     # 安全保证措施
            "quality": 6,    # 质量保证措施
            "environment": 7,# 环境保证措施
            "management": 8, # 施工管理及作业人员配备与分工
            "acceptance": 9, # 验收要求
            "other": 10,     # 其它资料
        }

        if first_code in order_map:
            return order_map[first_code]

        # 尝试从名称推断
        name_map = {
            "编制依据": 1,
            "工程概况": 2,
            "施工计划": 3,
            "施工工艺技术": 4,
            "安全保证措施": 5,
            "质量保证措施": 6,
            "环境保证措施": 7,
            "施工管理及作业人员配备与分工": 8,
            "验收要求": 9,
            "其它资料": 10,
            "其他资料": 10,
        }

        return name_map.get(first_name, 99)

    @staticmethod
    def merge_tertiary_results(
        unified_structure: UnifiedDocumentStructure,
        tertiary_results: List[Dict[str, Any]]
    ) -> UnifiedDocumentStructure:
        """
        将三级分类结果合并到统一文档结构

        Args:
            unified_structure: 统一文档结构（已有一二级）
            tertiary_results: 三级分类结果列表

        Returns:
            UnifiedDocumentStructure: 更新后的结构
        """
        tertiary_list = []

        for sec in unified_structure.secondary_classifications:
            # 查找对应的三级分类结果
            tertiary_items = []

            for result in tertiary_results:
                # 匹配条件：second_code 相同
                if result.get("second_code") == sec.second_code:
                    details = result.get("tertiary_classification_details", [])

                    for idx, detail in enumerate(details, 1):
                        tertiary_items.append(TertiaryItem(
                            third_seq=idx,
                            third_code=detail.get("third_category_code", ""),
                            third_name=detail.get("third_category_name", ""),
                            line_start=detail.get("start_line", 0),
                            line_end=detail.get("end_line", 0),
                            content=detail.get("content", ""),
                            confidence=1.0  # LLM返回的默认置信度
                        ))

                    break  # 找到匹配项，跳出内层循环

            if tertiary_items:
                # 计算行数统计
                total_lines = len(sec.second_content.split('\n')) if sec.second_content else 0
                classified_lines = sum(
                    item.line_end - item.line_start + 1
                    for item in tertiary_items
                )

                tertiary_list.append(TertiaryClassification(
                    first_seq=sec.first_seq,
                    first_code=sec.first_code,
                    first_name=sec.first_name,
                    second_seq=sec.second_seq,
                    second_code=sec.second_code,
                    second_name=sec.second_name,
                    third_items=tertiary_items,
                    total_lines=total_lines,
                    classified_lines=classified_lines
                ))

        unified_structure.tertiary_classifications = tertiary_list
        return unified_structure


# ========== 便捷函数 ==========

def build_unified_structure(
    primary_result: Dict[str, Any],
    secondary_result: Dict[str, Any],
    chunks: List[Dict[str, Any]],
    document_name: str = "",
    total_pages: int = 0
) -> UnifiedDocumentStructure:
    """
    便捷函数：从一/二级结果构建统一文档结构

    Args:
        primary_result: 一级分类结果
        secondary_result: 二级分类结果
        chunks: 文档chunks（含正文）
        document_name: 文档名称
        total_pages: 总页数

    Returns:
        UnifiedDocumentStructure: 统一文档结构
    """
    return DocumentStructureConverter.from_classification_results(
        primary_result=primary_result,
        secondary_result=secondary_result,
        chunks=chunks,
        document_name=document_name,
        total_pages=total_pages
    )


def merge_tertiary_to_structure(
    unified_structure: UnifiedDocumentStructure,
    tertiary_results: List[Dict[str, Any]]
) -> UnifiedDocumentStructure:
    """
    便捷函数：将三级分类结果合并到统一结构

    Args:
        unified_structure: 统一文档结构
        tertiary_results: 三级分类结果

    Returns:
        UnifiedDocumentStructure: 更新后的结构
    """
    return DocumentStructureConverter.merge_tertiary_results(
        unified_structure, tertiary_results
    )
