"""Select MCP tools appropriate for a project + task analysis.

Maps (project stack, task intent) → list of MCP server names that should be
made available for the request.
"""

from __future__ import annotations

from proxym.context._context import ProjectContext
from proxym.router import AnalysisResult


# Tool routing rules: intent keywords → MCP server names
TOOL_ROUTING_RULES: dict[str, list[str]] = {
    "file_operation": ["filesystem"],
    "git_operation": ["github", "filesystem"],
    "code_search": ["filesystem", "code2llm"],
    "issue_tracking": ["github", "linear"],
    "documentation": ["filesystem", "code2docs"],
    "database_query": ["postgresql", "sqlite"],
    "testing": ["filesystem"],
    "deployment": ["filesystem", "docker"],
}

# Stack-based default tools
STACK_TOOLS: dict[str, list[str]] = {
    "python": ["filesystem", "code2llm"],
    "javascript": ["filesystem", "code2llm"],
    "typescript": ["filesystem", "code2llm"],
    "rust": ["filesystem"],
    "go": ["filesystem"],
    "fastapi": ["filesystem", "code2llm", "code2docs"],
    "django": ["filesystem", "code2llm", "code2docs"],
    "react": ["filesystem", "code2llm"],
    "nextjs": ["filesystem", "code2llm"],
}

# Intent keywords found in analysis signals
_INTENT_KEYWORDS: dict[str, list[str]] = {
    "file_operation": ["file", "create", "write", "read", "delete"],
    "git_operation": ["git", "commit", "branch", "merge", "pull", "push"],
    "code_search": ["find", "search", "grep", "locate", "where"],
    "issue_tracking": ["issue", "ticket", "bug report", "feature request"],
    "documentation": ["doc", "readme", "explain", "document"],
    "database_query": ["database", "query", "sql", "table", "migration"],
    "testing": ["test", "pytest", "jest", "coverage"],
    "deployment": ["deploy", "docker", "ci", "cd", "pipeline"],
}


def select_tools(
    context: ProjectContext,
    analysis: AnalysisResult | None = None,
    available_servers: set[str] | None = None,
) -> list[str]:
    """Select MCP servers for a given project and task analysis.

    Parameters
    ----------
    context : ProjectContext
        Detected project context.
    analysis : AnalysisResult | None
        Content analysis result (used for intent-based tool selection).
    available_servers : set[str] | None
        If provided, filter results to only include registered servers.

    Returns
    -------
    list[str]
        Ordered list of MCP server names to activate.
    """
    tools: set[str] = set()

    # Stack-based defaults
    for stack_item in context.stack:
        tools.update(STACK_TOOLS.get(stack_item, []))

    # Intent-based additions from analysis signals
    if analysis:
        intent = _detect_intent(analysis)
        for intent_name in intent:
            tools.update(TOOL_ROUTING_RULES.get(intent_name, []))

    # Always include filesystem as baseline
    tools.add("filesystem")

    # Filter by available servers if provided
    if available_servers is not None:
        tools &= available_servers

    return sorted(tools)


def _detect_intent(analysis: AnalysisResult) -> list[str]:
    """Detect task intent from analysis signals and reasoning."""
    text = " ".join(analysis.signals + [analysis.reasoning]).lower()
    intents = []
    for intent_name, keywords in _INTENT_KEYWORDS.items():
        if any(kw in text for kw in keywords):
            intents.append(intent_name)
    return intents
