"""regex_require / regex_forbid。"""

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("regex_require")
class RegexRequireCheck(CheckBase):
    def run(self, ctx: CheckContext) -> CheckResult:
        pat = re.compile(ctx.stage.pattern or "")
        hits: list[CheckHit] = []
        for p in ctx.paragraphs:
            if not pat.search(p.text):
                hits.append(CheckHit(
                    paragraph=p, char_start=0, char_end=len(p.text),
                    actual={"text": p.text}, expected={"pattern": ctx.stage.pattern},
                    message=f"未匹配模式 {ctx.stage.pattern}",
                ))
        return CheckResult(passed=not hits, hits=hits)


@register("regex_forbid")
class RegexForbidCheck(CheckBase):
    def run(self, ctx: CheckContext) -> CheckResult:
        pat = re.compile(ctx.stage.pattern or "")
        hits: list[CheckHit] = []
        for p in ctx.paragraphs:
            for m in pat.finditer(p.text):
                hits.append(CheckHit(
                    paragraph=p, char_start=m.start(), char_end=m.end(),
                    actual={"text": m.group(0)},
                    expected={"forbid_pattern": ctx.stage.pattern},
                    message=f"出现禁止模式 {ctx.stage.pattern}（命中 \"{m.group(0)}\"）",
                ))
        return CheckResult(passed=not hits, hits=hits)
