from __future__ import annotations

import re


class AnswerQualityController:
    _REPLACEMENTS = (
        ("различные аргументы", "аргументы"),
        ("ряд аргументов", "аргументы"),
        ("различных подпакетов", "подпакетов"),
        ("основные службы", "службы"),
        ("играет роль", "работает как"),
        ("представляет собой", "это"),
    )
    _DROP_PATTERNS = (
        r"(?i)ответ основан исключительно[^.]*\.",
        r"(?i)нет явных неподтвержденных кандидатов\.?",
        r"(?i)кандидаты[^.\n]*нет[^.\n]*\.?",
        r"(?i)related tests[^.\n]*none[^.\n]*\.?",
        r"(?i)indirect evidence[^.\n]*none[^.\n]*\.?",
    )
    _NOT_FOUND_PATTERNS = (
        "не найден",
        "не найдена",
        "не найдены",
        "не обнаружен",
        "не обнаружена",
        "не обнаружены",
    )

    def refine(self, text: str, *, sub_intent: str | None = None) -> str:
        value = self._normalize_markdown(text)
        value = self._drop_empty_sections(value)
        value = self._replace_vague_phrases(value)
        if self._should_trim_not_found(value, sub_intent=sub_intent):
            value = self._trim_after_not_found(value)
        return self._normalize_spacing(value)

    def _normalize_markdown(self, text: str) -> str:
        value = str(text or "").strip()
        value = re.sub(r"(?m)^\s{0,3}#{1,6}\s*", "", value)
        return value.replace("**", "")

    def _drop_empty_sections(self, text: str) -> str:
        value = text
        for pattern in self._DROP_PATTERNS:
            value = re.sub(pattern, "", value)
        return value

    def _replace_vague_phrases(self, text: str) -> str:
        value = text
        for source, target in self._REPLACEMENTS:
            value = re.sub(re.escape(source), target, value, flags=re.IGNORECASE)
        return value

    def _should_trim_not_found(self, text: str, *, sub_intent: str | None) -> bool:
        current = str(sub_intent or "").strip().upper()
        if current not in {"EXPLAIN", "OPEN_FILE", "FIND_TESTS", "FIND_ENTRYPOINTS"}:
            return False
        lowered = text.lower()
        return any(pattern in lowered for pattern in self._NOT_FOUND_PATTERNS)

    def _trim_after_not_found(self, text: str) -> str:
        match = re.search(r"(?<=[.!?])\s+", text.strip())
        if not match:
            return text.strip()
        return text[: match.start()].strip()

    def _normalize_spacing(self, text: str) -> str:
        value = re.sub(r"\n{3,}", "\n\n", text)
        return re.sub(r"[ \t]{2,}", " ", value).strip()
