// @crash-shield-ignore-file — config/cache reader for Planu-controlled JSON; writer is this codebase, shape guaranteed by build/seed.
// tools/ecosystem-status.ts — Handler for ecosystem_status MCP tool (SPEC-151)
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { runEcosystemWatcher, rankCapabilities, extractSuggestions, } from '../engine/ecosystem-absorber/index.js';
import { formatSuccess, toolResult } from './response-helpers.js';
function loadSources() {
    try {
        const configPath = join(process.cwd(), 'src', 'config', 'ecosystem-sources.json');
        const raw = readFileSync(configPath, 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return [];
    }
}
function buildSourcesTable(sources, lastCrawled) {
    const rows = sources.map((s) => {
        const last = lastCrawled[s.id] ?? 'Never';
        const status = s.enabled ? 'enabled' : 'disabled';
        return `| ${s.name} | ${s.type} | ${String(s.crawlIntervalHours)}h | ${status} | ${last} |`;
    });
    return [
        '| Source | Type | Interval | Status | Last Crawled |',
        '|--------|------|----------|--------|--------------|',
        ...rows,
    ].join('\n');
}
/**
 * Handle the ecosystem_status tool invocation.
 * Returns markdown summary of ecosystem sources, discoveries, and suggestions.
 */
export async function handleEcosystemStatus(input) {
    const sources = loadSources();
    if (sources.length === 0) {
        return toolResult('No ecosystem sources configured. Check src/config/ecosystem-sources.json.', undefined, true);
    }
    const forceRefresh = input.refresh === true;
    const summary = await runEcosystemWatcher(sources, forceRefresh);
    const stackHints = [];
    const topCapabilities = rankCapabilities(summary.capabilities, stackHints, 5);
    const suggestions = extractSuggestions(topCapabilities);
    const body = [
        '## Sources',
        '',
        buildSourcesTable(sources, summary.lastCrawled),
        '',
        `## Discovery Summary`,
        '',
        `- **Total capabilities tracked**: ${String(summary.totalCapabilities)}`,
        `- **New this crawl**: ${String(summary.newCapabilities)}`,
        `- **Sources crawled**: ${summary.crawledSources.join(', ') || 'None (cache fresh)'}`,
        `- **Sources skipped (cache fresh)**: ${summary.skippedSources.join(', ') || 'None'}`,
    ];
    if (topCapabilities.length > 0) {
        body.push('', '## Recent Discoveries', '');
        for (const cap of topCapabilities) {
            body.push(`- **[${cap.category}]** ${cap.name} (relevance: ${String(cap.relevance)}) — ${cap.source}`);
        }
    }
    if (suggestions.length > 0) {
        body.push('', '## Suggestions', '');
        for (const s of suggestions) {
            body.push(`- ${s}`);
        }
    }
    const text = formatSuccess('Ecosystem Status', body.join('\n'));
    return toolResult(text);
}
//# sourceMappingURL=ecosystem-status.js.map