import { formatErrorMessage, serializeConnectionIssue } from './json-output.js';
import { buildToolDoc } from './list-detail-helpers.js';
import { classifyListError } from './list-format.js';
import { boldText, extraDimText } from './terminal.js';
import { formatTransportSummary } from './transport-utils.js';
export function printSingleServerHeader(definition, toolCount, durationMs, transportSummary, sourcePath, options) {
    const prefix = boldText(definition.name);
    if (definition.description) {
        console.log(`${prefix} - ${extraDimText(definition.description)}`);
    }
    else {
        console.log(prefix);
    }
    const summaryParts = [];
    summaryParts.push(extraDimText(typeof toolCount === 'number' ? `${toolCount} tool${toolCount === 1 ? '' : 's'}` : 'tools unavailable'));
    if (typeof durationMs === 'number') {
        summaryParts.push(extraDimText(`${durationMs}ms`));
    }
    if (transportSummary) {
        summaryParts.push(extraDimText(transportSummary));
    }
    if (sourcePath) {
        summaryParts.push(sourcePath);
    }
    const summaryLine = `  ${summaryParts.join(extraDimText(' · '))}`;
    if (options?.printSummaryNow === false) {
        console.log('');
    }
    else {
        console.log(summaryLine);
        console.log('');
    }
    return summaryLine;
}
export function printToolDetail(definition, metadata, includeSchema, requiredOnly) {
    const exampleOptions = buildExampleOptions(definition);
    const doc = buildToolDoc({
        serverName: definition.name,
        toolName: metadata.tool.name,
        description: metadata.tool.description,
        outputSchema: metadata.tool.outputSchema,
        options: metadata.options,
        requiredOnly,
        colorize: true,
        callSelector: exampleOptions?.selector,
        wrapExampleExpression: exampleOptions?.wrapExpression,
    });
    if (doc.docLines) {
        for (const line of doc.docLines) {
            console.log(`  ${line}`);
        }
    }
    console.log(`  ${doc.signature}`);
    if (doc.optionalSummary && requiredOnly) {
        console.log(`  ${doc.optionalSummary}`);
    }
    if (includeSchema && metadata.tool.inputSchema) {
        console.log(indent(JSON.stringify(metadata.tool.inputSchema, null, 2), '      '));
    }
    console.log('');
    return {
        examples: doc.examples,
        optionalOmitted: doc.hiddenOptions.length > 0,
    };
}
function buildExampleOptions(definition) {
    if (definition.source?.kind !== 'local' || definition.source.path !== '<adhoc>') {
        return undefined;
    }
    if (definition.command.kind === 'http') {
        const url = definition.command.url instanceof URL ? definition.command.url.href : String(definition.command.url);
        return { selector: url, wrapExpression: true };
    }
    return undefined;
}
export function createEmptyStatusCounts() {
    return {
        ok: 0,
        auth: 0,
        offline: 0,
        http: 0,
        error: 0,
    };
}
export function summarizeStatusCounts(entries) {
    const counts = createEmptyStatusCounts();
    entries.forEach((entry) => {
        counts[entry.status] = (counts[entry.status] ?? 0) + 1;
    });
    return counts;
}
export function buildJsonListEntry(result, timeoutSeconds, options) {
    if (result.status === 'ok') {
        return {
            name: result.server.name,
            status: 'ok',
            durationMs: result.durationMs,
            description: result.server.description,
            transport: formatTransportSummary(result.server),
            source: result.server.source,
            sources: options.includeSources ? result.server.sources : undefined,
            tools: result.tools.map((tool) => ({
                name: tool.name,
                description: tool.description,
                inputSchema: options.includeSchemas ? tool.inputSchema : undefined,
                outputSchema: options.includeSchemas ? tool.outputSchema : undefined,
            })),
        };
    }
    const authCommand = buildAuthCommandHint(result.server);
    const advice = classifyListError(result.error, result.server.name, timeoutSeconds, { authCommand });
    return {
        name: result.server.name,
        status: advice.category,
        durationMs: result.durationMs,
        description: result.server.description,
        transport: formatTransportSummary(result.server),
        source: result.server.source,
        sources: options.includeSources ? result.server.sources : undefined,
        issue: serializeConnectionIssue(advice.issue),
        authCommand: advice.authCommand,
        error: formatErrorMessage(result.error),
    };
}
export function createUnknownResult(server) {
    return {
        status: 'error',
        server,
        error: new Error('Unknown server result'),
        durationMs: 0,
    };
}
export function buildAuthCommandHint(definition) {
    if (definition.source?.kind === 'local' && definition.source.path === '<adhoc>') {
        if (definition.command.kind === 'http') {
            const url = definition.command.url instanceof URL ? definition.command.url.href : String(definition.command.url);
            return `mcporter auth ${url}`;
        }
        if (definition.command.kind === 'stdio') {
            const parts = [definition.command.command, ...(definition.command.args ?? [])];
            const rendered = parts.map(quoteCommandSegment).join(' ').trim();
            return rendered.length > 0 ? `mcporter auth --stdio ${rendered}` : 'mcporter auth --stdio';
        }
    }
    return `mcporter auth ${definition.name}`;
}
function indent(text, pad) {
    return text
        .split('\n')
        .map((line) => pad + line)
        .join('\n');
}
function quoteCommandSegment(segment) {
    if (/^[A-Za-z0-9_./:-]+$/.test(segment)) {
        return segment;
    }
    return JSON.stringify(segment);
}
//# sourceMappingURL=list-output.js.map