"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPushRejectedError = void 0;
exports.resolveWorkflowStateForPublication = resolveWorkflowStateForPublication;
exports.resolvePublicationTargetForIssue = resolvePublicationTargetForIssue;
exports.buildNeedsHumanVisibleUpdate = buildNeedsHumanVisibleUpdate;
exports.publishControlPlaneNeedsHumanUpdate = publishControlPlaneNeedsHumanUpdate;
exports.withWorkflowStateNeedsHumanReason = withWorkflowStateNeedsHumanReason;
exports.buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage = buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage;
exports.buildNeedsHumanPostMergeLinkedIssueCloseFailureNextMessage = buildNeedsHumanPostMergeLinkedIssueCloseFailureNextMessage;
exports.appendLinkedIssueCloseFailureLogs = appendLinkedIssueCloseFailureLogs;
exports.appendMergeSuccessLog = appendMergeSuccessLog;
exports.appendFinalSummary = appendFinalSummary;
exports.buildNeedsHumanMergeFailureMessage = buildNeedsHumanMergeFailureMessage;
exports.buildNeedsHumanMergedPullRequestCloseFailureMessage = buildNeedsHumanMergedPullRequestCloseFailureMessage;
exports.buildNeedsHumanMergedPullRequestCloseFailureNextMessage = buildNeedsHumanMergedPullRequestCloseFailureNextMessage;
exports.buildNeedsHumanMergeSuccessMessage = buildNeedsHumanMergeSuccessMessage;
exports.buildNeedsHumanMergeNextMessage = buildNeedsHumanMergeNextMessage;
exports.buildNeedsHumanFailureNextMessage = buildNeedsHumanFailureNextMessage;
exports.buildNeedsHumanMergeRaceMessage = buildNeedsHumanMergeRaceMessage;
exports.buildNeedsHumanMergeRaceNextMessage = buildNeedsHumanMergeRaceNextMessage;
exports.buildAutoMergePendingMessage = buildAutoMergePendingMessage;
exports.buildAutoMergePendingNextMessage = buildAutoMergePendingNextMessage;
exports.buildAutoMergeUnavailableMessage = buildAutoMergeUnavailableMessage;
exports.buildAutoMergeUnavailableNextMessage = buildAutoMergeUnavailableNextMessage;
exports.buildAutoMergeConflictReplanMessage = buildAutoMergeConflictReplanMessage;
exports.buildAutoMergeConflictReplanNextMessage = buildAutoMergeConflictReplanNextMessage;
exports.buildDependencyIntegratedSummary = buildDependencyIntegratedSummary;
exports.buildDependencyIntegratedNextMessage = buildDependencyIntegratedNextMessage;
exports.buildDependencyRequeueDeferredSummary = buildDependencyRequeueDeferredSummary;
exports.buildDependencyRequeueDeferredNextMessage = buildDependencyRequeueDeferredNextMessage;
const canonical_workflow_state_1 = require("../../comments/canonical-workflow-state");
const workflow_update_1 = require("../../comments/workflow-update");
var push_rejection_1 = require("../../git/push-rejection");
Object.defineProperty(exports, "isPushRejectedError", { enumerable: true, get: function () { return push_rejection_1.isPushRejectedError; } });
const catalog_1 = require("../../i18n/catalog");
const types_1 = require("../../platform/ticket-tracker/types");
const types_2 = require("../../platform/workflow-state/types");
const constants_1 = require("../../worker/constants");
const publisher_events_1 = require("../../workflows/publisher-events");
const publisher_shared_1 = require("../../workflows/publisher-shared");
const visible_update_builders_1 = require("../../workflows/visible-update-builders");
const workflow_projection_support_1 = require("../../workflows/workflow-projection-support");
const log_text_1 = require("../log-text");
const effect_log_1 = require("./effect-log");
const event_hook_publication_1 = require("./event-hook-publication");
const presentation_1 = require("./presentation");
const results_1 = require("./results");
const shared_1 = require("./shared");
function resolveWorkflowStateForPublication(issueComments, responseLanguage) {
    const workflowStateResolution = (0, canonical_workflow_state_1.resolveCanonicalWorkflowStateComment)(issueComments, responseLanguage);
    if (workflowStateResolution.kind === "invalid") {
        throw new Error(workflowStateResolution.summary);
    }
    return workflowStateResolution.kind === "found"
        ? workflowStateResolution.workflowState
        : null;
}
async function resolvePublicationTargetForIssue(context, issue) {
    if (issue.kind !== types_1.TRACKER_ITEM_KINDS.pullRequest) {
        return {
            kind: "existing_issue",
            issueId: issue.id,
            preloadedIssue: issue,
        };
    }
    return {
        kind: "pull_request_thread",
        pullRequestThreadId: issue.id,
        sourceIssueId: (await (0, shared_1.resolveLinkedIssueIdFromPullRequestTimeline)(context.ticketTracker, issue)) ?? issue.id,
        preloadedIssue: issue,
    };
}
function buildNeedsHumanVisibleUpdate(input) {
    return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
        event: input.event ?? publisher_events_1.WORKFLOW_VISIBLE_EVENTS.humanAttentionRequested,
        summary: input.summary,
        next: input.next,
        workerOutcome: constants_1.WORKER_OUTCOMES.waitHuman,
        needsHumanReason: input.needsHumanReason,
    });
}
async function publishControlPlaneNeedsHumanUpdate(input) {
    const needsHumanReason = input.needsHumanReason ?? publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.systemError;
    const comments = await (0, shared_1.loadSortedIssueComments)(input.context.ticketTracker, input.issue.id);
    const previousWorkflowState = resolveWorkflowStateForPublication(comments, input.responseLanguage);
    const nextWorkflowState = withWorkflowStateNeedsHumanReason(previousWorkflowState, needsHumanReason);
    const visibleUpdate = buildNeedsHumanVisibleUpdate({
        summary: input.summary,
        next: input.next,
        needsHumanReason,
    });
    const workflowProjection = (0, workflow_projection_support_1.buildWorkflowProjectionWithAuxiliaryLabels)({
        workflowLabels: input.context.config.ticketTracker.workflowLabels,
        previous: input.issue.workflowState,
        next: {
            status: types_2.WORKFLOW_STATUSES.aiNeedsHuman,
            rules: [...input.issue.workflowState.rules],
        },
        previousWorkflowState,
        nextWorkflowState,
        previousNeedsHumanReason: (0, workflow_update_1.findLatestNeedsHumanReason)(comments) ??
            previousWorkflowState?.needsHumanReason ??
            null,
        nextNeedsHumanReason: needsHumanReason,
        ...(input.issue.labelNames !== undefined &&
            input.issue.labelNames.length > 0
            ? { currentLabelNames: input.issue.labelNames }
            : {}),
    });
    const request = {
        target: await resolvePublicationTargetForIssue(input.context, input.issue),
        workflowState: nextWorkflowState,
        workflowProjection,
        visibleUpdate,
        commentCursorPolicy: {
            mode: publisher_shared_1.WORKFLOW_COMMENT_CURSOR_POLICY_MODES.preserve,
        },
        responseLanguage: input.responseLanguage,
    };
    return (0, event_hook_publication_1.publishRunWorkflowWithEventHooks)({
        context: input.context,
        request,
        ...(input.eventHookOrigin !== undefined
            ? { origin: input.eventHookOrigin }
            : {}),
        run: input.eventHookRun ?? null,
        ...(input.eventHookLogger !== undefined
            ? { logger: input.eventHookLogger }
            : {}),
    });
}
function withWorkflowStateNeedsHumanReason(workflowState, needsHumanReason) {
    return workflowState === null
        ? null
        : {
            ...workflowState,
            needsHumanReason,
        };
}
function buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.linkedIssueClose.failure");
}
function buildNeedsHumanPostMergeLinkedIssueCloseFailureNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.linkedIssueClose.next");
}
async function appendLinkedIssueCloseFailureLogs(input, error) {
    await (0, effect_log_1.appendEffectResultLog)(input.logger, [
        (0, log_text_1.issueLogField)("effect", "merge_pull_request"),
        (0, log_text_1.issueLogField)("pr", input.pullRequest.url),
        (0, log_text_1.issueLogField)("branch", input.branchName),
        (0, log_text_1.issueLogField)("note", `linked_issue_close_failed:${input.linkedIssueId}`),
    ]);
    await (0, effect_log_1.appendEffectFailureLog)(input.logger, [
        (0, log_text_1.issueLogField)("effect", "close_linked_issue_after_merge"),
        (0, log_text_1.issueLogField)("note", `linked_issue:${input.linkedIssueId}`),
        (0, results_1.renderFailureDetails)(error, input.logger.locale),
    ]);
}
async function appendMergeSuccessLog(input) {
    await (0, effect_log_1.appendEffectResultLog)(input.logger, [
        (0, log_text_1.issueLogField)("effect", "merge_pull_request"),
        (0, log_text_1.issueLogField)("pr", input.pullRequest.url),
        (0, log_text_1.issueLogField)("branch", input.branchName),
        (0, log_text_1.issueLogField)("note", input.shouldCloseLinkedIssue
            ? `closed_linked_issue:${input.linkedIssueId}`
            : "no_linked_issue"),
    ]);
}
async function appendFinalSummary(logger, summary) {
    await logger.appendSection((0, log_text_1.issueLogSection)("finalSummary"), (0, presentation_1.renderCliSummary)(summary, logger.locale));
    return summary;
}
function buildNeedsHumanMergeFailureMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.failure");
}
function buildNeedsHumanMergedPullRequestCloseFailureMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.close.failure");
}
function buildNeedsHumanMergedPullRequestCloseFailureNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.close.next");
}
function buildNeedsHumanMergeSuccessMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.success");
}
function buildNeedsHumanMergeNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.next");
}
function buildNeedsHumanFailureNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.failure.next");
}
function buildNeedsHumanMergeRaceMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.race");
}
function buildNeedsHumanMergeRaceNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.race.next");
}
function buildAutoMergePendingMessage(responseLanguage, dependencyIssueIds) {
    if (dependencyIssueIds !== undefined && dependencyIssueIds.length > 0) {
        return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.pending.dependencies", {
            dependencyRefs: formatDependencyRefs(dependencyIssueIds),
        });
    }
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.pending");
}
function buildAutoMergePendingNextMessage(responseLanguage, dependencyIssueIds) {
    if (dependencyIssueIds !== undefined && dependencyIssueIds.length > 0) {
        return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.pending.dependencies.next", {
            dependencyRefs: formatDependencyRefs(dependencyIssueIds),
        });
    }
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.pending.next");
}
function buildAutoMergeUnavailableMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.unavailable");
}
function buildAutoMergeUnavailableNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.unavailable.next");
}
function buildAutoMergeConflictReplanMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.conflictReplan");
}
function buildAutoMergeConflictReplanNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.conflictReplan.next");
}
function buildDependencyIntegratedSummary(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.dependencyIntegrated");
}
function buildDependencyIntegratedNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.dependencyIntegrated.next");
}
function buildDependencyRequeueDeferredSummary(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.dependencyRequeueDeferred");
}
function buildDependencyRequeueDeferredNextMessage(responseLanguage) {
    return (0, catalog_1.translate)(responseLanguage, "run.needsHuman.merge.dependencyRequeueDeferred.next");
}
function formatDependencyRefs(dependencyIssueIds) {
    return [...new Set(dependencyIssueIds)]
        .sort((left, right) => {
        const leftNumber = Number(left);
        const rightNumber = Number(right);
        if (Number.isFinite(leftNumber) && Number.isFinite(rightNumber)) {
            return leftNumber - rightNumber;
        }
        return left.localeCompare(right);
    })
        .map((issueId) => `#${issueId}`)
        .join(", ");
}
