import {
  fetchWithRetry,
  withTimeout
} from "./chunk-E6BQJL5D.js";
import {
  logger
} from "./chunk-F3NCFNUX.js";

// tools/codebase_search/core.ts
var CodebaseSearchClient = class {
  config;
  constructor(config = {}) {
    this.config = {
      apiKey: config.apiKey,
      searchUrl: process.env.MORPH_SEARCH_URL || "https://repos.morphllm.com",
      debug: config.debug,
      timeout: config.timeout || 3e4,
      retryConfig: config.retryConfig
    };
  }
  /**
   * Execute a semantic code search
   * 
   * @param input - Search parameters including query, repoId, and target directories
   * @param overrides - Optional config overrides for this operation
   * @returns Search results with ranked code matches
   */
  async search(input, overrides) {
    return executeCodebaseSearch(
      {
        query: input.query,
        target_directories: input.target_directories,
        explanation: input.explanation,
        limit: input.limit
      },
      { ...this.config, repoId: input.repoId, ...overrides }
    );
  }
};
async function executeCodebaseSearch(input, config) {
  const apiKey = config.apiKey || process.env.MORPH_API_KEY;
  if (!apiKey) {
    throw new Error("MORPH_API_KEY not found. Set environment variable or pass in config");
  }
  const searchUrl = config.searchUrl || process.env.MORPH_SEARCH_URL || "https://repos.morphllm.com";
  const timeout = config.timeout || 3e4;
  logger.debug("CodebaseSearch", "request", { query: input.query.slice(0, 100), repo_id: config.repoId, url: `${searchUrl}/v1/codebase_search` });
  const startTime = Date.now();
  try {
    const fetchPromise = fetchWithRetry(
      `${searchUrl}/v1/codebase_search`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          query: input.query,
          repoId: config.repoId,
          targetDirectories: input.target_directories || [],
          limit: input.limit || 10,
          candidateLimit: 50
        })
      },
      config.retryConfig
    );
    const response = await withTimeout(fetchPromise, timeout, `Codebase search timed out after ${timeout}ms`);
    if (!response.ok) {
      const errorText = await response.text();
      logger.error("CodebaseSearch", "response_error", { status: response.status, error: errorText, latency_ms: Date.now() - startTime });
      return {
        success: false,
        results: [],
        stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },
        error: `Search failed (${response.status}): ${errorText}`
      };
    }
    const data = await response.json();
    const elapsed = Date.now() - startTime;
    logger.debug("CodebaseSearch", "response", { results_count: data.results?.length || 0, latency_ms: elapsed });
    return {
      success: true,
      results: data.results || [],
      stats: data.stats || { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: elapsed }
    };
  } catch (error) {
    logger.error("CodebaseSearch", "exception", { error: error instanceof Error ? error.message : String(error), latency_ms: Date.now() - startTime });
    return {
      success: false,
      results: [],
      stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}

export {
  CodebaseSearchClient,
  executeCodebaseSearch
};
//# sourceMappingURL=chunk-S4IHNTCC.js.map