"""applies_to → 段落集合。"""

from __future__ import annotations
from fastapi_modules.fastapi_leaudit.govdoc_engine.models import Document, Paragraph
from fastapi_modules.fastapi_leaudit.govdoc_engine.dsl.schema import AppliesTo


def select_paragraphs(doc: Document, applies_to: AppliesTo) -> list[Paragraph]:
    if applies_to.paragraph_index is not None:
        idx = applies_to.paragraph_index
        if 0 <= idx < len(doc.paragraphs):
            return [doc.paragraphs[idx]]
        return []

    if applies_to.role == "any":
        return list(doc.paragraphs)

    targets: set[str] = set()
    if applies_to.role:
        targets.add(applies_to.role)
    if applies_to.roles:
        targets.update(applies_to.roles)

    if not targets:
        return list(doc.paragraphs)

    return [p for p in doc.paragraphs if p.role in targets]
