// SPDX-License-Identifier: Apache-2.0
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var HelmDependencyManager_1;
import * as constants from '../constants.js';
import * as version from '../../../version.js';
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from '../dependency-injection/container-helper.js';
import { InjectTokens } from '../dependency-injection/inject-tokens.js';
import { BaseDependencyManager } from './base-dependency-manager.js';
import { Zippy } from '../zippy.js';
import { PathEx } from '../../business/utils/path-ex.js';
import { PackageDownloader } from '../package-downloader.js';
import util from 'node:util';
import path from 'node:path';
import fs from 'node:fs';
import { SoloError } from '../errors/solo-error.js';
const HELM_RELEASE_BASE_URL = 'https://get.helm.sh';
const HELM_ARTIFACT_TEMPLATE = 'helm-%s-%s-%s.%s';
// Helm uses different file extensions based on OS
const HELM_ARTIFACT_EXT = new Map()
    .set(constants.OS_DARWIN, 'tar.gz')
    .set(constants.OS_LINUX, 'tar.gz')
    .set(constants.OS_WINDOWS, 'zip');
/**
 * Helm dependency manager installs or uninstalls helm client at SOLO_HOME_DIR/bin directory
 */
let HelmDependencyManager = HelmDependencyManager_1 = class HelmDependencyManager extends BaseDependencyManager {
    zippy;
    constructor(downloader, zippy, installationDirectory, osPlatform, osArch, helmVersion) {
        // Patch injected values to handle undefined values
        installationDirectory = patchInject(installationDirectory, InjectTokens.HelmInstallationDir, HelmDependencyManager_1.name);
        osPlatform = patchInject(osPlatform, InjectTokens.OsPlatform, HelmDependencyManager_1.name);
        osArch = patchInject(osArch, InjectTokens.OsArch, HelmDependencyManager_1.name);
        helmVersion = patchInject(helmVersion, InjectTokens.HelmVersion, HelmDependencyManager_1.name);
        downloader = patchInject(downloader, InjectTokens.PackageDownloader, HelmDependencyManager_1.name);
        // Call the base constructor with the Helm-specific parameters
        super(downloader, installationDirectory, osPlatform, osArch, helmVersion || version.HELM_VERSION, constants.HELM, HELM_RELEASE_BASE_URL);
        this.zippy = zippy;
        this.zippy = patchInject(zippy, InjectTokens.Zippy, HelmDependencyManager_1.name);
    }
    /**
     * Get the Helm artifact name based on version, OS, and architecture
     */
    getArtifactName() {
        const fileExtension = HELM_ARTIFACT_EXT.get(this.osPlatform) || 'tar.gz';
        return util.format(HELM_ARTIFACT_TEMPLATE, this.getRequiredVersion(), this.osPlatform, this.osArch, fileExtension);
    }
    /**
     * Process the downloaded Helm package by extracting it and finding the executable
     */
    async processDownloadedPackage(packageFilePath, temporaryDirectory) {
        // Extract the archive
        if (this.osPlatform === constants.OS_WINDOWS) {
            this.zippy.unzip(packageFilePath, temporaryDirectory);
        }
        else {
            this.zippy.untar(packageFilePath, temporaryDirectory);
        }
        // Find the Helm executable inside the extracted directory
        const helmExecutablePath = path.join(temporaryDirectory, `${this.osPlatform}-${this.osArch}`, this.osPlatform === constants.OS_WINDOWS ? `${constants.HELM}.exe` : constants.HELM);
        // Ensure the extracted file exists
        if (!fs.existsSync(helmExecutablePath)) {
            const executablePath = PathEx.join(temporaryDirectory, this.osPlatform === constants.OS_WINDOWS ? `${constants.HELM}.exe` : constants.HELM);
            if (!fs.existsSync(executablePath)) {
                throw new Error(`Helm executable not found in extracted archive: ${executablePath}`);
            }
            return [executablePath];
        }
        return [helmExecutablePath];
    }
    async getVersion(executablePath) {
        try {
            const output = await this.run(`${executablePath} version --short`);
            const parts = output[0].split('+');
            const versionOnly = parts[0];
            this.logger.info(`Helm version: ${versionOnly}`);
            this.logger.debug(`Found ${constants.HELM}:${versionOnly}`);
            return versionOnly;
        }
        catch (error) {
            throw new SoloError('Failed to check helm version', error);
        }
    }
    getDownloadURL() {
        return `${this.downloadBaseUrl}/${this.artifactName}`;
    }
    getChecksumURL() {
        return `${this.downloadURL}.sha256sum`;
    }
};
HelmDependencyManager = HelmDependencyManager_1 = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.PackageDownloader)),
    __param(1, inject(InjectTokens.Zippy)),
    __param(2, inject(InjectTokens.HelmInstallationDir)),
    __param(3, inject(InjectTokens.OsPlatform)),
    __param(4, inject(InjectTokens.OsArch)),
    __param(5, inject(InjectTokens.HelmVersion)),
    __metadata("design:paramtypes", [PackageDownloader,
        Zippy, String, String, String, String])
], HelmDependencyManager);
export { HelmDependencyManager };
//# sourceMappingURL=helm-dependency-manager.js.map