import chalk from 'chalk';
import { extractSingleTextContent } from './tool-result.js';
import { isValidSessionName } from '../lib/utils.js';
import { getSession } from '../lib/sessions.js';
export { extractSingleTextContent } from './tool-result.js';
function hslToHex(h, s, l) {
    s /= 100;
    l /= 100;
    const a = s * Math.min(l, 1 - l);
    const f = (n) => {
        const k = (n + h / 30) % 12;
        const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
        return Math.round(255 * color).toString(16).padStart(2, '0');
    };
    return `#${f(0)}${f(8)}${f(4)}`;
}
export function rainbow(text) {
    const len = text.length;
    if (len === 0)
        return text;
    return text
        .split('')
        .map((char, i) => {
        const hue = 12 + (i / (len - 1)) * 270;
        const hex = hslToHex(hue, 45, 62);
        return chalk.hex(hex)(char);
    })
        .join('');
}
export function formatOutput(data, mode = 'human', options) {
    if (mode === 'json') {
        return formatJson(data);
    }
    const output = formatHuman(data, options);
    if (!output.endsWith('````') && !output.endsWith('\n')) {
        return output + '\n';
    }
    return output;
}
export function formatJson(data) {
    const json = JSON.stringify(data, null, 2);
    if (!process.stdout.isTTY) {
        return json;
    }
    return highlightJson(json);
}
function highlightJson(json) {
    return json.replace(/("(?:\\.|[^"\\])*")\s*:|("(?:\\.|[^"\\])*")|(\b(?:true|false|null)\b)|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g, (match, key, str, bool, num) => {
        if (key) {
            return chalk.cyan(key) + ':';
        }
        if (str) {
            return chalk.green(str);
        }
        if (bool) {
            return chalk.magenta(bool);
        }
        if (num) {
            return chalk.yellow(num);
        }
        return match;
    });
}
export function formatHuman(data, options) {
    if (data === null || data === undefined) {
        return chalk.gray('(no data)');
    }
    const singleText = extractSingleTextContent(data);
    if (singleText !== undefined) {
        return `${chalk.gray('````')}\n${singleText}\n${chalk.gray('````')}`;
    }
    if (Array.isArray(data)) {
        if (data.length === 0) {
            return chalk.gray('(empty list)');
        }
        const first = data[0];
        if (first && typeof first === 'object') {
            if ('name' in first && 'inputSchema' in first) {
                return formatTools(data, options);
            }
            if ('uriTemplate' in first) {
                return formatResourceTemplates(data);
            }
            if ('uri' in first) {
                return formatResources(data);
            }
            if ('name' in first && 'arguments' in first) {
                return formatPrompts(data);
            }
        }
        return data.map((item) => formatHuman(item)).join('\n');
    }
    if (typeof data === 'object') {
        if (isPromptResult(data)) {
            return formatPromptResult(data);
        }
        return formatObject(data);
    }
    if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
        return String(data);
    }
    return JSON.stringify(data);
}
function formatToolAnnotations(annotations) {
    if (!annotations)
        return null;
    const parts = [];
    if (annotations.readOnlyHint === true) {
        parts.push('read-only');
    }
    else if (annotations.destructiveHint === true) {
        parts.push(chalk.red('destructive'));
    }
    if (annotations.idempotentHint === true) {
        parts.push('idempotent');
    }
    if (annotations.openWorldHint === true) {
        parts.push('open-world');
    }
    return parts.length > 0 ? parts.join(', ') : null;
}
export function formatSchemaType(schema) {
    if (!schema || typeof schema !== 'object') {
        return 'any';
    }
    const schemaType = schema.type;
    if (Array.isArray(schemaType)) {
        return schemaType.join(' | ');
    }
    if (schemaType === 'array' && schema.items) {
        const items = schema.items;
        const itemType = formatSchemaType(items);
        return `array<${itemType}>`;
    }
    if (schemaType === 'object' && schema.properties) {
        return 'object';
    }
    if (schema.enum && Array.isArray(schema.enum)) {
        const enumValues = schema.enum;
        if (enumValues.length <= 5) {
            return enumValues.map((v) => JSON.stringify(v)).join(' | ');
        }
        return `enum(${enumValues.length} values)`;
    }
    if (schema.oneOf && Array.isArray(schema.oneOf)) {
        const types = schema.oneOf.map(formatSchemaType);
        return types.join(' | ');
    }
    if (schema.anyOf && Array.isArray(schema.anyOf)) {
        const types = schema.anyOf.map(formatSchemaType);
        return types.join(' | ');
    }
    if (typeof schemaType === 'string') {
        return schemaType;
    }
    return 'any';
}
function grayBacktick() {
    return chalk.gray('`');
}
function inBackticks(text) {
    return `${grayBacktick()}${chalk.cyan(text)}${grayBacktick()}`;
}
export function formatSimplifiedArgs(schema, indent = '') {
    const lines = [];
    const bullet = chalk.dim('*');
    if (!schema || typeof schema !== 'object') {
        lines.push(`${indent}${bullet} ${chalk.gray('(none)')}`);
        return lines;
    }
    const properties = schema.properties;
    const required = schema.required || [];
    if (!properties || Object.keys(properties).length === 0) {
        lines.push(`${indent}${bullet} ${chalk.gray('(none)')}`);
        return lines;
    }
    for (const [name, propSchema] of Object.entries(properties)) {
        const typeStr = formatSchemaType(propSchema);
        const isRequired = required.includes(name);
        const description = propSchema.description;
        const defaultValue = propSchema.default;
        let line = `${indent}${bullet} ${inBackticks(name)}: ${chalk.yellow(typeStr)}`;
        if (isRequired) {
            line += ` ${chalk.red('[required]')}`;
        }
        if (defaultValue !== undefined) {
            line += chalk.dim(` (default: ${JSON.stringify(defaultValue)})`);
        }
        if (description) {
            line += ` ${chalk.dim('-')} ${description}`;
        }
        lines.push(line);
    }
    return lines;
}
export function formatTools(tools, options) {
    if (options?.full) {
        return formatToolsFull(tools);
    }
    return formatToolsCompact(tools);
}
function formatToolsSummary(tools) {
    const lines = [];
    lines.push(chalk.bold(`Available tools (${tools.length}):`));
    const bullet = chalk.dim('*');
    for (const tool of tools) {
        const annotationsStr = formatToolAnnotations(tool.annotations);
        const annotationsSuffix = annotationsStr ? ` ${chalk.gray(`[${annotationsStr}]`)}` : '';
        lines.push(`${bullet} ${inBackticks(tool.name)}${annotationsSuffix}`);
    }
    return lines;
}
function formatToolsCompact(tools) {
    const lines = formatToolsSummary(tools);
    lines.push('');
    lines.push('For full details, use "tools-list --full" or "tools-get <name>"');
    return lines.join('\n');
}
function formatToolsFull(tools) {
    const lines = formatToolsSummary(tools);
    for (const tool of tools) {
        lines.push('');
        lines.push(chalk.dim('---'));
        lines.push(formatToolDetail(tool));
    }
    return lines.join('\n');
}
export function formatToolDetail(tool) {
    const lines = [];
    const title = tool.annotations?.title;
    if (title) {
        lines.push(chalk.bold(`# ${title}`));
    }
    const annotationsStr = formatToolAnnotations(tool.annotations);
    const annotationsSuffix = annotationsStr ? ` ${chalk.gray(`[${annotationsStr}]`)}` : '';
    lines.push(`${chalk.bold('Tool:')} ${inBackticks(tool.name)}${annotationsSuffix}`);
    lines.push('');
    lines.push(chalk.bold('Input:'));
    const inputArgs = formatSimplifiedArgs(tool.inputSchema, '');
    lines.push(...inputArgs);
    if ('outputSchema' in tool && tool.outputSchema) {
        lines.push('');
        lines.push(chalk.bold('Output:'));
        const outputArgs = formatSimplifiedArgs(tool.outputSchema, '');
        lines.push(...outputArgs);
    }
    if (tool.description) {
        lines.push('');
        lines.push(chalk.bold('Description:'));
        lines.push(chalk.gray('````'));
        lines.push(tool.description);
        lines.push(chalk.gray('````'));
    }
    return lines.join('\n');
}
export function formatResources(resources) {
    const lines = [];
    lines.push(chalk.bold(`Available resources (${resources.length}):`));
    const bullet = chalk.dim('*');
    for (const resource of resources) {
        lines.push(`${bullet} ${inBackticks(resource.uri)}`);
    }
    for (const resource of resources) {
        lines.push('');
        lines.push(chalk.dim('---'));
        lines.push(formatResourceDetail(resource));
    }
    return lines.join('\n');
}
export function formatResourceDetail(resource) {
    const lines = [];
    lines.push(`${chalk.bold('Resource:')} ${inBackticks(resource.uri)}`);
    if (resource.name) {
        lines.push(`${chalk.bold('Name:')} ${resource.name}`);
    }
    if (resource.mimeType) {
        lines.push(`${chalk.bold('MIME type:')} ${chalk.yellow(resource.mimeType)}`);
    }
    lines.push('');
    lines.push(chalk.bold('Description:'));
    if (resource.description) {
        lines.push(chalk.gray('````'));
        lines.push(resource.description);
        lines.push(chalk.gray('````'));
    }
    else {
        lines.push(chalk.gray('````'));
        lines.push(chalk.gray('(no description)'));
        lines.push(chalk.gray('````'));
    }
    return lines.join('\n');
}
export function formatResourceTemplates(templates) {
    const lines = [];
    lines.push(chalk.bold(`Available resource templates (${templates.length}):`));
    const bullet = chalk.dim('*');
    for (const template of templates) {
        lines.push(`${bullet} ${inBackticks(template.uriTemplate)}`);
    }
    for (const template of templates) {
        lines.push('');
        lines.push(chalk.dim('---'));
        lines.push(formatResourceTemplateDetail(template));
    }
    return lines.join('\n');
}
export function formatResourceTemplateDetail(template) {
    const lines = [];
    lines.push(`${chalk.bold('Template:')} ${inBackticks(template.uriTemplate)}`);
    if (template.name) {
        lines.push(`${chalk.bold('Name:')} ${template.name}`);
    }
    if (template.mimeType) {
        lines.push(`${chalk.bold('MIME type:')} ${chalk.yellow(template.mimeType)}`);
    }
    lines.push('');
    lines.push(chalk.bold('Description:'));
    if (template.description) {
        lines.push(chalk.gray('````'));
        lines.push(template.description);
        lines.push(chalk.gray('````'));
    }
    else {
        lines.push(chalk.gray('````'));
        lines.push(chalk.gray('(no description)'));
        lines.push(chalk.gray('````'));
    }
    return lines.join('\n');
}
export function formatPrompts(prompts) {
    const lines = [];
    lines.push(chalk.bold(`Available prompts (${prompts.length}):`));
    const bullet = chalk.dim('*');
    for (const prompt of prompts) {
        lines.push(`${bullet} ${inBackticks(prompt.name)}`);
    }
    for (const prompt of prompts) {
        lines.push('');
        lines.push(chalk.dim('---'));
        lines.push(formatPromptDetail(prompt));
    }
    return lines.join('\n');
}
export function formatPromptDetail(prompt) {
    const lines = [];
    lines.push(`${chalk.bold('Prompt:')} ${inBackticks(prompt.name)}`);
    lines.push('');
    lines.push(chalk.bold('Arguments:'));
    if (prompt.arguments && prompt.arguments.length > 0) {
        for (const arg of prompt.arguments) {
            const typePart = chalk.yellow('string');
            const requiredPart = arg.required ? ` ${chalk.red('[required]')}` : '';
            const description = arg.description ? ` ${chalk.dim('-')} ${arg.description}` : '';
            lines.push(`  ${inBackticks(arg.name)}: ${typePart}${requiredPart}${description}`);
        }
    }
    else {
        lines.push(chalk.gray('  (no arguments)'));
    }
    lines.push('');
    lines.push(chalk.bold('Description:'));
    if (prompt.description) {
        lines.push(chalk.gray('````'));
        lines.push(prompt.description);
        lines.push(chalk.gray('````'));
    }
    else {
        lines.push(chalk.gray('````'));
        lines.push(chalk.gray('(no description)'));
        lines.push(chalk.gray('````'));
    }
    return lines.join('\n');
}
function isPromptResult(data) {
    if (!data || typeof data !== 'object')
        return false;
    const obj = data;
    if (!('messages' in obj) || !Array.isArray(obj.messages))
        return false;
    if (obj.messages.length === 0)
        return false;
    const first = obj.messages[0];
    return 'role' in first && 'content' in first;
}
function formatPromptResult(result) {
    const lines = [];
    if (result.description) {
        lines.push(chalk.bold('Description:'));
        lines.push(chalk.gray('````'));
        lines.push(result.description);
        lines.push(chalk.gray('````'));
        lines.push('');
    }
    lines.push(chalk.bold(`Messages (${result.messages.length}):`));
    for (const message of result.messages) {
        lines.push('');
        lines.push(`${chalk.bold('Role:')} ${chalk.cyan(message.role)}`);
        lines.push(formatPromptContent(message.content));
    }
    return lines.join('\n');
}
function formatPromptContent(content) {
    const lines = [];
    const block = content;
    switch (block.type) {
        case 'text':
            lines.push(chalk.gray('````'));
            lines.push(block.text || '');
            lines.push(chalk.gray('````'));
            break;
        case 'image':
            lines.push(chalk.gray('````'));
            lines.push(`[Image: ${block.mimeType || 'unknown type'}]`);
            if (block.data) {
                lines.push(`${block.data.substring(0, 50)}...`);
            }
            lines.push(chalk.gray('````'));
            break;
        case 'audio':
            lines.push(chalk.gray('````'));
            lines.push(`[Audio: ${block.mimeType || 'unknown type'}]`);
            lines.push(chalk.gray('````'));
            break;
        case 'resource_link':
            lines.push(chalk.gray('````'));
            lines.push(`[Resource link: ${block.uri || 'unknown'}]`);
            lines.push(chalk.gray('````'));
            break;
        case 'resource':
            lines.push(chalk.gray('````'));
            if (block.resource) {
                lines.push(`[Embedded resource: ${block.resource.uri}]`);
                if ('text' in block.resource && block.resource.text) {
                    lines.push(block.resource.text);
                }
            }
            else {
                lines.push('[Embedded resource]');
            }
            lines.push(chalk.gray('````'));
            break;
        default:
            lines.push(chalk.gray('````'));
            lines.push(JSON.stringify(content, null, 2));
            lines.push(chalk.gray('````'));
    }
    return lines.join('\n');
}
export function formatObject(obj) {
    const lines = [];
    for (const [key, value] of Object.entries(obj)) {
        const formattedKey = chalk.cyan(`${key}:`);
        let formattedValue;
        if (value === null || value === undefined) {
            formattedValue = chalk.gray(String(value));
        }
        else if (typeof value === 'object') {
            formattedValue = JSON.stringify(value, null, 2);
        }
        else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
            formattedValue = String(value);
        }
        else {
            formattedValue = JSON.stringify(value);
        }
        lines.push(`${formattedKey} ${formattedValue}`);
    }
    return lines.join('\n');
}
export function formatSuccess(message) {
    return chalk.green(`✓ ${message}`);
}
export function formatError(message) {
    return chalk.red(`✗ ${message}`);
}
export function formatWarning(message) {
    return chalk.yellow(`⚠ ${message}`);
}
export function formatInfo(message) {
    return chalk.cyan(`ℹ ${message}`);
}
function truncateWithEllipsis(str, maxLen) {
    if (str.length <= maxLen + 3)
        return str;
    return str.substring(0, maxLen - 1) + '…';
}
export function formatSessionLine(session) {
    const nameStr = chalk.cyan(session.name);
    let target;
    if (session.server.url) {
        target = session.server.url;
    }
    else {
        target = session.server.command || 'unknown';
        if (session.server.args && session.server.args.length > 0) {
            target += ' ' + session.server.args.join(' ');
        }
    }
    const targetStr = truncateWithEllipsis(target, 80);
    const parts = [];
    if (session.server.command) {
        parts.push('stdio');
    }
    else {
        parts.push('HTTP');
        if (session.profileName) {
            parts.push('OAuth: ' + chalk.magenta(session.profileName) + chalk.dim(''));
        }
    }
    if (session.protocolVersion) {
        parts.push('MCP: ' + session.protocolVersion);
    }
    const infoStr = chalk.dim('(') + chalk.dim(parts.join(', ')) + chalk.dim(')');
    let proxyStr = '';
    if (session.proxy) {
        proxyStr = ' ' + chalk.green('[proxy: ') + chalk.greenBright(`${session.proxy.host}:${session.proxy.port}`) + chalk.green(']');
    }
    return `${nameStr} → ${targetStr} ${infoStr}${proxyStr}`;
}
export async function logTarget(target, options) {
    if (options.outputMode !== 'human' || options.hide) {
        return;
    }
    if (isValidSessionName(target)) {
        const session = await getSession(target);
        if (session) {
            console.log(`[${formatSessionLine(session)}]\n`);
            return;
        }
    }
    const tc = options.serverConfig;
    const mcpVersionStr = options.protocolVersion ? `, MCP: ${options.protocolVersion}` : '';
    if (tc?.command) {
        let targetStr = tc.command;
        if (tc.args && tc.args.length > 0) {
            targetStr += ' ' + tc.args.join(' ');
        }
        targetStr = truncateWithEllipsis(targetStr, 80);
        console.log(`[→ ${targetStr} ${chalk.dim(`(stdio${mcpVersionStr})`)}]`);
        return;
    }
    const serverStr = tc?.url || target;
    const parts = ['HTTP'];
    if (options.profileName) {
        parts.push('OAuth: ' + chalk.magenta(options.profileName));
    }
    if (options.protocolVersion) {
        parts.push('MCP: ' + options.protocolVersion);
    }
    console.log(`[→ ${serverStr} ${chalk.dim('(' + parts.join(', ') + ')')}]\n`);
}
export function formatJsonError(error, code) {
    return formatJson({
        error: error.message,
        code,
    });
}
export function formatServerDetails(details, target) {
    const lines = [];
    const bullet = chalk.dim('*');
    const bt = chalk.gray('`');
    const { serverInfo, capabilities, instructions } = details;
    if (serverInfo) {
        lines.push(chalk.bold('Server:') + ` ${serverInfo.name} (version: ${serverInfo.version || "N/A"})`);
        lines.push('');
    }
    lines.push(chalk.bold('Capabilities:'));
    const capabilityList = [];
    if (capabilities?.tools) {
        capabilityList.push(`${bullet} tools ${capabilities.tools.listChanged ? '(dynamic)' : '(static)'}`);
    }
    if (capabilities?.resources) {
        const features = [];
        if (capabilities.resources.subscribe)
            features.push('subscribe');
        if (capabilities.resources.listChanged)
            features.push('dynamic list');
        const featureStr = features.length > 0 ? ` (supports ${features.join(', ')})` : '';
        capabilityList.push(`${bullet} resources${featureStr}`);
    }
    if (capabilities?.prompts) {
        const featureStr = capabilities.prompts.listChanged ? ' (dynamic list)' : '';
        capabilityList.push(`${bullet} prompts${featureStr}`);
    }
    if (capabilities?.logging) {
        capabilityList.push(`${bullet} logging`);
    }
    if (capabilities?.completions) {
        capabilityList.push(`${bullet} completions`);
    }
    if (capabilityList.length > 0) {
        lines.push(capabilityList.join('\n'));
    }
    else {
        lines.push(`${bullet} (none)`);
    }
    lines.push('');
    lines.push(chalk.bold('Available commands:'));
    const commands = [];
    if (capabilities?.tools) {
        commands.push(`${bullet} ${bt}mcpc ${target} tools-list${bt}`);
        commands.push(`${bullet} ${bt}mcpc ${target} tools-get <name>${bt}`);
        commands.push(`${bullet} ${bt}mcpc ${target} tools-call <name> [arg1:=val1 ... | <args-json> | <stdin]${bt}`);
    }
    if (capabilities?.resources) {
        commands.push(`${bullet} ${bt}mcpc ${target} resources-list${bt}`);
        commands.push(`${bullet} ${bt}mcpc ${target} resources-read <uri>${bt}`);
    }
    if (capabilities?.prompts) {
        commands.push(`${bullet} ${bt}mcpc ${target} prompts-list${bt}`);
        commands.push(`${bullet} ${bt}mcpc ${target} prompts-get <name> [arg1:=val1 ... | <args-json> | <stdin]${bt}`);
    }
    if (capabilities?.logging) {
        commands.push(`${bullet} ${bt}mcpc ${target} logging-set-level <lvl>${bt}`);
    }
    commands.push(`${bullet} ${bt}mcpc ${target} shell${bt}`);
    lines.push(commands.join('\n'));
    lines.push('');
    const trimmed = instructions ? instructions.trim() : '';
    if (trimmed) {
        lines.push(chalk.bold('Instructions:'));
        lines.push(chalk.gray('````'));
        lines.push(trimmed);
        lines.push(chalk.gray('````'));
    }
    return lines.join('\n');
}
//# sourceMappingURL=output.js.map