import { z } from 'zod';
import { EXIT_CODES, parseCommandArgs, usageError } from "../infrastructure.js";
import { openGraph, readActiveCursor } from "../shared.js";
const GC_OPTIONS = {};
const gcSchema = z.object({}).strict();
function gcUsage() {
    throw usageError('Usage: warp-graph gc <status|maybe-run|run>');
}
async function assertNoActiveCursor(persistence, graphName) {
    const cursor = await readActiveCursor(persistence, graphName);
    if (cursor !== null) {
        throw usageError('gc refuses to run while seek cursor is active; run git warp seek --latest first');
    }
}
async function gcStatus(options) {
    const { graph, graphName } = await openGraph(options);
    await graph.materialize();
    return {
        payload: { graph: graphName, metrics: graph.getGCMetrics() },
        exitCode: EXIT_CODES.OK,
    };
}
async function maybeRunGc(options) {
    const { graph, graphName, persistence } = await openGraph(options);
    await assertNoActiveCursor(persistence, graphName);
    await graph.materialize();
    const result = graph.maybeRunGC();
    return {
        payload: { graph: graphName, result },
        exitCode: EXIT_CODES.OK,
    };
}
async function runGc(options) {
    const { graph, graphName, persistence } = await openGraph(options);
    await assertNoActiveCursor(persistence, graphName);
    await graph.materialize();
    const result = graph.runGC();
    return {
        payload: { graph: graphName, result },
        exitCode: EXIT_CODES.OK,
    };
}
export default async function handleGc({ options, args }) {
    const action = args[0] ?? 'status';
    const rest = args.slice(1);
    parseCommandArgs(rest, GC_OPTIONS, gcSchema);
    if (action === 'status') {
        return await gcStatus(options);
    }
    if (action === 'maybe-run') {
        return await maybeRunGc(options);
    }
    if (action === 'run') {
        return await runGc(options);
    }
    return gcUsage();
}
