import { formatOutput, formatWarning } from '../output.js';
import { withMcpClient } from '../helpers.js';
import { parseCommandArgs, hasStdinData, readStdinArgs } from '../parser.js';
import { ClientError } from '../../lib/errors.js';
import { loadSchemaFromFile, validatePromptSchema, formatValidationError, } from '../../lib/schema-validator.js';
export async function listPrompts(target, options) {
    await withMcpClient(target, options, async (client, _context) => {
        const allPrompts = [];
        let cursor = undefined;
        do {
            const result = await client.listPrompts(cursor);
            allPrompts.push(...result.prompts);
            cursor = result.nextCursor;
        } while (cursor);
        console.log(formatOutput(allPrompts, options.outputMode));
    });
}
export async function getPrompt(target, name, options) {
    let parsedArgs;
    if (options.args && options.args.length > 0) {
        parsedArgs = parseCommandArgs(options.args);
    }
    else if (hasStdinData()) {
        parsedArgs = await readStdinArgs();
    }
    else {
        parsedArgs = {};
    }
    const promptArgs = {};
    for (const [key, value] of Object.entries(parsedArgs)) {
        promptArgs[key] = typeof value === 'string' ? value : JSON.stringify(value);
    }
    let expectedSchema;
    if (options.schema) {
        expectedSchema = (await loadSchemaFromFile(options.schema));
    }
    await withMcpClient(target, options, async (client, _context) => {
        const schemaMode = options.schemaMode || 'compatible';
        if (expectedSchema && schemaMode !== 'ignore') {
            const result = await client.listPrompts();
            const actualSchema = result.prompts.find((p) => p.name === name);
            if (!actualSchema) {
                throw new ClientError(`Prompt not found: ${name}`);
            }
            const validation = validatePromptSchema(actualSchema, expectedSchema, schemaMode, promptArgs);
            if (!validation.valid) {
                throw new ClientError(formatValidationError(validation, `prompt "${name}"`));
            }
            if (validation.warnings.length > 0 && options.outputMode === 'human') {
                for (const warning of validation.warnings) {
                    console.log(formatWarning(`Schema warning: ${warning}`));
                }
            }
        }
        const result = await client.getPrompt(name, promptArgs);
        console.log(formatOutput(result, options.outputMode));
    });
}
//# sourceMappingURL=prompts.js.map