import { EXIT_CODES, usageError, parseCommandArgs } from "../infrastructure.js";
import { openGraph, applyCursorCeiling, emitCursorWarning } from "../shared.js";
import { pathSchema } from "../schemas.js";
const PATH_OPTIONS = {
    from: { type: 'string' },
    to: { type: 'string' },
    dir: { type: 'string' },
    label: { type: 'string', multiple: true },
    'max-depth': { type: 'string' },
};
function endpointFrom(values, positionals) {
    const value = values.from ?? positionals[0];
    if (value === undefined || value.length === 0) {
        throw usageError('path requires --from <id> or a source positional');
    }
    return value;
}
function endpointTo(values, positionals) {
    const value = values.to ?? positionals[1];
    if (value === undefined || value.length === 0) {
        throw usageError('path requires --to <id> or a target positional');
    }
    return value;
}
function firstLabel(labels) {
    return labels[0];
}
function traversalOptions(values) {
    const options = { dir: values.dir ?? 'out' };
    const label = firstLabel(values.labels);
    if (label !== undefined) {
        return values.maxDepth !== undefined
            ? { ...options, labelFilter: label, maxDepth: values.maxDepth }
            : { ...options, labelFilter: label };
    }
    return values.maxDepth !== undefined
        ? { ...options, maxDepth: values.maxDepth }
        : options;
}
/** Handles `git warp path`: finds a shortest path through the read surface. */
export default async function handlePath({ options, args }) {
    const { values, positionals } = parseCommandArgs(args, PATH_OPTIONS, pathSchema, { allowPositionals: true });
    const from = endpointFrom(values, positionals);
    const to = endpointTo(values, positionals);
    const { graph, graphName, persistence } = await openGraph(options);
    const cursorInfo = await applyCursorCeiling(graph, persistence, graphName);
    emitCursorWarning(cursorInfo, null);
    await graph.materialize();
    const result = await graph.traverse.shortestPath(from, to, traversalOptions(values));
    return {
        payload: {
            graph: graphName,
            from,
            to,
            found: result.found,
            path: result.path,
            length: result.length,
        },
        exitCode: result.found ? EXIT_CODES.OK : EXIT_CODES.NO_MATCH,
    };
}
