"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.finalizeMergedPullRequestOrBuildSummary = finalizeMergedPullRequestOrBuildSummary;
exports.closeLinkedIssueAfterMergeOrBuildSummary = closeLinkedIssueAfterMergeOrBuildSummary;
const workflow_update_1 = require("../../comments/workflow-update");
const types_1 = require("../../platform/workflow-state/types");
const constants_1 = require("../../worker/constants");
const publisher_1 = require("../../workflows/publisher");
const publisher_shared_1 = require("../../workflows/publisher-shared");
const visible_update_builders_1 = require("../../workflows/visible-update-builders");
const publisher_events_1 = require("../../workflows/publisher-events");
const workflow_projection_support_1 = require("../../workflows/workflow-projection-support");
const constants_2 = require("../constants");
const log_text_1 = require("../log-text");
const effect_log_1 = require("./effect-log");
const event_hook_publication_1 = require("./event-hook-publication");
const effects_1 = require("./effects");
const merge_finalization_closing_1 = require("./merge-finalization-closing");
const needs_human_merge_support_1 = require("./needs-human-merge-support");
const pr_publication_1 = require("./pr-publication");
const publisher_factory_1 = require("./publisher-factory");
const results_1 = require("./results");
const shared_1 = require("./shared");
async function publishPullRequestCloseFailedUpdate(input) {
    const needsHumanReason = publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.closeFailed;
    const nextWorkflowState = (0, needs_human_merge_support_1.withWorkflowStateNeedsHumanReason)(input.workflowState, needsHumanReason);
    const request = {
        target: await (0, needs_human_merge_support_1.resolvePublicationTargetForIssue)(input.context, input.issue),
        workflowState: nextWorkflowState,
        workflowProjection: (0, workflow_projection_support_1.buildWorkflowProjectionWithAuxiliaryLabels)({
            workflowLabels: input.context.config.ticketTracker.workflowLabels,
            previous: input.issue.workflowState,
            next: {
                status: types_1.WORKFLOW_STATUSES.aiNeedsHuman,
                rules: [...input.issue.workflowState.rules],
            },
            previousWorkflowState: input.workflowState,
            nextWorkflowState,
            previousNeedsHumanReason: input.workflowState?.needsHumanReason ?? null,
            nextNeedsHumanReason: needsHumanReason,
            ...(input.issue.labelNames !== undefined &&
                input.issue.labelNames.length > 0
                ? { currentLabelNames: input.issue.labelNames }
                : {}),
        }),
        visibleUpdate: (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
            event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.humanAttentionRequested,
            summary: (0, needs_human_merge_support_1.buildNeedsHumanMergedPullRequestCloseFailureMessage)(input.responseLanguage),
            next: (0, needs_human_merge_support_1.buildNeedsHumanMergedPullRequestCloseFailureNextMessage)(input.responseLanguage),
            workerOutcome: constants_1.WORKER_OUTCOMES.waitHuman,
            needsHumanReason,
        }),
        ...(input.trackerTitle !== undefined
            ? {
                trackerFields: {
                    title: input.trackerTitle,
                },
            }
            : {}),
        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,
        origin: "control_plane_error_handoff",
    });
}
async function finalizeMergedPullRequestOrBuildSummary(input) {
    const previousNeedsHumanReason = input.previousNeedsHumanReason ??
        (0, workflow_update_1.findLatestNeedsHumanReason)(input.issueComments);
    const workflowState = input.workflowState ??
        (0, needs_human_merge_support_1.resolveWorkflowStateForPublication)(input.issueComments, input.responseLanguage);
    const finalizedWorkflowState = workflowState === null
        ? null
        : (0, merge_finalization_closing_1.finalizeWorkflowStateForMerge)(workflowState, input.issue.baseTitle);
    const trackerTitle = (0, effects_1.resolveRenderedTitleIfChanged)({
        issue: input.issue,
        workflowState: finalizedWorkflowState,
        locale: input.responseLanguage,
        surface: "pull_request",
        enabled: input.context.config.ticketTracker.showStepProgressInTitles === true,
    });
    try {
        const plan = (0, pr_publication_1.buildPullRequestMergeFinalizationPublicationPlan)({
            workflowLabels: input.context.config.ticketTracker.workflowLabels,
            responseLanguage: input.responseLanguage,
            pullRequestIssue: input.issue,
            pullRequestSourceIssueId: (0, shared_1.resolveLinkedIssueIdFromPullRequest)({ body: input.issue.body }, input.issueComments) ?? input.issue.id,
            pullRequestWorkflowState: finalizedWorkflowState,
            pullRequestNeedsHumanReason: previousNeedsHumanReason,
            ...(trackerTitle !== null
                ? { pullRequestTrackerTitle: trackerTitle }
                : {}),
        });
        if (plan.kind !== "pr_merge_finalization") {
            throw new Error("Expected a PR merge finalization publication plan.");
        }
        const publication = await (0, event_hook_publication_1.publishRunWorkflowWithEventHooks)({
            context: input.context,
            request: plan.pullRequestThreadRequest,
        });
        if (publication.targetClosed) {
            input.issue.isOpen = false;
        }
        return null;
    }
    catch (error) {
        if ((0, publisher_1.isWorkflowTerminalActionError)(error, "close")) {
            const publication = await publishPullRequestCloseFailedUpdate({
                context: input.context,
                issue: input.issue,
                workflowState: finalizedWorkflowState,
                responseLanguage: input.responseLanguage,
                ...(trackerTitle !== null ? { trackerTitle } : {}),
            });
            await (0, effect_log_1.appendEffectFailureLog)(input.logger, [
                (0, log_text_1.issueLogField)("effect", "close_pull_request_after_merge"),
                (0, log_text_1.issueLogField)("pr", input.pullRequest.url),
                (0, results_1.renderFailureDetails)(error, input.logger.locale),
            ]);
            return (0, results_1.buildRunCliSummary)({
                issue: input.issue,
                outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedHuman,
                responseLanguage: input.responseLanguage,
                summary: (0, needs_human_merge_support_1.buildNeedsHumanMergedPullRequestCloseFailureMessage)(input.responseLanguage),
                commentUrl: (0, publisher_factory_1.resolveRunWorkflowPublicationCommentUrl)(publication),
                prUrl: input.pullRequest.url,
                nextStep: (0, needs_human_merge_support_1.buildNeedsHumanMergedPullRequestCloseFailureNextMessage)(input.responseLanguage),
            });
        }
        const publication = await (0, needs_human_merge_support_1.publishControlPlaneNeedsHumanUpdate)({
            context: input.context,
            issue: input.issue,
            responseLanguage: input.responseLanguage,
            summary: (0, needs_human_merge_support_1.buildNeedsHumanMergeFailureMessage)(input.responseLanguage),
            next: (0, needs_human_merge_support_1.buildNeedsHumanFailureNextMessage)(input.responseLanguage),
            eventHookOrigin: "control_plane_error_handoff",
            eventHookLogger: input.logger,
        });
        await (0, effect_log_1.appendEffectFailureLog)(input.logger, [
            (0, log_text_1.issueLogField)("effect", "finalize_pull_request_after_merge"),
            (0, log_text_1.issueLogField)("pr", input.pullRequest.url),
            (0, results_1.renderFailureDetails)(error, input.logger.locale),
        ]);
        return (0, results_1.buildRunCliSummary)({
            issue: input.issue,
            outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedHuman,
            responseLanguage: input.responseLanguage,
            summary: (0, needs_human_merge_support_1.buildNeedsHumanMergeFailureMessage)(input.responseLanguage),
            commentUrl: publication.visibleUpdateComment?.url ?? null,
            prUrl: input.pullRequest.url,
            nextStep: (0, needs_human_merge_support_1.buildNeedsHumanFailureNextMessage)(input.responseLanguage),
        });
    }
}
async function closeLinkedIssueAfterMergeOrBuildSummary(input) {
    try {
        const linkedIssue = await input.context.ticketTracker.getIssueRecord(input.linkedIssueId);
        const linkedComments = await (0, shared_1.loadSortedIssueComments)(input.context.ticketTracker, input.linkedIssueId, { timeline: "issue-only" });
        const closingTransition = await (0, merge_finalization_closing_1.publishWorkingInPrMergeFinalization)({
            context: input.context,
            issue: linkedIssue,
            issueComments: linkedComments,
            logger: input.logger,
            pullRequest: input.pullRequest,
            responseLanguage: input.responseLanguage,
        });
        return closingTransition;
    }
    catch (error) {
        const isCloseFailure = (0, publisher_1.isWorkflowTerminalActionError)(error, "close");
        const nextStep = isCloseFailure
            ? (0, needs_human_merge_support_1.buildNeedsHumanPostMergeLinkedIssueCloseFailureNextMessage)(input.responseLanguage)
            : (0, needs_human_merge_support_1.buildNeedsHumanFailureNextMessage)(input.responseLanguage);
        const publication = await (0, needs_human_merge_support_1.publishControlPlaneNeedsHumanUpdate)({
            context: input.context,
            issue: input.issue,
            responseLanguage: input.responseLanguage,
            summary: (0, needs_human_merge_support_1.buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage)(input.responseLanguage),
            next: nextStep,
            needsHumanReason: isCloseFailure
                ? publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.closeFailed
                : publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.systemError,
            eventHookOrigin: "control_plane_error_handoff",
            eventHookLogger: input.logger,
        });
        await (0, needs_human_merge_support_1.appendLinkedIssueCloseFailureLogs)(input, error);
        return (0, results_1.buildRunCliSummary)({
            issue: input.issue,
            outcome: constants_2.RUN_ISSUE_OUTCOMES.queuedHuman,
            responseLanguage: input.responseLanguage,
            summary: (0, needs_human_merge_support_1.buildNeedsHumanPostMergeLinkedIssueCloseFailureMessage)(input.responseLanguage),
            commentUrl: publication.visibleUpdateComment?.url ?? null,
            prUrl: input.pullRequest.url,
            nextStep,
        });
    }
}
