import { searchSymbols } from "./search-tools.js";
import { findReferences } from "./symbol-tools.js";
import { listAllRepos } from "./index-tools.js";
/**
 * Run a search function across all indexed repos (or a filtered subset).
 * Collects results and errors separately — never silently swallows failures.
 */
async function searchAcrossRepos(repoPattern, searchFn) {
    const repos = await listAllRepos({ compact: false });
    const repoList = (Array.isArray(repos) ? repos : []);
    const filtered = repoPattern
        ? repoList.filter((r) => r.name.includes(repoPattern))
        : repoList;
    const results = [];
    const errors = [];
    for (const repo of filtered) {
        try {
            const items = await searchFn(repo.name);
            if (items.length > 0) {
                results.push({ repo: repo.name, items });
            }
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            errors.push({ repo: repo.name, error: message });
        }
    }
    return { results, errors, reposSearched: filtered.length };
}
/**
 * Search symbols across ALL indexed repos (or a filtered subset).
 * Useful for monorepos and microservice architectures.
 */
export async function crossRepoSearchSymbols(query, options) {
    const { results, errors, reposSearched } = await searchAcrossRepos(options?.repo_pattern, (repoName) => searchSymbols(repoName, query, options));
    return {
        symbol_results: results.map(({ repo, items }) => ({ repo, results: items })),
        total_matches: results.reduce((sum, r) => sum + r.items.length, 0),
        repos_searched: reposSearched,
        errors,
    };
}
/**
 * Find references to a symbol across ALL indexed repos.
 */
export async function crossRepoFindReferences(symbolName, options) {
    const { results, errors, reposSearched } = await searchAcrossRepos(options?.repo_pattern, (repoName) => findReferences(repoName, symbolName, options?.file_pattern));
    return {
        ref_results: results.map(({ repo, items }) => ({ repo, references: items })),
        total_references: results.reduce((sum, r) => sum + r.items.length, 0),
        repos_searched: reposSearched,
        errors,
    };
}
//# sourceMappingURL=cross-repo-tools.js.map