import { resolveMcpAuthStatus } from './auth-status.js';
import { getMcpConfigPath, upsertMcpServerConfig } from './config.js';
import { getHostedMcpOAuthProviderId } from './hosted-oauth-id.js';
import { registerHostedMcpOAuthProviders, unregisterHostedMcpOAuthProviders } from './hosted-oauth-provider.js';
function getConfigPath(options) {
    return getMcpConfigPath(options.globalConfigDir);
}
export function validateHostedMcpInstallInput(name, url) {
    if (!/^[A-Za-z0-9._-]+$/.test(name)) {
        throw new Error('MCP server name must contain only letters, numbers, dots, underscores, or dashes.');
    }
    const parsed = new URL(url);
    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
        throw new Error('Hosted MCP URL must start with http:// or https://.');
    }
    const pathname = parsed.pathname.replace(/\/+$/, '').toLowerCase();
    if (pathname.endsWith('/sse')) {
        throw new Error([
            `Hosted MCP URL '${url}' looks like a legacy SSE endpoint.`,
            'ShortcutXL currently installs streamable HTTP MCP servers with --url.',
            "Use the provider's streamable HTTP /mcp URL instead, for example https://mcp.notion.com/mcp for Notion."
        ].join(' '));
    }
}
export async function installHostedMcpServer(options) {
    validateHostedMcpInstallInput(options.name, options.url);
    const configPath = getConfigPath(options);
    const serverConfig = {
        transport: 'streamable_http',
        url: options.url,
        ...(options.providerName
            ? {
                oauth: {
                    providerName: options.providerName
                }
            }
            : {})
    };
    upsertMcpServerConfig(configPath, options.name, serverConfig, { force: options.force });
    const providerIds = registerHostedMcpOAuthProviders({ [options.name]: serverConfig }, options.authStorage, options.mcpOAuthStore);
    try {
        const authStatus = await resolveMcpAuthStatus(options.name, serverConfig, {
            authStorage: options.authStorage,
            mcpOAuthStore: options.mcpOAuthStore,
            discovery: 'network'
        });
        return {
            configPath,
            providerId: authStatus === 'unsupported'
                ? undefined
                : getHostedMcpOAuthProviderId(options.name, serverConfig),
            providerName: authStatus === 'unsupported'
                ? undefined
                : (serverConfig.oauth?.providerName ?? `MCP: ${options.name}`),
            authStatus: authStatus === 'oauth' || authStatus === 'not_logged_in' || authStatus === 'configured'
                ? authStatus
                : 'unsupported'
        };
    }
    finally {
        if (!options.keepProviderRegistered) {
            for (const providerId of providerIds) {
                unregisterHostedMcpOAuthProviders([providerId]);
            }
        }
    }
}
//# sourceMappingURL=install.js.map