"""
从 PDF 提取结构构造 toc_items，供 hierarchy_classifier 使用。
"""

from typing import Dict, Any, List

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


def build_toc_items_from_structure(structure: Dict[str, Any]) -> List[Dict[str, Any]]:
    """
    将 PdfStructureExtractor 的输出转换为 hierarchy_classifier 所需的 toc_items 格式。

    Returns:
        [
            {"title": "第一章 xxx", "page": 1, "level": 1, "original": "第一章 xxx"},
            {"title": "一、xxx", "page": 2, "level": 2, "original": "一、xxx"},
            ...
        ]
    """
    toc_items: List[Dict[str, Any]] = []
    for chapter_title, sections in structure.get("chapters", {}).items():
        page_start = min(s["page_start"] for s in sections.values()) if sections else 1
        toc_items.append({
            "title": chapter_title,
            "page": page_start,
            "level": 1,
            "original": chapter_title,
        })
        for section_title, section_data in sections.items():
            if section_title == "章节标题":
                continue
            toc_items.append({
                "title": section_title,
                "page": section_data["page_start"],
                "level": 2,
                "original": section_title,
            })

    logger.info(f"[TocBuilder] 构造完成，共 {len(toc_items)} 个目录项")
    return toc_items
