const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const { LanguageClient, TransportKind } = require('vscode-languageclient/node');

let client;

function activate(context) {
    // Resolve the binary path relative to the extension folder
    const binaryName = getBinaryName();
    const serverPath = context.asAbsolutePath(path.join('bin', binaryName));

    // Ensure executable permissions on Unix systems
    if (process.platform !== 'win32') {
        try {
            fs.chmodSync(serverPath, '755');
        } catch (e) {
            console.error(`Error setting permissions for ${serverPath}:`, e);
        }
    }

    const serverOptions = {
        run: { command: serverPath, transport: TransportKind.stdio },
        debug: { command: serverPath, transport: TransportKind.stdio }
    };

    const clientOptions = {
        documentSelector: [{ scheme: 'file', language: 'wasot' }]
    };

    client = new LanguageClient(
        'wasotLanguageServer',
        'Wasot Language Server',
        serverOptions,
        clientOptions
    );

    client.start();
}

function getBinaryName() {
    switch (process.platform) {
        case 'win32':
            return 'wasot-lsp-win.exe';
        case 'darwin':
            return 'wasot-lsp-mac';
        default:
            return 'wasot-lsp-linux';
    }
}

function deactivate() {
    if (client) {
        return client.stop();
    }
}

module.exports = { activate, deactivate };
