#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ChunksConverter：chunks 格式与 SectionContent 格式的转换器
"""

import re
from typing import Any, Dict, List, Tuple

from .models import ClassificationResult, SectionContent
from .category_loaders import CategoryStandardLoader


class ChunksConverter:
    """chunks 格式与 SectionContent 格式的转换器"""

    def __init__(self, category_loader: CategoryStandardLoader):
        self.category_loader = category_loader

    def chunks_to_sections(self, chunks: List[Dict[str, Any]]) -> List[SectionContent]:
        """
        将 chunks 列表转换为 SectionContent 列表

        分组策略：
        1. 优先按 section_label 分组（更精确的文档结构）
        2. 如果 section_label 相同，再按一级分类分组
        3. 从 section_label 提取二级分类名称用于匹配三级标准

        Args:
            chunks: 文档分块列表，每个 chunk 需包含:
                - chapter_classification: 一级分类代码
                - secondary_category_code: 二级分类代码（可能为 none）
                - secondary_category_cn: 二级分类中文名
                - review_chunk_content 或 content: 内容文本
                - section_label: 章节标签（如 "第一章编制依据->一、法律法规"）

        Returns:
            List[SectionContent]: 二级标题段落列表
        """
        # 按 section_label 分组（更精确）
        # section_label 格式: "第一章编制依据->一、法律法规"
        section_groups: Dict[str, List[Dict]] = {}

        for chunk in chunks:
            # 获取分类信息
            section_label = chunk.get("section_label", "") or chunk.get("chapter", "")
            first_code = chunk.get("chapter_classification", "") or chunk.get("first_code", "")
            second_code = chunk.get("secondary_category_code", "") or chunk.get("second_code", "")
            second_cn = chunk.get("secondary_category_cn", "") or chunk.get("second_name", "")

            # 分组策略：每个二级分类独立分组，禁止合并不同二级分类
            # 优先使用 section_label，其次使用 secondary_category_code
            if section_label and "->" in section_label:
                # 有明确的章节标签，使用它作为分组键
                group_key = section_label
            elif second_code and second_code not in ("none", "None", ""):
                # 有二级分类代码，按二级分类独立分组（关键：不再合并到一级分类下）
                group_key = f"{first_code}->{second_code}"
            elif section_label:
                group_key = section_label
            else:
                # 完全没有分类信息，使用唯一键避免合并
                group_key = f"unknown_{first_code}_{id(chunk)}"

            if group_key not in section_groups:
                section_groups[group_key] = []
            section_groups[group_key].append(chunk)

        # 为每个分组创建 SectionContent
        section_contents = []
        all_lines = []  # 全局行号追踪

        for group_key, group_chunks in section_groups.items():
            if not group_chunks:
                continue

            # 合并该分组的所有内容，同时记录每个原始 chunk 的行范围
            section_lines = []
            chunk_line_counts: List[Tuple[str, int]] = []  # (chunk_id, line_count)
            for chunk in group_chunks:
                content = chunk.get("review_chunk_content", "") or chunk.get("content", "") or chunk.get("original_content", "")
                if content:
                    lines = content.split('\n')
                    n = len(lines)
                    chunk_id = chunk.get("chunk_id") or chunk.get("id") or str(id(chunk))
                    chunk_line_counts.append((chunk_id, n))
                    section_lines.extend(lines)
                    all_lines.extend(lines)
                else:
                    chunk_id = chunk.get("chunk_id") or chunk.get("id") or str(id(chunk))
                    chunk_line_counts.append((chunk_id, 0))

            if not section_lines:
                continue

            # 获取一级分类代码
            first_code = group_chunks[0].get("chapter_classification", "") or group_chunks[0].get("first_code", "")

            # 获取二级分类名称和代码
            second_code = group_chunks[0].get("secondary_category_code", "") or group_chunks[0].get("second_code", "")
            second_cn = group_chunks[0].get("secondary_category_cn", "") or group_chunks[0].get("second_name", "")

            # 从 section_label 提取二级分类名称（优先）
            section_label = group_chunks[0].get("section_label", "") or group_chunks[0].get("chapter", "")
            if "->" in section_label:
                parts = section_label.split("->")
                if len(parts) >= 2:
                    extracted = parts[1].strip()
                    # 去除序号前缀（如 "一、" "二、"）
                    cleaned = re.sub(r'^[一二三四五六七八九十]+[、）\s]+', '', extracted).strip()
                    if cleaned:
                        second_cn = cleaned
                        # 尝试根据提取的名称匹配二级分类代码
                        matched_standards = self.category_loader.get_standards_by_second_name(cleaned)
                        if matched_standards:
                            second_code = matched_standards[0].second_code

            # 构建带行号的内容
            start_line = len(all_lines) - len(section_lines) + 1
            line_number_map = list(range(start_line, len(all_lines) + 1))
            numbered_lines = []
            for i, line in enumerate(section_lines):
                numbered_lines.append(f"<{line_number_map[i]}> {line}")
            numbered_content = '\n'.join(numbered_lines)

            # 计算每个原始 chunk 在全局行号中的范围
            chunk_ranges: List[Tuple[str, int, int]] = []
            current_global = start_line
            for chunk_id, n_lines in chunk_line_counts:
                if n_lines > 0:
                    chunk_ranges.append((chunk_id, current_global, current_global + n_lines - 1))
                    current_global += n_lines

            # 获取三级分类标准
            category_standards = self.category_loader.get_standards_by_second_code(second_code)
            if not category_standards:
                category_standards = self.category_loader.get_standards_by_second_name(second_cn)

            # 构建 section_key（使用 group_key 保留 section_label 信息，粒度更细）
            section_key = group_key

            section_contents.append(SectionContent(
                section_key=section_key,
                section_name=second_cn or second_code,
                lines=section_lines,
                numbered_content=numbered_content,
                category_standards=category_standards,
                line_number_map=line_number_map,
                chunk_ranges=chunk_ranges
            ))

        return section_contents

    def classification_result_to_chunks(
        self,
        result: ClassificationResult,
        original_chunks: List[Dict[str, Any]],
        first_code: str,
        second_code: str
    ) -> List[Dict[str, Any]]:
        """
        将 ClassificationResult 转换回 chunks 格式

        将行级分类结果展开，为每个三级分类创建对应的 chunk 条目

        Args:
            result: 分类结果
            original_chunks: 原始 chunks（用于保留其他字段）
            first_code: 一级分类代码
            second_code: 二级分类代码

        Returns:
            List[Dict]: 更新后的 chunks 列表
        """
        updated_chunks = []

        # 收集所有三级分类信息，过滤掉非标准项（no_standard）
        tertiary_classifications = []
        for content in result.classified_contents:
            # 跳过非标准项，不纳入三级分类统计
            if content.third_category_code == "no_standard":
                continue
            tertiary_classifications.append({
                "third_category_name": content.third_category_name,
                "third_category_code": content.third_category_code,
                "start_line": content.start_line,
                "end_line": content.end_line,
                "content": content.content
            })

        # 更新原始 chunks
        for chunk in original_chunks:
            updated_chunk = dict(chunk)
            updated_chunk["first_code"] = first_code
            updated_chunk["second_code"] = second_code

            # 添加三级分类详情列表
            updated_chunk["tertiary_classification_details"] = tertiary_classifications

            # 如果有三级分类结果，设置第一个作为主要分类（向后兼容）
            if tertiary_classifications:
                updated_chunk["tertiary_category_code"] = tertiary_classifications[0]["third_category_code"]
                updated_chunk["tertiary_category_cn"] = tertiary_classifications[0]["third_category_name"]

            updated_chunks.append(updated_chunk)

        return updated_chunks
