"""模板 → 有序章节规格映射(Phase 5)。 真实 ParsedTemplate.sections 为 ChapterMarker 列表;章节由 type=="heading" 起, 紧随其后的 type=="placeholder" 且形如 `section:` 的标记归属该章, 用于确定 chapter_id 与 section_placeholder(语言无关、按文档顺序)。 """ from __future__ import annotations import re from genesis.data_models import ParsedTemplate from genesis.writer.models import ChapterSpec _SECTION_RE = re.compile(r"^section:(.+)$", re.IGNORECASE) def map_template(parsed: ParsedTemplate) -> list[ChapterSpec]: specs: list[ChapterSpec] = [] idx = 0 current: ChapterSpec | None = None for ch in getattr(parsed, "sections", []): t = getattr(ch, "type", None) if t == "heading": idx += 1 current = ChapterSpec( chapter_id=f"chapter_{idx}", title=getattr(ch, "name", ""), section_placeholder=None ) specs.append(current) elif t == "placeholder" and current is not None: m = _SECTION_RE.match(getattr(ch, "name", "")) if m: sid = m.group(1) current.section_placeholder = getattr(ch, "name", "") if current.chapter_id.startswith("chapter_"): current.chapter_id = sid return specs