// tech-discovery.ts — Main orchestrator for tool discovery across npm and GitHub registries
import { readFileSync } from 'node:fs';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { searchNpmRegistry, searchGitHubTopics } from './registry-search.js';
import { rankResults } from './result-ranker.js';
// --- config (loaded once at module init) ---
const CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), '../../config/discovery-queries.json');
let queryMapping = null;
function loadDiscoveryQueryMapping() {
    if (queryMapping !== null) {
        return queryMapping;
    }
    try {
        queryMapping = JSON.parse(readFileSync(CONFIG_PATH, 'utf-8'));
    }
    catch {
        queryMapping = {};
    }
    return queryMapping;
}
// --- cache helpers ---
const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
function cacheFile(dataDir) {
    return join(dataDir, 'discovery-cache.json');
}
async function readCache(dataDir) {
    try {
        const raw = await readFile(cacheFile(dataDir), 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return {};
    }
}
async function writeCache(dataDir, cache) {
    try {
        const path = cacheFile(dataDir);
        await mkdir(dirname(path), { recursive: true });
        await writeFile(path, JSON.stringify(cache, null, 2), 'utf-8');
    }
    catch {
        // best-effort — never fail the caller
    }
}
function isFresh(entry) {
    return Date.now() - new Date(entry.cachedAt).getTime() < CACHE_TTL_MS;
}
// --- main export ---
export async function discoverTools(patterns, _stackLanguage, dataDir) {
    const mapping = loadDiscoveryQueryMapping();
    const cache = await readCache(dataDir);
    const cacheUpdated = { ...cache };
    const allResults = await Promise.all(patterns.map(async (pattern) => {
        const cached = cache[pattern];
        if (cached && isFresh(cached)) {
            return cached.results;
        }
        const config = mapping[pattern];
        const keywords = config?.npm_keywords ?? [pattern];
        const topics = config?.github_topics ?? [pattern];
        const [npmResults, ghResults] = await Promise.all([
            searchNpmRegistry(keywords),
            searchGitHubTopics(topics),
        ]);
        const ranked = rankResults(npmResults, ghResults, _stackLanguage);
        cacheUpdated[pattern] = { results: ranked, cachedAt: new Date().toISOString() };
        return ranked;
    }));
    await writeCache(dataDir, cacheUpdated);
    const merged = allResults.flat();
    const seen = new Set();
    const deduped = merged.filter((tool) => {
        if (seen.has(tool.name)) {
            return false;
        }
        seen.add(tool.name);
        return true;
    });
    return rankResults(deduped, [], _stackLanguage);
}
//# sourceMappingURL=tech-discovery.js.map