"""层级序号格式 check。"""

import re
from fastapi_modules.fastapi_leaudit.govdoc_engine.engine.checks import register
from fastapi_modules.fastapi_leaudit.govdoc_engine.engine.checks.base import CheckBase, CheckContext, CheckHit, CheckResult


@register("hierarchy")
class HierarchyCheck(CheckBase):
    """检查层级序号格式：
    - expected_order: 各级允许的模式（正向白名单，按 level 升序）
    - forbid_patterns: 禁用模式（黑名单，命中即报错）
    """

    def run(self, ctx: CheckContext) -> CheckResult:
        forbid = [re.compile(p) for p in (ctx.stage.forbid_patterns or [])]
        hits: list[CheckHit] = []
        for p in ctx.paragraphs:
            text = p.text.strip()
            for f in forbid:
                m = f.search(text)
                if m:
                    hits.append(CheckHit(
                        paragraph=p, char_start=m.start(), char_end=m.end(),
                        actual={"text": m.group(0)},
                        expected={"forbid_pattern": f.pattern},
                        message=f"层级序号格式错误：命中禁用模式 {f.pattern}",
                    ))
        return CheckResult(passed=not hits, hits=hits)
