"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prDebugDataRe = void 0;
exports.hashBody = hashBody;
exports.getRenovateDebugPayload = getRenovateDebugPayload;
exports.getRenovateConfigHashPayload = getRenovateConfigHashPayload;
exports.getPrBodyStruct = getPrBodyStruct;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const logger_1 = require("../../logger");
const emoji_1 = require("../../util/emoji");
const hash_1 = require("../../util/hash");
const regex_1 = require("../../util/regex");
const string_1 = require("../../util/string");
exports.prDebugDataRe = (0, regex_1.regEx)(/\n?<!--renovate-debug:(?<payload>.*?)-->\n?/);
const renovateConfigHashRe = (0, regex_1.regEx)(/\n?<!--renovate-config-hash:(?<payload>.*?)-->\n?/);
const prCheckboxRe = (0, regex_1.regEx)(/- (?<checkbox>\[[\sx]]) <!-- rebase-check -->/);
function noWhitespaceOrHeadings(input) {
    return input.replace((0, regex_1.regEx)(/\r?\n|\r|\s|#/g), '');
}
const reviewableRegex = (0, regex_1.regEx)(/\s*<!-- Reviewable:start -->/);
function hashBody(body) {
    let result = body?.trim() ?? '';
    result = result.replace(exports.prDebugDataRe, '');
    const reviewableIndex = result.search(reviewableRegex);
    if (reviewableIndex > -1) {
        result = result.slice(0, reviewableIndex);
    }
    result = (0, emoji_1.stripEmojis)(result);
    result = noWhitespaceOrHeadings(result);
    result = (0, hash_1.toSha256)(result);
    return result;
}
function isRebaseRequested(body) {
    const match = prCheckboxRe.exec(body);
    if (!match) {
        return undefined;
    }
    return match.groups?.checkbox === '[x]';
}
function getRenovateDebugPayload(body) {
    const match = exports.prDebugDataRe.exec(body);
    return match?.groups?.payload;
}
function getRenovateConfigHashPayload(body) {
    const match = renovateConfigHashRe.exec(body);
    return match?.groups?.payload;
}
function getPrBodyStruct(input) {
    const body = input ?? '';
    const hash = hashBody(body);
    const result = { hash };
    const rebaseRequested = isRebaseRequested(body);
    if (!is_1.default.undefined(rebaseRequested)) {
        result.rebaseRequested = rebaseRequested;
    }
    const rawConfigHash = getRenovateConfigHashPayload(body);
    if (rawConfigHash) {
        result.rawConfigHash = rawConfigHash;
    }
    const debugPayload = getRenovateDebugPayload(body);
    if (debugPayload) {
        try {
            result.debugData = JSON.parse((0, string_1.fromBase64)(debugPayload));
        }
        catch (e) {
            logger_1.logger.warn('Unable to read and parse debugData from the PR');
        }
    }
    return result;
}
//# sourceMappingURL=pr-body.js.map