"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RootCauseExecutionsApi = void 0;
const runConclusionToTestimExecution_1 = require("./runConclusionToTestimExecution");
const testimExecutionsApi_1 = require("./testimExecutionsApi");
const testimAssetsApi_1 = require("./testimAssetsApi");
const path = __importStar(require("path"));
const fs_1 = require("fs");
const fse = __importStar(require("fs-extra"));
class RootCauseExecutionsApi {
    constructor(testimExecutionsApi = new testimExecutionsApi_1.TestimExecutionsApi(), testimAssetsApi = new testimAssetsApi_1.TestimAssetsApi()) {
        this.testimExecutionsApi = testimExecutionsApi;
        this.testimAssetsApi = testimAssetsApi;
    }
    async createExecution(conclusionFolderPath, testimUserMetadata, progress, signal) {
        const conclusion = require(path.join(conclusionFolderPath, 'runConclusion.json'));
        const filesToUpload = await runConclusionToTestimExecution_1.getRunConclusionFiles(conclusionFolderPath);
        const arbitraryResultsFilePath = filesToUpload.find((file) => file.endsWith('results.json'));
        const gitMetadata = arbitraryResultsFilePath
            ? extractGitMetadata(arbitraryResultsFilePath)
            : undefined;
        const execution = runConclusionToTestimExecution_1.runConclusionToTestimExecution(conclusion, testimUserMetadata, gitMetadata);
        execution.metadata.screenplayFilesUploaded = filesToUpload.length;
        await createTempResultFilesWithResultIds(filesToUpload, execution);
        function isImage(fileName) {
            return fileName.endsWith('.png') || fileName.endsWith('.jpg') || fileName.endsWith('.webp');
        }
        execution.metadata.screenplayImagesUploaded = filesToUpload.filter(isImage).length;
        await this.testimExecutionsApi.createExecution(execution, signal);
        let done = 0;
        const filePromises = filesToUpload.map((file) => this.testimAssetsApi
            .uploadAsset({
            pathInsideBucket: `.root-cause/${conclusion.runId}/${path.relative(conclusionFolderPath, file)}`,
            projectId: testimUserMetadata.projectId,
            asset: fs_1.createReadStream(file.endsWith('results.json') ? `${file.substr(0, file.length - 5)}_tmp.json` : file),
            signal,
        })
            .then(() => {
            done += 1;
            if (progress) {
                progress(done / filesToUpload.length);
            }
        }));
        await Promise.all(filePromises);
        await removeTempResultFiles(filesToUpload);
        return { rootCauseConclusion: conclusion, testimFormat: execution };
    }
}
exports.RootCauseExecutionsApi = RootCauseExecutionsApi;
async function createTempResultFilesWithResultIds(files, execution) {
    var _a;
    const executionResults = Object.keys(execution.execution).map((resultId) => execution.execution[resultId]);
    for (let i = 0; i < files.length; i++) {
        if (files[i].endsWith('results.json')) {
            const resultFile = await fse.readJSON(files[i]);
            resultFile.resultId = (_a = executionResults.find((er) => er.endTime === resultFile.metadata.endedTimestamp)) === null || _a === void 0 ? void 0 : _a.resultId;
            const tempPath = `${files[i].substr(0, files[i].length - 5)}_tmp.json`;
            await fse.writeJSON(tempPath, resultFile);
        }
    }
}
async function removeTempResultFiles(files) {
    for (let i = 0; i < files.length; i++) {
        if (files[i].endsWith('results.json')) {
            const tempPath = `${files[i].substr(0, files[i].length - 5)}_tmp.json`;
            await fse.unlink(tempPath);
        }
    }
}
function extractGitMetadata(fileName) {
    var _a, _b;
    try {
        const testResult = require(fileName);
        const metadata = testResult.metadata.branchInfo;
        if (!metadata) {
            return undefined;
        }
        return {
            gitBranch: metadata.branchName,
            gitCommit: metadata.commitHash,
            gitRepoUrl: (_b = (_a = process.env.GIT_URL) !== null && _a !== void 0 ? _a : process.env.CIRCLE_REPOSITORY_URL) !== null && _b !== void 0 ? _b : '',
        };
    }
    catch (e) {
        return undefined;
    }
}
