"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendFailureSuggestionRequestIfApplicable = void 0;
const guid_1 = require("./testim-services-api/guid");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const node_fetch_1 = __importStar(require("node-fetch"));
const debug_1 = __importDefault(require("debug"));
const consts_1 = require("./consts");
const loggerError = debug_1.default('root-cause:error');
const GUID_FILE = 'guid_container';
async function sendFailureSuggestionRequestIfApplicable(crashes, artifacts) {
    if (process.env.SUGGESTIONS_OPT_OUT) {
        return;
    }
    let resp;
    try {
        const body = await buildRequest(crashes, artifacts);
        try {
            resp = await sendRequest(body);
        }
        catch (e) {
            loggerError(e);
        }
    }
    catch (e) {
        loggerError(e);
    }
    if (resp && resp.status !== 200) {
        loggerError('sendFailureSuggestionRequestIfApplicable status code is not 200:', resp.status);
    }
    return resp;
}
exports.sendFailureSuggestionRequestIfApplicable = sendFailureSuggestionRequestIfApplicable;
async function buildRequest(crashes, artifacts) {
    return {
        osName: os_1.default.type(),
        uid: await getUID(),
        artifacts,
        age: await getAgeInDays(),
        crashes,
    };
}
async function sendRequest(body) {
    const headers = new node_fetch_1.Headers();
    headers.set('content-type', 'application/json');
    return node_fetch_1.default(`${consts_1.BASE_BACKEND_URL}/suggestions/failureReason`, {
        method: 'POST',
        headers,
        body: JSON.stringify(body),
    });
}
async function getAgeInDays() {
    const creationTime = await getCreationTime();
    const now = Date.now();
    const diffInMs = now - creationTime;
    const diffInDays = Math.floor(diffInMs / (24 * 60 * 60 * 1000));
    return diffInDays;
}
async function getCreationTime() {
    try {
        const statsInfo = fs_extra_1.default.stat(path_1.default.resolve(__dirname, GUID_FILE));
        return (await statsInfo).birthtimeMs;
    }
    catch (e) {
        return Date.now();
    }
}
async function getUID() {
    try {
        const uid = await fs_extra_1.default.readFile(path_1.default.resolve(__dirname, GUID_FILE), 'utf8');
        return uid;
    }
    catch (e) {
        loggerError('guid file not found, generate new one');
        const newUid = guid_1.guid(8);
        try {
            await fs_extra_1.default.writeFile(path_1.default.resolve(__dirname, GUID_FILE), newUid);
        }
        catch (e) {
            loggerError('failed to persist the guid');
            loggerError(e);
        }
        return newUid;
    }
}
