from __future__ import annotations

import re

from app.modules.rag.intent_router_v2.analysis.normalization import FILE_PATH_RE
from app.modules.rag.intent_router_v2.analysis.symbol_rules import COMMON_PATH_SEGMENTS, PY_KEYWORDS

_IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]{2,}")


class KeywordHintBuilder:
    def build(self, text: str) -> list[str]:
        hints: list[str] = []
        path_segments = self._path_segments(text)
        for token in _IDENTIFIER_RE.findall(text or ""):
            if token.lower() in PY_KEYWORDS:
                continue
            if token.lower() in path_segments:
                continue
            if token not in hints:
                hints.append(token)
        for match in FILE_PATH_RE.finditer(text or ""):
            candidate = match.group(0).lower()
            if candidate not in hints:
                hints.append(candidate)
        return hints[:12]

    def _path_segments(self, text: str) -> set[str]:
        values: set[str] = set(COMMON_PATH_SEGMENTS)
        for match in FILE_PATH_RE.finditer(text or ""):
            for part in re.split(r"[/.]+", match.group(0).lower()):
                if part:
                    values.add(part)
        return values
