import process from 'node:process';
import { z } from 'zod';
import { compactStringify } from "../../presenters/json.js";
import { EXIT_CODES, parseCommandArgs, usageError } from "../infrastructure.js";
import { openGraph } from "../shared.js";
const WATCH_OPTIONS = {
    poll: { type: 'string' },
};
const watchSchema = z.object({
    poll: z.coerce.number().int().min(1000, 'poll must be >= 1000').optional(),
}).strict();
function parseWatchArgs(args) {
    const { values, positionals } = parseCommandArgs(args, WATCH_OPTIONS, watchSchema, {
        allowPositionals: true,
    });
    if (positionals.length > 1) {
        throw usageError('Usage: warp-graph watch [pattern] [--poll <ms>]');
    }
    return { pattern: positionals[0] ?? '*', values };
}
function watchOptions(graphName, pattern, values) {
    return {
        ...(values.poll !== undefined ? { poll: values.poll } : {}),
        onChange(diff) {
            process.stdout.write(`${compactStringify({ type: 'change', graph: graphName, pattern, diff })}\n`);
        },
        onError(error) {
            process.stderr.write(`watch error: ${String(error)}\n`);
        },
    };
}
function closeWatch(subscription) {
    return () => {
        subscription.unsubscribe();
        return Promise.resolve();
    };
}
export default async function handleWatch({ options, args }) {
    const { pattern, values } = parseWatchArgs(args);
    const { graph, graphName } = await openGraph(options);
    const subscription = graph.watch(pattern, watchOptions(graphName, pattern, values));
    return {
        payload: {
            graph: graphName,
            pattern,
            status: 'watching',
            eventFormat: 'ndjson',
        },
        exitCode: EXIT_CODES.OK,
        close: closeWatch(subscription),
    };
}
