from __future__ import annotations

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


class KeywordHintSanitizer:
    _GENERIC_KEY_TERMS = {"файл", "класс", "метод", "функция", "документация"}
    _DOMAIN_ALLOWLIST = {"RAG", "API", "HTTP", "SQL"}
    _DIR_SCOPE_MARKERS = ("в папке", "в директории", "в каталоге")

    def sanitize(self, raw: str, anchors: list[QueryAnchor], base_hints: list[str]) -> list[str]:
        text = (raw or "").lower()
        allow_dirs = any(marker in text for marker in self._DIR_SCOPE_MARKERS)
        file_paths = [anchor.value for anchor in anchors if anchor.type == "FILE_PATH" and self._looks_like_file(anchor.value)]
        known_dirs = {path.rsplit("/", 1)[0] for path in file_paths if "/" in path}
        result: list[str] = []

        for anchor in anchors:
            if anchor.type == "FILE_PATH":
                if self._looks_like_directory(anchor.value):
                    if not allow_dirs and (known_dirs or file_paths):
                        continue
                self._append(result, anchor.value)
            if anchor.type == "SYMBOL":
                self._append(result, anchor.value)

        for token in base_hints:
            if token in self._DOMAIN_ALLOWLIST:
                self._append(result, token)
                continue
            lowered = token.lower()
            if lowered in self._GENERIC_KEY_TERMS:
                continue
            if token in known_dirs and not allow_dirs:
                continue
            if "/" in token and "." not in token and not allow_dirs and file_paths:
                continue
            self._append(result, token)
        return result[:8]

    def _append(self, values: list[str], candidate: str) -> None:
        if candidate and candidate not in values:
            values.append(candidate)

    def _looks_like_file(self, value: str) -> bool:
        tail = (value or "").rsplit("/", 1)[-1]
        return "." in tail

    def _looks_like_directory(self, value: str) -> bool:
        return "/" in (value or "") and not self._looks_like_file(value)
