from __future__ import annotations

from app.modules.rag.intent_router_v2.analysis.followup_detector import FollowUpDetector
from app.modules.rag.intent_router_v2.models import ConversationState, QueryAnchor


class ConversationAnchorBuilder:
    def __init__(self, followup: FollowUpDetector | None = None) -> None:
        self._followup = followup or FollowUpDetector()

    def build(
        self,
        raw: str,
        state: ConversationState,
        *,
        continue_mode: bool,
        has_user_symbol: bool,
        has_user_file_path: bool,
    ) -> list[QueryAnchor]:
        if not continue_mode:
            return []
        anchors: list[QueryAnchor] = []
        if has_user_file_path:
            return anchors
        for path in self._paths_for_carryover(state.active_path_scope):
            anchors.append(
                QueryAnchor(
                    type="FILE_PATH",
                    value=path,
                    source="conversation_state",
                    span=None,
                    confidence=0.6,
                )
            )
        if has_user_symbol:
            return anchors
        if not self._followup.is_follow_up(raw):
            return anchors
        symbol = state.active_symbol or (state.active_code_span_symbols[0] if state.active_code_span_symbols else None)
        if symbol:
            anchors.append(
                QueryAnchor(
                    type="SYMBOL",
                    value=symbol,
                    source="conversation_state",
                    span=None,
                    confidence=0.64,
                )
            )
        return anchors

    def _paths_for_carryover(self, active_path_scope: list[str]) -> list[str]:
        paths = list(active_path_scope or [])
        file_paths = [path for path in paths if self._looks_like_file(path)]
        if file_paths:
            return file_paths[:1]
        return paths[:1]

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