import { z } from 'zod';
import { EXIT_CODES, parseCommandArgs } from "../infrastructure.js";
import { openGraph } from "../shared.js";
const FORK_OPTIONS = {
    from: { type: 'string' },
    at: { type: 'string' },
    'fork-name': { type: 'string' },
    'fork-writer': { type: 'string' },
};
const forkSchema = z.object({
    from: z.string().min(1, 'Missing value for --from'),
    at: z.string().min(1, 'Missing value for --at'),
    'fork-name': z.string().min(1, 'Missing value for --fork-name').optional(),
    'fork-writer': z.string().min(1, 'Missing value for --fork-writer').optional(),
}).strict().transform((val) => ({
    from: val.from,
    at: val.at,
    forkName: val['fork-name'] ?? null,
    forkWriter: val['fork-writer'] ?? null,
}));
export default async function handleFork({ options, args }) {
    const { values } = parseCommandArgs(args, FORK_OPTIONS, forkSchema);
    const { graph, graphName } = await openGraph(options);
    const forked = await graph.fork({
        from: values.from,
        at: values.at,
        ...(values.forkName !== null ? { forkName: values.forkName } : {}),
        ...(values.forkWriter !== null ? { forkWriterId: values.forkWriter } : {}),
    });
    return {
        payload: {
            graph: graphName,
            forkGraph: forked.graphName,
            forkWriter: forked.writerId,
            from: values.from,
            at: values.at,
            status: 'created',
        },
        exitCode: EXIT_CODES.OK,
    };
}
