import { DEFAULT_TUI_WS_PORT } from './tui-defaults.js';
/**
 * Resolve TUI WebSocket listen port from CLI args and env (same rules as legacy `index.ts`).
 * `args` should be `process.argv.slice(2)`.
 */
export function resolveTuiWsPort(args, env) {
    const portArgIndex = args.findIndex((arg) => arg === '--port' || arg === '-p');
    if (portArgIndex !== -1 && args[portArgIndex + 1]) {
        const portArg = parseInt(args[portArgIndex + 1], 10);
        if (!isNaN(portArg) && portArg > 0 && portArg <= 65535) {
            return { ok: true, port: portArg };
        }
        return {
            ok: false,
            message: `[ERROR] Invalid port: ${args[portArgIndex + 1]}. Must be between 1 and 65535.`,
        };
    }
    if (env.TUI_PORT) {
        const envPort = parseInt(env.TUI_PORT, 10);
        if (!isNaN(envPort) && envPort > 0 && envPort <= 65535) {
            return { ok: true, port: envPort };
        }
        return {
            ok: false,
            message: `[ERROR] Invalid TUI_PORT environment variable: ${env.TUI_PORT}. Must be between 1 and 65535.`,
        };
    }
    const legacy = env['4RUNR_PORT'];
    if (legacy) {
        const envPort = parseInt(legacy, 10);
        if (!isNaN(envPort) && envPort > 0 && envPort <= 65535) {
            return { ok: true, port: envPort };
        }
        return {
            ok: false,
            message: `[ERROR] Invalid 4RUNR_PORT environment variable: ${legacy}. Must be between 1 and 65535.`,
        };
    }
    return { ok: true, port: DEFAULT_TUI_WS_PORT };
}
//# sourceMappingURL=tui-port-resolver.js.map