"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.ensureCli = ensureCli;
const fs = __importStar(require("node:fs/promises"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const https = __importStar(require("node:https"));
const http = __importStar(require("node:http"));
const vscode = __importStar(require("vscode"));
const CLI_NAME = process.platform === 'win32' ? 'neuralinverse.exe' : 'neuralinverse';
async function ensureCli(ctx, deploymentUrl, output) {
    const binDir = path.join(ctx.globalStorageUri.fsPath, 'bin');
    const cliPath = path.join(binDir, CLI_NAME);
    try {
        await fs.access(cliPath);
        output.appendLine(`CLI found at: ${cliPath}`);
        return cliPath;
    }
    catch {
        // not present, try to download
    }
    const enabled = vscode.workspace
        .getConfiguration('neuralinverse.cloud')
        .get('enableDownloads', true);
    if (!enabled) {
        vscode.window.showErrorMessage('Neural Inverse Cloud: CLI not found and downloads are disabled. ' +
            'Install the nicloud CLI manually or enable downloads in settings.');
        return undefined;
    }
    return downloadCli(deploymentUrl, binDir, cliPath, output);
}
async function downloadCli(deploymentUrl, binDir, cliPath, output) {
    const platform = os.platform();
    const arch = os.arch() === 'arm64' ? 'arm64' : 'amd64';
    let osName;
    switch (platform) {
        case 'darwin':
            osName = 'darwin';
            break;
        case 'linux':
            osName = 'linux';
            break;
        case 'win32':
            osName = 'windows';
            break;
        default:
            vscode.window.showErrorMessage(`Neural Inverse Cloud: Unsupported platform: ${platform}`);
            return undefined;
    }
    const downloadUrl = `${deploymentUrl}/bin/neuralinverse-${osName}-${arch}`;
    output.appendLine(`Downloading CLI from: ${downloadUrl}`);
    try {
        await fs.mkdir(binDir, { recursive: true });
        await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Neural Inverse Cloud: Downloading CLI...' }, () => download(downloadUrl, cliPath));
        await fs.chmod(cliPath, 0o755);
        output.appendLine(`CLI downloaded to: ${cliPath}`);
        return cliPath;
    }
    catch (err) {
        output.appendLine(`CLI download failed: ${err}`);
        vscode.window.showErrorMessage(`Neural Inverse Cloud: Failed to download CLI. ${err}`);
        return undefined;
    }
}
function download(url, dest) {
    return new Promise((resolve, reject) => {
        const mod = url.startsWith('https') ? https : http;
        const request = mod.get(url, (res) => {
            if (res.statusCode === 301 || res.statusCode === 302) {
                const location = res.headers.location;
                if (location) {
                    download(location, dest).then(resolve, reject);
                    return;
                }
            }
            if (res.statusCode !== 200) {
                reject(new Error(`HTTP ${res.statusCode}`));
                return;
            }
            const chunks = [];
            res.on('data', (chunk) => chunks.push(chunk));
            res.on('end', async () => {
                try {
                    await fs.writeFile(dest, Buffer.concat(chunks));
                    resolve();
                }
                catch (e) {
                    reject(e);
                }
            });
            res.on('error', reject);
        });
        request.on('error', reject);
    });
}
//# sourceMappingURL=cli.js.map