"""
PDF 目录提取实现（基于 file_parse 接口）

只处理 PDF，不依赖 doc_worker。
"""

from __future__ import annotations

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

import fitz  # PyMuPDF

from ..config.provider import default_config_provider
from ..interfaces import DocumentSource, TOCExtractor
from ..utils.toc_level_identifier import TOCLevelIdentifier
from ..utils.toc_pattern_matcher import TOCPatternMatcher


class PdfTOCExtractor(TOCExtractor):
    """PDF 目录提取实现。"""

    def __init__(self) -> None:
        self._cfg = default_config_provider
        self._matcher = TOCPatternMatcher()
        self._level_identifier = TOCLevelIdentifier()

    def extract_toc(self, source: DocumentSource) -> Dict[str, Any]:
        max_pages = int(self._cfg.get("toc_extraction.max_pages", 15))
        pages_text = self._extract_pdf_pages(source, max_pages=max_pages)

        all_toc_items: List[Dict[str, Any]] = []
        toc_page_nums: List[int] = []

        for page in pages_text:
            items = self._matcher.detect_toc_patterns(page["text"])
            if items:
                all_toc_items.extend(items)
                toc_page_nums.append(page["page_num"])

        # 去重
        unique_toc: List[Dict[str, Any]] = []
        seen = set()
        for item in all_toc_items:
            key = (item["title"], item["page"])
            if key in seen:
                continue
            seen.add(key)
            unique_toc.append(item)

        # 识别层级
        unique_toc = self._level_identifier.identify_levels(unique_toc)

        return {
            "toc_items": unique_toc,
            "toc_count": len(unique_toc),
            "toc_pages": toc_page_nums,
        }

    def _extract_pdf_pages(self, source: DocumentSource, max_pages: int) -> List[Dict[str, Any]]:
        if source.content is not None:
            doc = fitz.open(stream=source.content)
        elif source.path is not None:
            doc = fitz.open(source.path)
        else:
            raise ValueError("DocumentSource 既没有 path 也没有 content")

        pages: List[Dict[str, Any]] = []
        try:
            for page_num in range(min(len(doc), max_pages)):
                page = doc[page_num]
                text = page.get_text()
                pages.append({"page_num": page_num + 1, "text": text})
        finally:
            doc.close()
        return pages







