import { z } from 'zod';
import { createCommand } from '../../../types';
import * as tui from '../../../tui';
import { createCadenceKVAdapter, CADENCE_NAMESPACE, getLoopStateKey, parseLoopState, } from './util';
import { getCommand } from '../../../command-prefix';
const CadenceStopResponseSchema = z.object({
    success: z.boolean(),
    loopId: z.string(),
    previousStatus: z.string().optional(),
    newStatus: z.string().optional(),
    message: z.string(),
});
export const stopSubcommand = createCommand({
    name: 'stop',
    aliases: ['cancel'],
    description: 'Stop and cancel a Cadence loop',
    tags: ['mutating', 'updates-resource', 'fast', 'requires-auth'],
    requires: { auth: true },
    examples: [
        { command: getCommand('cadence stop lp_auth_impl'), description: 'Stop and cancel a loop' },
    ],
    schema: {
        args: z.object({
            loopId: z.string().min(1).describe('The loop ID to stop'),
        }),
        response: CadenceStopResponseSchema,
    },
    async handler(ctx) {
        const { args, options } = ctx;
        const kv = await createCadenceKVAdapter(ctx);
        const key = getLoopStateKey(args.loopId);
        const result = await kv.get(CADENCE_NAMESPACE, key);
        if (!result.exists || !result.data) {
            if (!options.json) {
                tui.error(`Loop ${args.loopId} not found.`);
            }
            return {
                success: false,
                loopId: args.loopId,
                message: 'Loop not found',
            };
        }
        let data;
        if (typeof result.data === 'string') {
            try {
                data = JSON.parse(result.data);
            }
            catch {
                if (!options.json) {
                    tui.error(`Failed to parse loop state for ${args.loopId}`);
                }
                return {
                    success: false,
                    loopId: args.loopId,
                    message: 'Failed to parse loop state',
                };
            }
        }
        else {
            data = result.data;
        }
        const loop = parseLoopState(data);
        if (!loop) {
            if (!options.json) {
                tui.error(`Invalid loop state for ${args.loopId}`);
            }
            return {
                success: false,
                loopId: args.loopId,
                message: 'Invalid loop state',
            };
        }
        const previousStatus = loop.status;
        if (loop.status === 'completed' || loop.status === 'cancelled') {
            if (!options.json) {
                tui.warning(`Loop ${args.loopId} is already ${loop.status}`);
            }
            return {
                success: false,
                loopId: args.loopId,
                previousStatus,
                message: `Loop is already ${loop.status}`,
            };
        }
        // Update status to cancelled
        const updatedLoop = {
            ...loop,
            status: 'cancelled',
            updatedAt: new Date().toISOString(),
        };
        await kv.set(CADENCE_NAMESPACE, key, JSON.stringify(updatedLoop), {
            contentType: 'application/json',
        });
        if (!options.json) {
            tui.success(`Stopped loop ${args.loopId}`);
        }
        return {
            success: true,
            loopId: args.loopId,
            previousStatus,
            newStatus: 'cancelled',
            message: 'Loop cancelled successfully',
        };
    },
});
export default stopSubcommand;
//# sourceMappingURL=stop.js.map