// transport-factory.ts — Parses CLI flags and selects the appropriate MCP transport.
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { createHttpTransport } from './http-transport.js';
const VALID_TRANSPORTS = ['stdio', 'http'];
const DEFAULT_PORT = 3100;
const DEFAULT_HOST = '127.0.0.1';
function getFlag(args, name) {
    const prefix = `--${name}=`;
    for (let i = 0; i < args.length; i++) {
        const arg = args[i];
        if (arg?.startsWith(prefix)) {
            return arg.slice(prefix.length);
        }
        if (arg === `--${name}` && i + 1 < args.length) {
            return args[i + 1];
        }
    }
    return undefined;
}
export function parseTransportConfig(args) {
    const transportValue = getFlag(args, 'transport') ?? process.env.TRANSPORT ?? 'stdio';
    if (!VALID_TRANSPORTS.includes(transportValue)) {
        console.error(`[Planu] Unknown transport "${transportValue}". Valid options: ${VALID_TRANSPORTS.join(', ')}`);
        process.exit(1);
    }
    const portStr = getFlag(args, 'port') ?? process.env.PORT;
    const port = portStr ? Number(portStr) : DEFAULT_PORT;
    if (Number.isNaN(port) || port < 1 || port > 65535) {
        console.error(`[Planu] Invalid port "${portStr}". Must be 1–65535.`);
        process.exit(1);
    }
    return {
        transport: transportValue,
        port,
        host: getFlag(args, 'host') ?? process.env.HOST ?? DEFAULT_HOST,
        corsOrigin: getFlag(args, 'cors-origin') ?? process.env.CORS_ORIGIN,
    };
}
export async function selectTransport(server, args, serverFactory) {
    const config = parseTransportConfig(args);
    if (config.transport === 'stdio') {
        const transport = new StdioServerTransport();
        await server.connect(transport);
        installStdioShutdownHandlers(server);
        return;
    }
    // HTTP mode: each session needs its own McpServer instance
    const factory = serverFactory ?? (() => server);
    await createHttpTransport(factory, config);
}
function installStdioShutdownHandlers(server) {
    let shuttingDown = false;
    const shutdown = (reason) => {
        if (shuttingDown) {
            return;
        }
        shuttingDown = true;
        console.error(`[Planu] MCP stdio ${reason}; shutting down.`);
        void server
            .close()
            .catch((err) => {
            console.error('[Planu] Error while closing MCP server:', err);
        })
            .finally(() => {
            process.exit(0);
        });
    };
    process.stdin.once('end', () => {
        shutdown('stdin ended');
    });
    process.stdin.once('close', () => {
        shutdown('stdin closed');
    });
    process.once('SIGTERM', () => {
        shutdown('received SIGTERM');
    });
    process.once('SIGINT', () => {
        shutdown('received SIGINT');
    });
}
//# sourceMappingURL=transport-factory.js.map