from __future__ import annotations

import re

from app.modules.agent.engine.router.schemas import RouterContext


class IntentSwitchDetector:
    _EXPLICIT_SWITCH_MARKERS = (
        "теперь",
        "а теперь",
        "давай теперь",
        "переключись",
        "переключаемся",
        "сейчас другое",
        "новая задача",
        "new task",
        "switch to",
        "now do",
        "instead",
    )
    _FOLLOW_UP_MARKERS = (
        "а еще",
        "а ещё",
        "подробнее",
        "почему",
        "зачем",
        "что если",
        "и еще",
        "и ещё",
        "покажи подробнее",
        "можешь подробнее",
    )

    def should_switch(self, user_message: str, context: RouterContext) -> bool:
        if not context.dialog_started or context.active_intent is None:
            return False
        text = " ".join((user_message or "").strip().lower().split())
        if not text:
            return False
        if self._is_follow_up(text):
            return False
        if any(marker in text for marker in self._EXPLICIT_SWITCH_MARKERS):
            return True
        return self._is_strong_targeted_edit_request(text) or self._is_strong_docs_request(text)

    def _is_follow_up(self, text: str) -> bool:
        return any(marker in text for marker in self._FOLLOW_UP_MARKERS)

    def _is_strong_targeted_edit_request(self, text: str) -> bool:
        edit_markers = (
            "добавь",
            "добавить",
            "измени",
            "исправь",
            "обнови",
            "удали",
            "замени",
            "append",
            "update",
            "edit",
            "remove",
            "replace",
        )
        has_edit_marker = any(marker in text for marker in edit_markers)
        has_file_marker = (
            "readme" in text
            or bool(re.search(r"\b[\w.\-/]+\.(md|txt|rst|yaml|yml|json|toml|ini|cfg|py)\b", text))
        )
        return has_edit_marker and has_file_marker

    def _is_strong_docs_request(self, text: str) -> bool:
        docs_markers = (
            "подготовь документац",
            "сгенерируй документац",
            "создай документац",
            "опиши документац",
            "generate documentation",
            "write documentation",
        )
        return any(marker in text for marker in docs_markers)
