"""Symbol indexing tools for AI agent integration."""

import json
from pathlib import Path
from langchain_core.tools import tool

from ieum.indexing import CodebaseIndexer, SymbolSearch, SymbolDatabase


# Use a shared database path
DEFAULT_DB_PATH = Path.home() / ".ieum" / "index.db"


@tool
def index_file_tool(file_path: str, project_path: str = ".") -> str:
    """Index a file to extract and store its symbols for fast searching.

    Args:
        file_path: Path to the file to index.
        project_path: Root path of the project (default: current directory).

    Returns:
        Summary of indexed symbols.
    """
    db = SymbolDatabase(DEFAULT_DB_PATH)
    indexer = CodebaseIndexer(project_path, db)

    try:
        count = indexer.index_file(file_path)
        db.close()
        return f"Indexed {count} symbols from {file_path}"
    except Exception as e:
        db.close()
        return f"Error indexing file: {e}"


@tool
def search_symbols_tool(query: str, symbol_type: str = None, limit: int = 20) -> str:
    """Search for symbols in the indexed codebase.

    Args:
        query: Search query (supports partial matching).
        symbol_type: Optional filter by type (function, class, method, variable).
        limit: Maximum number of results (default: 20).

    Returns:
        JSON string containing matching symbols with file locations.
    """
    db = SymbolDatabase(DEFAULT_DB_PATH)
    search = SymbolSearch(db=db)

    try:
        from ieum.indexing.search import SearchFilters
        filters = SearchFilters(symbol_type=symbol_type) if symbol_type else None
        results = search.search(query, filters=filters, limit=limit)
        db.close()

        if not results:
            return f"No symbols found matching '{query}'"

        output = {
            "query": query,
            "count": len(results),
            "results": []
        }

        for r in results:
            output["results"].append({
                "name": r.get("name"),
                "type": r.get("type"),
                "file": r.get("file_path"),
                "line": r.get("line"),
            })

        return json.dumps(output, indent=2, ensure_ascii=False)
    except Exception as e:
        db.close()
        return f"Search error: {e}"
