"use strict";
/**
 * `vyuh-dxkit explore feature <keyword>` — where is feature X
 * implemented? The marquee query of the explore CLI.
 *
 * Three-stage resolution (per Sprint 0 spec):
 *   1. Direct symbolIndex match
 *   2. Substring expansion (opt-in via --substring; off by default)
 *   3. Structural expansion (community + 1-hop callers/callees)
 *
 * On zero hits, prints "did you mean..." suggestions from
 * edit-distance against symbolIndex keys.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.runFeature = runFeature;
const queries_1 = require("../queries");
const format_1 = require("../format");
const DEFAULT_LIMIT = 50;
function runFeature(graph, positionals, values) {
    const keyword = positionals[0];
    if (!keyword) {
        process.stderr.write('Usage: vyuh-dxkit explore feature <keyword> [--substring] [--limit 50]\n');
        process.exit(1);
    }
    const limit = parseLimit(values.limit, DEFAULT_LIMIT);
    const substring = !!values.substring;
    const result = (0, queries_1.featureQuery)(graph, keyword, { limit, substring });
    if (values.json) {
        (0, format_1.printJson)((0, format_1.envelope)('explore.feature', { keyword, limit, substring }, graph, result));
        return;
    }
    const sections = [];
    sections.push((0, format_1.markdownHeader)('Feature', `\`${keyword}\``, graph));
    if (result.results.length === 0) {
        if (result.suggestions.length > 0) {
            const lines = result.suggestions
                .map((s) => `  - \`${s.key}\` (${s.hits} hit${s.hits === 1 ? '' : 's'})`)
                .join('\n');
            sections.push(`No exact symbol match for \`${keyword}\`. Related symbols (substring or typo-distance):\n\n${lines}\n\nRerun with \`--substring\` to expand structurally from these (the typical "where is X implemented?" workflow), or pick a specific symbol above.`);
        }
        else {
            sections.push(`No symbols matched \`${keyword}\` (no close alternatives found either). Try a different keyword, rerun with \`--substring\` for broader matching, or check \`vyuh-dxkit explore communities\` to see the natural-module structure.`);
        }
        (0, format_1.printMarkdown)(...sections);
        return;
    }
    // Summary line + central entry point (if any).
    const totalSeeds = result.results.reduce((sum, c) => sum + c.seedHits, 0);
    sections.push(`**Seed matches**: ${totalSeeds} symbol${totalSeeds === 1 ? '' : 's'} across ${result.results.length} cluster${result.results.length === 1 ? '' : 's'}.`);
    // Per-cluster sections.
    for (const cluster of result.results) {
        sections.push(buildClusterSection(cluster));
    }
    if (result.centralEntryPoint) {
        const cep = result.centralEntryPoint;
        const where = cep.line ? `${cep.sourceFile}:${cep.line}` : cep.sourceFile;
        sections.push(`\nThe most-called seed symbol is **\`${cep.symbol}\`** at \`${where}\` — called from ${cep.calledFrom} place${cep.calledFrom === 1 ? '' : 's'}. A natural starting read.`);
    }
    sections.push((0, format_1.markdownFooter)('Drill into one: `vyuh-dxkit explore file <path>`.'));
    (0, format_1.printMarkdown)(...sections);
}
function buildClusterSection(cluster) {
    const lines = [];
    const id = cluster.clusterId + 1;
    const role = cluster.role;
    const seedNote = cluster.seedHits === 0 ? ' (expansion only — no direct seed)' : '';
    lines.push(`### Cluster ${id} — ${role}${seedNote}`);
    if (cluster.communityId !== undefined) {
        lines.push(`*Community*: ${cluster.communityId}${cluster.dominantSourceDir ? ` (${cluster.dominantSourceDir})` : ''}`);
    }
    if (cluster.keySymbols.length > 0) {
        lines.push(`*Key symbols*: ${cluster.keySymbols.map((s) => `\`${s}\``).join(', ')}`);
    }
    lines.push('');
    lines.push((0, format_1.markdownTable)(['File'], cluster.files.slice(0, 12).map((f) => ({ File: f }))));
    if (cluster.files.length > 12) {
        lines.push(`\n*+ ${cluster.files.length - 12} more file${cluster.files.length - 12 === 1 ? '' : 's'}*`);
    }
    return lines.join('\n');
}
function parseLimit(raw, defaultValue) {
    if (!raw)
        return defaultValue;
    const n = parseInt(raw, 10);
    if (isNaN(n) || n < 1)
        return defaultValue;
    return Math.min(n, 1000);
}
//# sourceMappingURL=feature.js.map