"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPreviewUrlFromComments = exports.PullRequestState = exports.PullRequestSource = exports.PullRequestProvider = void 0;
var PullRequestProvider;
(function (PullRequestProvider) {
    PullRequestProvider["GITHUB"] = "github";
    PullRequestProvider["GITLAB"] = "gitlab";
})(PullRequestProvider || (exports.PullRequestProvider = PullRequestProvider = {}));
var PullRequestSource;
(function (PullRequestSource) {
    PullRequestSource["CUSTOM_METRIC"] = "custom_metric";
    PullRequestSource["CUSTOM_DIMENSION"] = "custom_dimension";
    PullRequestSource["SQL_RUNNER"] = "sql_runner";
    PullRequestSource["SOURCE_EDITOR"] = "source_editor";
    PullRequestSource["AI_AGENT"] = "ai_agent";
})(PullRequestSource || (exports.PullRequestSource = PullRequestSource = {}));
var PullRequestState;
(function (PullRequestState) {
    PullRequestState["OPEN"] = "open";
    PullRequestState["CLOSED"] = "closed";
    PullRequestState["MERGED"] = "merged";
})(PullRequestState || (exports.PullRequestState = PullRequestState = {}));
const PREVIEW_PROJECT_UUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
/**
 * Find the Lightdash preview-environment URL inside a pull request's comments.
 *
 * When the AI write-back opens a PR against a dbt repo, that repo's CI runs
 * `lightdash preview`, which publishes a PREVIEW-type project and posts its URL
 * (`{siteUrl}/projects/{previewProjectUuid}/...`) as a PR comment. Only URLs on
 * this instance's own host are considered, so a link to github.com or an
 * unrelated site is never mistaken for a preview. Comments are scanned
 * newest-first, so a re-published preview wins. Returns null when none match.
 */
const extractPreviewUrlFromComments = (commentBodies, siteUrl) => {
    let host;
    try {
        host = new URL(siteUrl).host;
    }
    catch {
        return null;
    }
    const escapedHost = host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const previewUrlRegex = new RegExp(`https?://${escapedHost}/projects/${PREVIEW_PROJECT_UUID}(?:/[\\w-]+)*`, 'i');
    for (let i = commentBodies.length - 1; i >= 0; i -= 1) {
        const match = commentBodies[i].match(previewUrlRegex);
        if (match) {
            return match[0];
        }
    }
    return null;
};
exports.extractPreviewUrlFromComments = extractPreviewUrlFromComments;
//# sourceMappingURL=gitIntegration.js.map