"""Rebuild document text from processed blocks.""" from __future__ import annotations from app.engine.models import DocumentBlock def stitch_blocks(blocks: list[DocumentBlock]) -> str: """Join blocks preserving blank lines and non-rewriteable sections.""" if not blocks: return "" parts: list[str] = [] for i, block in enumerate(blocks): if block.kind == "blank": # Represented as paragraph separator; avoid stacking too many if parts and not parts[-1].endswith("\n\n"): if parts[-1] and not parts[-1].endswith("\n"): parts.append("\n\n") elif parts[-1].endswith("\n") and not parts[-1].endswith("\n\n"): parts.append("\n") continue text = block.text or "" if i > 0 and parts and not parts[-1].endswith("\n"): # Separate consecutive non-blank blocks with blank line if both are paras/headings prev = blocks[i - 1] if prev.kind != "blank": parts.append("\n\n") parts.append(text) out = "".join(parts) out = out.replace("\n\n\n\n", "\n\n").strip() return out def join_sentences(sentences: list[str]) -> str: return " ".join(s.strip() for s in sentences if s and s.strip())