"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.YcmdInstaller = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
const detection_1 = require("./detection");
class YcmdInstaller {
    static YCMD_REPO_URL = 'https://github.com/ycm-core/ycmd.git';
    static getDefaultInstallPath() {
        return path.join(os.homedir(), '.knowhow/ycmd');
    }
    static isInstalledInKnowhow(installPath) {
        const ycmdPath = installPath || this.getDefaultInstallPath();
        return detection_1.YcmdDetection.isValidYcmdInstallation(ycmdPath);
    }
    static async install(installPath) {
        const ycmdPath = installPath || this.getDefaultInstallPath();
        console.log(`Installing ycmd to ${ycmdPath}...`);
        const parentDir = path.dirname(ycmdPath);
        if (!fs.existsSync(parentDir)) {
            fs.mkdirSync(parentDir, { recursive: true });
        }
        this.checkPrerequisites();
        try {
            console.log('Cloning ycmd repository...');
            (0, child_process_1.execSync)(`git clone --recursive ${this.YCMD_REPO_URL} "${ycmdPath}"`, {
                stdio: 'inherit',
                cwd: parentDir
            });
            console.log('Building ycmd...');
            await this.buildYcmd(ycmdPath);
            console.log('ycmd installation completed successfully');
        }
        catch (error) {
            if (fs.existsSync(ycmdPath)) {
                fs.rmSync(ycmdPath, { recursive: true, force: true });
            }
            throw new Error(`Failed to install ycmd: ${error.message}`);
        }
    }
    static async buildYcmd(ycmdPath) {
        const buildScript = path.join(ycmdPath, 'build.py');
        if (!fs.existsSync(buildScript)) {
            throw new Error('build.py not found in ycmd directory');
        }
        const pythonCmd = detection_1.YcmdDetection.getPythonCommand();
        (0, child_process_1.execSync)(`${pythonCmd} build.py --all`, {
            stdio: 'inherit',
            cwd: ycmdPath
        });
    }
    static checkPrerequisites() {
        try {
            (0, child_process_1.execSync)('git --version', { stdio: 'pipe' });
        }
        catch {
            throw new Error('Git is required but not found in PATH');
        }
        if (!detection_1.YcmdDetection.isPythonAvailable()) {
            throw new Error('Python 3 is required but not found in PATH');
        }
        try {
            (0, child_process_1.execSync)('cmake --version', { stdio: 'pipe' });
        }
        catch {
            throw new Error('CMake is required but not found in PATH. Please install cmake.');
        }
        this.checkPlatformPrerequisites();
    }
    static checkPlatformPrerequisites() {
        const platform = os.platform();
        switch (platform) {
            case 'linux':
                try {
                    (0, child_process_1.execSync)('gcc --version', { stdio: 'pipe' });
                }
                catch {
                    throw new Error('GCC compiler is required but not found. Please install build-essential or equivalent.');
                }
                break;
            case 'darwin':
                try {
                    (0, child_process_1.execSync)('xcode-select --print-path', { stdio: 'pipe' });
                }
                catch {
                    throw new Error('Xcode command line tools are required. Please run: xcode-select --install');
                }
                break;
            case 'win32':
                try {
                    (0, child_process_1.execSync)('cl', { stdio: 'pipe' });
                }
                catch {
                    console.warn('Visual Studio Build Tools not detected. ycmd build may fail.');
                }
                break;
            default:
                console.warn(`Platform ${platform} may not be fully supported`);
        }
    }
    static uninstall(installPath) {
        const ycmdPath = installPath || this.getDefaultInstallPath();
        if (fs.existsSync(ycmdPath)) {
            console.log('Uninstalling ycmd...');
            fs.rmSync(ycmdPath, { recursive: true, force: true });
            console.log('ycmd uninstalled successfully');
        }
        else {
            console.log('ycmd is not installed in specified directory');
        }
    }
    static async update(installPath) {
        const ycmdPath = installPath || this.getDefaultInstallPath();
        if (!this.isInstalledInKnowhow(ycmdPath)) {
            throw new Error('ycmd is not installed in specified directory');
        }
        console.log('Updating ycmd...');
        try {
            (0, child_process_1.execSync)('git pull origin master', {
                stdio: 'inherit',
                cwd: ycmdPath
            });
            (0, child_process_1.execSync)('git submodule update --recursive', {
                stdio: 'inherit',
                cwd: ycmdPath
            });
            await this.buildYcmd(ycmdPath);
            console.log('ycmd updated successfully');
        }
        catch (error) {
            throw new Error(`Failed to update ycmd: ${error.message}`);
        }
    }
    static getInstallationInfo(installPath) {
        const ycmdPath = installPath || this.getDefaultInstallPath();
        const isInstalled = this.isInstalledInKnowhow(ycmdPath);
        const otherInstallations = detection_1.YcmdDetection.findInstallations()
            .filter(p => p !== ycmdPath);
        const info = {
            isInstalled,
            hasOtherInstallations: otherInstallations.length > 0,
            otherInstallations
        };
        if (isInstalled) {
            return {
                ...info,
                path: ycmdPath,
                version: this.getVersion(ycmdPath)
            };
        }
        return info;
    }
    static getVersion(ycmdPath) {
        try {
            const versionFile = path.join(ycmdPath, 'ycmd', 'VERSION');
            if (fs.existsSync(versionFile)) {
                return fs.readFileSync(versionFile, 'utf8').trim();
            }
            const gitVersion = (0, child_process_1.execSync)('git describe --tags --abbrev=0', {
                cwd: ycmdPath,
                encoding: 'utf8'
            }).trim();
            return gitVersion;
        }
        catch {
            return undefined;
        }
    }
}
exports.YcmdInstaller = YcmdInstaller;
//# sourceMappingURL=installer.js.map