"""
DOCX 文档处理流程

整合目录提取、分类、全文提取、文本切分等步骤。
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, Optional

from ..interfaces import DocumentPipeline, DocumentSource
from ..config.provider import default_config_provider
from ..classification.hierarchy_classifier import HierarchyClassifier

from .toc_extractor import DocxTOCExtractor
from .full_text_extractor import DocxFullTextExtractor
from .text_splitter import DocxTextSplitter


class DocxPipeline(DocumentPipeline):
    """DOCX 文档处理流水线"""

    def __init__(self):
        self._cfg = default_config_provider
        self._toc_extractor = DocxTOCExtractor()
        self._full_text_extractor = DocxFullTextExtractor(
            paragraphs_per_page=int(self._cfg.get("toc_extraction.paragraphs_per_page", 30))
        )
        self._text_splitter = DocxTextSplitter()
        self._classifier = HierarchyClassifier()

    def run(
        self,
        source: DocumentSource,
        target_level: Optional[int] = None,
        max_chunk_size: Optional[int] = None,
        min_chunk_size: Optional[int] = None,
    ) -> Dict[str, Any]:
        """
        运行完整流程
        
        返回：
        {
            "toc_info": {...},
            "classification": {...},
            "chunks": [...],
            "meta": {...},
        }
        """
        # 从配置获取默认值
        if target_level is None:
            target_level = int(self._cfg.get("text_splitting.target_level", 1))
        if max_chunk_size is None:
            max_chunk_size = int(self._cfg.get("text_splitting.max_chunk_size", 3000))
        if min_chunk_size is None:
            min_chunk_size = int(self._cfg.get("text_splitting.min_chunk_size", 50))

        print(f"开始处理 DOCX 文档...")
        print(f"  目标层级: {target_level}")
        print(f"  最大块大小: {max_chunk_size}")
        print(f"  最小块大小: {min_chunk_size}")

        # 步骤1: 提取目录
        print("\n步骤1: 提取目录...")
        toc_info = self._toc_extractor.extract_toc(source)
        print(f"  提取到 {toc_info['toc_count']} 个目录项")

        # 步骤2: 分类目录项
        print("\n步骤2: 分类目录项...")
        classification = self._classifier.classify(toc_info["toc_items"], target_level)
        print(f"  分类完成，共 {classification['total_count']} 个目标层级项")

        # 步骤3: 提取全文
        print("\n步骤3: 提取全文...")
        pages_content = self._full_text_extractor.extract_full_text(source)
        print(f"  提取到 {len(pages_content)} 页内容")

        # 步骤4: 切分文本
        print("\n步骤4: 切分文本...")
        chunks = self._text_splitter.split_by_hierarchy(
            classification["items"],
            pages_content,
            toc_info,
            target_level,
            max_chunk_size,
            min_chunk_size,
        )
        print(f"  切分完成，共 {len(chunks)} 个块")

        # 填充文件名
        file_name = Path(source.path).name if source.path else "unknown.docx"
        for chunk in chunks:
            chunk["file_name"] = file_name

        return {
            "toc_info": toc_info,
            "classification": classification,
            "chunks": chunks,
            "meta": {
                "target_level": target_level,
                "max_chunk_size": max_chunk_size,
                "min_chunk_size": min_chunk_size,
                "file_type": "docx",
            },
        }
