"""易混淆词对（字面 + 正则）。"""

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("confused_pair")
class ConfusedPairCheck(CheckBase):
    def run(self, ctx: CheckContext) -> CheckResult:
        pairs = ctx.stage.pairs or []
        hits: list[CheckHit] = []
        for p in ctx.paragraphs:
            for pair in pairs:
                wrong = pair.get("wrong")
                wrong_pat = pair.get("wrong_pattern")
                correct = pair.get("correct") or pair.get("suggest", "")
                reason = pair.get("reason", "")
                if wrong and wrong in p.text:
                    start = p.text.find(wrong)
                    hits.append(CheckHit(
                        paragraph=p, char_start=start, char_end=start + len(wrong),
                        actual={"text": wrong}, expected={"text": correct},
                        message=f"\"{wrong}\" 应为 \"{correct}\"。{reason}",
                    ))
                elif wrong_pat:
                    for m in re.finditer(wrong_pat, p.text):
                        hits.append(CheckHit(
                            paragraph=p, char_start=m.start(), char_end=m.end(),
                            actual={"text": m.group(0)},
                            expected={"text": correct},
                            message=f"\"{m.group(0)}\" 应为 \"{correct}\"。{reason}",
                        ))
        return CheckResult(passed=not hits, hits=hits)
