/**
 * Tool Relevance
 *
 * Score tools by the level of agent intent they indicate.
 * Higher scores = more deliberate/important actions.
 */

/**
 * Tool relevance scores by tool name
 *
 * Hierarchy:
 * - 1.0: Active modifications (write, edit, apply)
 * - 0.8-0.9: Deliberate investigation (read, get_callers)
 * - 0.6-0.7: Targeted search (semantic_search, grep)
 * - 0.3: Broad discovery (list_files, glob)
 * - 0.2: Graph algorithms (pagerank)
 */
export const TOOL_RELEVANCE: Record<string, number> = {
  // Highest: Active code modifications
  write_to_file: 1.0,
  writeFile: 1.0,
  apply_diff: 1.0,
  applyDiff: 1.0,
  edit_file: 1.0,
  editFile: 1.0,
  delete_file: 1.0,
  deleteFile: 1.0,

  // High: Deliberate investigation
  read_file: 0.9,
  readFile: 0.9,
  get_callers: 0.9,
  getCallers: 0.9,
  get_callees: 0.9,
  getCallees: 0.9,
  expand_node: 0.85,
  expandNode: 0.85,
  get_class_hierarchy: 0.85,
  getClassHierarchy: 0.85,
  get_file_dependencies: 0.85,
  getFileDependencies: 0.85,

  // Medium: Targeted search
  semantic_search: 0.7,
  semanticSearch: 0.7,
  text_search: 0.65,
  textSearch: 0.65,
  grep: 0.6,
  grepTool: 0.6,
  find_entity: 0.6,
  findEntity: 0.6,

  // Low: Broad discovery
  list_files: 0.3,
  listFiles: 0.3,
  glob: 0.3,
  globTool: 0.3,

  // Lowest: Graph algorithms
  get_top_pagerank: 0.2,
  getTopPagerank: 0.2,
  get_communities: 0.2,
  getCommunities: 0.2,
  get_area_importance: 0.2,
  getAreaImportance: 0.2,
};

/**
 * Tools that return ranked search results
 */
export const SEARCH_TOOLS = new Set([
  'semantic_search',
  'semanticSearch',
  'text_search',
  'textSearch',
  'grep',
  'grepTool',
  'find_entity',
  'findEntity',
]);

/**
 * Number of top search results that get full score
 */
export const TOP_RESULTS_LIMIT = 3;

/**
 * Score multiplier for non-top search results
 */
export const NON_TOP_RESULT_MULTIPLIER = 0.5;

/**
 * Default relevance for unknown tools
 */
export const DEFAULT_TOOL_RELEVANCE = 0.5;

/**
 * Get relevance score for a tool
 */
export function getToolRelevance(toolName: string): number {
  return TOOL_RELEVANCE[toolName] ?? DEFAULT_TOOL_RELEVANCE;
}

/**
 * Check if a tool is a search tool
 */
export function isSearchTool(toolName: string): boolean {
  return SEARCH_TOOLS.has(toolName);
}

/**
 * Calculate score for an entity discovered by a tool
 *
 * @param toolName - Name of the tool
 * @param resultPosition - Position in search results (0-indexed, undefined for non-search)
 */
export function calculateToolScore(toolName: string, resultPosition?: number): number {
  const baseScore = getToolRelevance(toolName);

  // For search tools, apply position-based multiplier
  if (isSearchTool(toolName) && resultPosition !== undefined) {
    if (resultPosition < TOP_RESULTS_LIMIT) {
      return baseScore;
    }
    return baseScore * NON_TOP_RESULT_MULTIPLIER;
  }

  return baseScore;
}
