"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ycmdStart = ycmdStart;
const serverManager_1 = require("../serverManager");
const client_1 = require("../client");
const installer_1 = require("../installer");
const pathUtils_1 = require("../utils/pathUtils");
async function ycmdStart(params = {}) {
    try {
        const installInfo = installer_1.YcmdInstaller.getInstallationInfo();
        if (!installInfo.isInstalled && installInfo.otherInstallations.length === 0) {
            await installer_1.YcmdInstaller.install();
        }
        if ((await serverManager_1.ycmdServerManager.isRunning()) && !params.forceRestart) {
            const serverInfo = serverManager_1.ycmdServerManager.getServerInfo();
            return {
                success: true,
                serverInfo: serverInfo ? {
                    host: serverInfo.host,
                    port: serverInfo.port,
                    status: serverInfo.status,
                    pid: serverInfo.pid
                } : undefined,
                message: 'ycmd server is already running'
            };
        }
        if (params.forceRestart && (await serverManager_1.ycmdServerManager.isRunning())) {
            await serverManager_1.ycmdServerManager.stop();
        }
        const resolvedWorkspaceRoot = (0, pathUtils_1.resolveWorkspaceRoot)();
        const projectRoot = (0, pathUtils_1.findProjectRoot)(resolvedWorkspaceRoot);
        const serverInfo = await serverManager_1.ycmdServerManager.start(projectRoot, params.port);
        const client = new client_1.YcmdClient(serverInfo);
        const isReady = await client.isReady();
        if (!isReady) {
            throw new Error('Server started but is not ready');
        }
        if (projectRoot) {
            try {
                await client.loadExtraConfFile(projectRoot);
            }
            catch (error) {
                console.warn('Failed to load extra conf file:', error);
            }
        }
        return {
            success: true,
            serverInfo: {
                host: serverInfo.host,
                port: serverInfo.port,
                status: serverInfo.status,
                pid: serverInfo.pid
            },
            message: `ycmd server started successfully on ${serverInfo.host}:${serverInfo.port}`
        };
    }
    catch (error) {
        return {
            success: false,
            message: `Failed to start ycmd server: ${error.message}`
        };
    }
}
//# sourceMappingURL=start.js.map