"use strict";
/**
 * Top-level dispatcher for the `vyuh-dxkit explore` subcommand family.
 * The CLI (`src/cli.ts`) routes `case 'explore'` here; this module
 * dispatches the inner subcommand to the appropriate handler.
 *
 * Six subcommands per the Sprint 0 design (`tmp/2.7-explore-cli-design.md`):
 *   - entry-points  — what does this repo do?
 *   - hot-files     — what's central? (top files by call in-degree)
 *   - file <path>   — drill into one file's neighborhood
 *   - feature <kw>  — where is X implemented?
 *   - communities   — natural-module summary
 *   - api-surface   — exported symbols with no internal callers
 *
 * Architecture:
 *   - This file owns argument parsing + subcommand routing only.
 *   - All graph data comes from `loadGraph(cwd)` (canonical loader,
 *     CLAUDE.md Rule 12).
 *   - All graph traversal flows through `./explore/queries.ts`
 *     (canonical query module, also Rule 12).
 *   - Output formatting (JSON envelope + markdown tables) flows
 *     through `./explore/format.ts`.
 *
 * Sprint 1 landed the loader + types + query primitives. Sprint 2
 * adds the high-level queries + subcommand handlers below as each
 * lands.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.runExplore = runExplore;
const node_child_process_1 = require("node:child_process");
const node_fs_1 = require("node:fs");
const path = __importStar(require("node:path"));
const load_1 = require("./explore/load");
const api_surface_1 = require("./explore/cli/api-surface");
const communities_1 = require("./explore/cli/communities");
const context_1 = require("./explore/cli/context");
const entry_points_1 = require("./explore/cli/entry-points");
const feature_1 = require("./explore/cli/feature");
const file_1 = require("./explore/cli/file");
const hot_files_1 = require("./explore/cli/hot-files");
/**
 * Entry point called from `src/cli.ts:case 'explore'`. Receives the
 * already-parsed `values` from the top-level `parseArgs` plus the
 * positional arguments after `'explore'` (subcommand name + any
 * subcommand-specific args).
 */
async function runExplore(cwd, positionals, values) {
    const subcommand = positionals[0];
    if (!subcommand) {
        printExploreHelp();
        return;
    }
    // Honor --refresh by regenerating graph.json before query. The
    // simplest implementation: shell out to `vyuh-dxkit health` (which
    // produces graph.json as a side effect via gatherLayer2Parallel).
    if (values.refresh) {
        await refreshGraph(cwd);
    }
    const graph = loadGraphOrExit(cwd);
    switch (subcommand) {
        case 'hot-files':
            (0, hot_files_1.runHotFiles)(graph, positionals.slice(1), values);
            return;
        case 'communities':
            (0, communities_1.runCommunities)(graph, positionals.slice(1), values);
            return;
        case 'file':
            (0, file_1.runFile)(graph, positionals.slice(1), values, cwd);
            return;
        case 'entry-points':
            (0, entry_points_1.runEntryPoints)(graph, positionals.slice(1), values, cwd);
            return;
        case 'api-surface':
            (0, api_surface_1.runApiSurface)(graph, positionals.slice(1), values);
            return;
        case 'feature':
            (0, feature_1.runFeature)(graph, positionals.slice(1), values);
            return;
        case 'context':
            (0, context_1.runContext)(graph, positionals.slice(1), values, cwd);
            return;
        case 'help':
        case '--help':
        case '-h':
            printExploreHelp();
            return;
        default:
            process.stderr.write(`Unknown explore subcommand: ${subcommand}\n\n`);
            printExploreHelp();
            process.exit(1);
    }
}
/**
 * Load the graph and exit with a typed error message on failure.
 * Centralized so every subcommand gets the same diagnostic prose +
 * exit codes per the Sprint 0 spec (2 = not found, 3 = schema
 * mismatch, 4 = corrupt).
 */
function loadGraphOrExit(cwd) {
    try {
        return (0, load_1.loadGraph)(cwd);
    }
    catch (err) {
        if (err instanceof load_1.GraphNotFoundError) {
            process.stderr.write(`${err.message}\n`);
            process.exit(2);
        }
        if (err instanceof load_1.GraphSchemaVersionError) {
            process.stderr.write(`${err.message}\n`);
            process.exit(3);
        }
        if (err instanceof load_1.GraphCorruptError) {
            process.stderr.write(`${err.message}\n`);
            process.exit(4);
        }
        throw err;
    }
}
/**
 * Shell out to `vyuh-dxkit health` to regenerate graph.json. Uses
 * the locally-installed dxkit (resolved via the same `bin` script
 * the user invoked). Output streams through to the terminal so the
 * user sees the health run's progress.
 */
async function refreshGraph(cwd) {
    // Resolve the current dxkit entry point. The caller's CLI script
    // lives at one of two places depending on install flavor; both
    // resolve via the same node entry.
    const dxkitBin = resolveDxkitBin();
    return new Promise((resolve, reject) => {
        const child = (0, node_child_process_1.spawn)('node', [dxkitBin, 'health', cwd], {
            stdio: 'inherit',
            cwd,
        });
        child.on('exit', (code) => {
            if (code === 0)
                resolve();
            else
                reject(new Error(`vyuh-dxkit health exited with code ${code}`));
        });
        child.on('error', reject);
    });
}
function resolveDxkitBin() {
    // dist/explore-cli.js → dist/index.js
    const distEntry = path.resolve(__dirname, 'index.js');
    if ((0, node_fs_1.existsSync)(distEntry))
        return distEntry;
    // Fallback for local dev where __dirname might be elsewhere.
    return 'node_modules/@vyuhlabs/dxkit/dist/index.js';
}
function printExploreHelp() {
    process.stderr.write(`
vyuh-dxkit explore <subcommand> [args] [flags]

Subcommands:
  hot-files                Files most depended on (top by call in-degree)
  entry-points             Route handlers / controllers / forms
  file <path>              Symbols + callers/callees for one file
  feature <keyword>        Where is feature X implemented?
  communities              Natural-module clusters
  api-surface              Exported symbols with no internal callers
  context <query>          Slim structural slice for a query (token-reduction;
                           also available as the top-level 'vyuh-dxkit context')
  context <file:line>      Focused source chunk around a location + its callers
                           /callees (read ~the enclosing symbol, not the file)

Flags (all subcommands):
  --json                   Emit structured JSON envelope
  --limit N                Cap result count (per-subcommand defaults)
  --refresh                Force-regenerate graph.json before query

context-only flags:
  --budget N               Token ceiling on the slice / source chunk (default 2000)
  --depth N                Hard ceiling on call-graph hops (query form; default: budget-bounded)
  --substring              Broaden keyword matching to substrings (query form)

Reads from .dxkit/reports/graph.json. Run \`vyuh-dxkit health\` first
to generate the artifact.
`);
}
//# sourceMappingURL=explore-cli.js.map