# Copyright (C) 2026 GoodData Corporation

"""Utility functions for rule retrieval."""

from __future__ import annotations

from pathlib import Path

from aida_mcp.utils.aida_paths import DOT_AIDA


def find_rules_directory(start_path: Path) -> Path | None:
    """
    Find the `.aida/rules/` directory by walking up from start_path.

    Similar to how git finds .git/ - useful when developers open a subdirectory
    (e.g., services/example-service) instead of the repository root.

    Args:
        start_path: Directory to start searching from

    Returns:
        Path to `.aida/rules/` directory, or None if not found
    """
    current = start_path.resolve()

    # Walk up the directory tree (max 10 levels to avoid infinite loops)
    for _ in range(10):
        rules_dir = current / DOT_AIDA / "rules"
        if rules_dir.is_dir():
            return rules_dir

        parent = current.parent
        if parent == current:
            # Reached filesystem root
            break
        current = parent

    return None


def enhance_query_with_file_context(query: str, file_context: list[str] | None) -> str:
    """
    Enhance query with terms extracted from file context.

    Args:
        query: Original query string
        file_context: Optional list of file paths

    Returns:
        Enhanced query string with context terms appended
    """
    if not file_context:
        return query

    context_terms: list[str] = []
    for fp in file_context:
        parts = Path(fp).parts
        for part in parts:
            if part not in ("src", "main", "test", "app", "kotlin", "java", "py"):
                context_terms.append(part)

    if context_terms:
        return f"{query} {' '.join(context_terms[:5])}"

    return query
