from __future__ import annotations

from app.modules.rag.intent_router_v2.models import QueryAnchor


class AnchorSpanValidator:
    def sanitize(self, anchors: list[QueryAnchor], raw_len: int) -> list[QueryAnchor]:
        result: list[QueryAnchor] = []
        for anchor in anchors:
            if anchor.source != "user_text":
                result.append(anchor.model_copy(update={"span": None}))
                continue
            if anchor.span is None:
                result.append(anchor)
                continue
            start = int(anchor.span.start)
            end = int(anchor.span.end)
            if 0 <= start < end <= raw_len:
                result.append(anchor)
                continue
            result.append(anchor.model_copy(update={"span": None, "confidence": max(anchor.confidence * 0.5, 0.0)}))
        return result
