/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import * as z from 'zod';
export function declareCommand(command) {
    return command;
}
const kEmptyOptions = z.object({});
const kEmptyArgs = z.object({});
export function parseCommand(command, args) {
    const optionsObject = { ...args };
    delete optionsObject['_'];
    const optionsSchema = (command.options ?? kEmptyOptions).strict();
    const options = zodParse(optionsSchema, optionsObject, 'option');
    const argsSchema = (command.args ?? kEmptyArgs).strict();
    const argNames = [...Object.keys(argsSchema.shape)];
    const argv = args['_'].slice(1);
    if (argv.length > argNames.length)
        throw new Error(`error: too many arguments: expected ${argNames.length}, received ${argv.length}`);
    const argsObject = {};
    argNames.forEach((name, index) => argsObject[name] = argv[index]);
    const parsedArgsObject = zodParse(argsSchema, argsObject, 'argument');
    const toolName = typeof command.toolName === 'function' ? command.toolName({ ...parsedArgsObject, ...options }) : command.toolName;
    const toolParams = command.toolParams({ ...parsedArgsObject, ...options });
    return { toolName, toolParams };
}
function zodParse(schema, data, type) {
    try {
        return schema.parse(data);
    }
    catch (e) {
        throw new Error(e.issues.map(issue => {
            const keys = issue.code === 'unrecognized_keys' ? issue.keys : [''];
            const props = keys.map(key => [...issue.path, key].filter(Boolean).join('.'));
            return props.map(prop => {
                const label = type === 'option' ? `'--${prop}' option` : `'${prop}' argument`;
                switch (issue.code) {
                    case 'invalid_type':
                        return 'error: ' + label + ': ' + issue.message.replace(/Invalid input:/, '').trim();
                    case 'unrecognized_keys':
                        return 'error: unknown ' + label;
                    default:
                        return 'error: ' + label + ': ' + issue.message;
                }
            });
        }).flat().join('\n'));
    }
}
//# sourceMappingURL=command.js.map