"""
pdf_worker_adapter - 简化版

使用 splitter_pdf.py 的严格正则匹配逻辑，移除复杂组件。
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional

from foundation.observability.logger.loggering import review_logger as logger

from ..classification.chunk_classifier import ChunkClassifier
from ..classification.hierarchy_classifier import HierarchyClassifier
from ..config.provider import default_config_provider
from ..interfaces import DocumentPipeline, DocumentSource, FileParseFacade, FullTextExtractor, ResultWriter
from ..pipeline import DefaultDocumentPipeline, DefaultFileParseFacade, PipelineComponents
from .fulltext_extractor import PdfFullTextExtractor
from .hybrid_extractor import HybridFullTextExtractor
from .ocr_enhanced_extractor import OcrEnhancedExtractor
from .json_writer import PdfJsonResultWriter
from .text_splitter import PdfTextSplitter
from .toc_extractor import PdfTOCExtractor


@dataclass
class PdfWorkerConfig:
    """PDF处理配置"""
    writers: Optional[List[ResultWriter]] = None
    expected_chapters: Optional[List[str]] = None
    enable_validation: bool = True
    use_ocr: bool = True  # 默认启用 OCR（表格页识别）
    ocr_mode: str = "enhanced"  # OCR 模式: "enhanced" (推荐) 或 "hybrid"


def build_pdf_facade(config: Optional[PdfWorkerConfig] = None) -> FileParseFacade:
    """
    构建 PDF 处理门面

    提取模式：
    - 默认: PyMuPDF 本地提取（无OCR，章节切分最稳定）
    - OCR enhanced: 先 PyMuPDF 提取全部，再对表格页 OCR 替换（推荐）
    - OCR hybrid: 检测表格页，表格页直接 OCR（可能破坏章节格式）

    Args:
        config: 配置对象
            - use_ocr=True 启用 OCR
            - ocr_mode="enhanced" (推荐，稳定) 或 "hybrid"
    """
    if config is None:
        config = PdfWorkerConfig()

    writers: List[ResultWriter] = config.writers or [PdfJsonResultWriter()]

    # 选择提取器
    if config.use_ocr:
        if config.ocr_mode == "enhanced":
            logger.info("使用 OCR 增强模式（推荐）：PyMuPDF + 表格页 OCR 替换")
            extractor: FullTextExtractor = OcrEnhancedExtractor()
        else:
            logger.info("使用 OCR 混合模式：表格页直接 OCR")
            extractor = HybridFullTextExtractor()
    else:
        logger.info("使用本地提取模式（PyMuPDF）")
        extractor = PdfFullTextExtractor()

    components = PipelineComponents(
        config=default_config_provider,
        toc_extractor=PdfTOCExtractor(),
        classifier=HierarchyClassifier(),
        fulltext_extractor=extractor,
        splitter=PdfTextSplitter(
            enable_validation=config.enable_validation,
            expected_chapters=config.expected_chapters or []
        ),
        writers=writers,
        chunk_classifier=ChunkClassifier(),
    )

    pipeline: DocumentPipeline = DefaultDocumentPipeline(components)
    facade: FileParseFacade = DefaultFileParseFacade(pipeline)
    return facade


# 别名，保持兼容性
build_hybrid_facade = build_pdf_facade


def extract_and_split(
    pdf_path: str,
    expected_chapters: Optional[List[str]] = None,
    enable_validation: bool = True
) -> Dict[str, Any]:
    """
    直接提取PDF章节（便捷函数）

    Args:
        pdf_path: PDF文件路径
        expected_chapters: 期望章节列表（用于检查缺失）
        enable_validation: 是否启用章节验证

    Returns:
        {
            "chunks": [...],  # 内容块列表
            "validation_report": {...},  # 验证报告
            "toc_info": {...},
            "classification": {...},
        }
    """
    from pathlib import Path

    config = PdfWorkerConfig(
        expected_chapters=expected_chapters,
        enable_validation=enable_validation
    )

    facade = build_pdf_facade(config)

    result = facade.process_file(
        file_path=pdf_path,
        target_level=1,
        max_chunk_size=10000,
        min_chunk_size=10,
    )

    # 获取验证报告
    # 注意：splitter 中的验证结果需要通过其他方式获取
    # 这里简化处理，只返回基本结果

    return result
