"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildStandardTransitionPublishRequest = buildStandardTransitionPublishRequest;
exports.buildPendingWaitHumanPublicationPublishRequest = buildPendingWaitHumanPublicationPublishRequest;
exports.buildStandardTransitionVisibleUpdate = buildStandardTransitionVisibleUpdate;
exports.buildPullRequestHandoffVisibleUpdate = buildPullRequestHandoffVisibleUpdate;
exports.maybePublishLinkedIssueTitleForPullRequest = maybePublishLinkedIssueTitleForPullRequest;
const canonical_workflow_state_1 = require("../../comments/canonical-workflow-state");
const control_plane_config_1 = require("../../config/control-plane-config");
const catalog_1 = require("../../i18n/catalog");
const types_1 = require("../../platform/ticket-tracker/types");
const workflow_labels_1 = require("../../platform/ticket-tracker/workflow-labels");
const constants_1 = require("../../worker/constants");
const publisher_shared_1 = require("../../workflows/publisher-shared");
const publish_precondition_support_1 = require("../../workflows/publish-precondition-support");
const visible_update_builders_1 = require("../../workflows/visible-update-builders");
const publisher_events_1 = require("../../workflows/publisher-events");
const recurring_1 = require("../../workflows/recurring");
const child_issue_title_1 = require("./child-issue-title");
const effects_state_support_1 = require("./effects-state-support");
const results_1 = require("./results");
const shared_1 = require("./shared");
const presentation_1 = require("./presentation");
const run_limit_policy_1 = require("./run-limit-policy");
async function buildStandardTransitionPublishRequest(input) {
    const target = resolveTransitionTarget({
        issue: input.context.state.issue,
        comments: input.comments,
    });
    const terminalSuccessClose = (0, results_1.shouldCloseTerminalWorkflowSuccess)(input.context.state);
    const effectiveConfig = (0, control_plane_config_1.resolveIssueEffectiveConfigForWorkflowState)(input.context.config, input.workflowState);
    const recurringChildBaseTitle = resolvePlannedRecurringChildBaseTitle({
        context: input.context,
        effectiveConfig,
    });
    const trackerTitle = (0, effects_state_support_1.resolveRenderedTitleIfChanged)({
        issue: input.context.state.issue,
        workflowState: input.workflowState,
        ...(recurringChildBaseTitle !== null
            ? { baseTitleOverride: recurringChildBaseTitle }
            : {}),
        locale: input.context.state.responseLanguage,
        suppressDoneLabel: !terminalSuccessClose,
        surface: input.context.state.issue.kind === types_1.TRACKER_ITEM_KINDS.pullRequest
            ? "pull_request"
            : "issue",
        enabled: effectiveConfig.ticketTracker.showStepProgressInTitles === true,
    });
    const postCloseDependencyChanges = terminalSuccessClose
        ? resolveRecurringChildCompletionDependencyChanges(input.context.state.issue)
        : [];
    const publishPrecondition = buildStandardTransitionPublishPrecondition({
        comments: input.comments,
        state: input.context.state,
    });
    return {
        target,
        workflowState: input.workflowState,
        workflowProjection: {
            previous: input.context.state.previousSnapshot,
            next: input.context.state.nextSnapshot,
            ...(input.context.state.labelProjection !== undefined
                ? { labelProjection: input.context.state.labelProjection }
                : {}),
            auxiliaryManagedLabels: {
                previous: (0, workflow_labels_1.pickAuxiliaryManagedLabelNames)(input.context.workflowLabels, input.context.state.issue.labelNames),
                next: (0, workflow_labels_1.resolveAuxiliaryManagedLabelNames)({
                    workflowLabels: input.context.workflowLabels,
                    snapshot: input.context.state.nextSnapshot,
                    needsHumanReason: input.context.state.needsHumanReason,
                    recurringLabelNames: (0, recurring_1.resolveRecurringLabelNames)(input.context.workflowLabels.aiRecurring, input.workflowState),
                }),
            },
        },
        visibleUpdate: await buildStandardTransitionVisibleUpdate({
            context: input.context,
            workflowState: input.workflowState,
        }),
        ...(trackerTitle !== null
            ? {
                trackerFields: {
                    title: trackerTitle,
                },
            }
            : {}),
        ...(input.context.state.invalidWorkflowStatePolicy !== undefined
            ? {
                invalidWorkflowStatePolicy: input.context.state.invalidWorkflowStatePolicy,
            }
            : {}),
        commentCursorPolicy: {
            mode: publisher_shared_1.WORKFLOW_COMMENT_CURSOR_POLICY_MODES.preserve,
        },
        ...(publishPrecondition !== undefined ? { publishPrecondition } : {}),
        ...(terminalSuccessClose
            ? {
                terminalAction: {
                    kind: "close",
                    ...(postCloseDependencyChanges.length > 0
                        ? { postCloseDependencyChanges }
                        : {}),
                },
            }
            : {}),
        responseLanguage: input.context.state.responseLanguage,
    };
}
function buildStandardTransitionPublishPrecondition(input) {
    if (input.state.planningIntent !== "revise_plan") {
        return undefined;
    }
    const currentWorkflowStateResolution = (0, canonical_workflow_state_1.resolveCanonicalWorkflowStateComment)(input.comments, input.state.responseLanguage);
    if (currentWorkflowStateResolution.kind === "invalid") {
        throw new Error(currentWorkflowStateResolution.summary);
    }
    return (0, publish_precondition_support_1.buildWorkflowPublishPrecondition)({
        currentWorkflowStateCommentId: currentWorkflowStateResolution.kind === "found"
            ? currentWorkflowStateResolution.comment.id
            : null,
        workflowState: currentWorkflowStateResolution.kind === "found"
            ? currentWorkflowStateResolution.workflowState
            : null,
    });
}
function buildPendingWaitHumanPublicationPublishRequest(input) {
    const currentWorkflowStateResolution = (0, canonical_workflow_state_1.resolveCanonicalWorkflowStateComment)(input.comments, input.state.responseLanguage);
    if (currentWorkflowStateResolution.kind === "invalid") {
        throw new Error(currentWorkflowStateResolution.summary);
    }
    return {
        ...input.request,
        publishPrecondition: (0, publish_precondition_support_1.buildWorkflowPublishPrecondition)({
            currentWorkflowStateCommentId: currentWorkflowStateResolution.kind === "found"
                ? currentWorkflowStateResolution.comment.id
                : null,
            workflowState: currentWorkflowStateResolution.kind === "found"
                ? currentWorkflowStateResolution.workflowState
                : null,
        }),
    };
}
function resolvePlannedRecurringChildBaseTitle(input) {
    const issue = input.context.state.issue;
    const plannedIssueTitle = input.context.state.plannedIssueTitle?.trim() ?? "";
    if (issue.kind !== types_1.TRACKER_ITEM_KINDS.issue ||
        plannedIssueTitle.length === 0 ||
        input.effectiveConfig.recurring.updateChildTitleAfterPlan !== true ||
        !(0, recurring_1.hasRecurringChildIssueTitlePrefix)(issue.title)) {
        return null;
    }
    const parentIssueId = (0, child_issue_title_1.parseParentIssueIdTitleSuffix)(issue.title);
    if (parentIssueId === null ||
        !(0, child_issue_title_1.hasParentIssueTitleSuffix)(issue.title, parentIssueId)) {
        return null;
    }
    return (0, child_issue_title_1.replaceRecurringChildIssueTitleCoreWithinLimit)(issue.title, plannedIssueTitle, parentIssueId, 180);
}
function resolveRecurringChildCompletionDependencyChanges(issue) {
    if (issue.kind !== types_1.TRACKER_ITEM_KINDS.issue ||
        !(0, recurring_1.hasRecurringChildIssueTitlePrefix)(issue.title)) {
        return [];
    }
    const parentIssueId = (0, child_issue_title_1.parseParentIssueIdTitleSuffix)(issue.title);
    if (parentIssueId === null || parentIssueId === issue.id) {
        return [];
    }
    return [
        {
            kind: "remove_blocking_dependency",
            issue: { kind: "issue", issueId: parentIssueId },
            blockedBy: { kind: "target" },
        },
    ];
}
function resolveTransitionTarget(input) {
    if (input.issue.kind !== types_1.TRACKER_ITEM_KINDS.pullRequest) {
        return {
            kind: "existing_issue",
            issueId: input.issue.id,
            preloadedIssue: input.issue,
        };
    }
    const sourceIssueId = (0, shared_1.resolveLinkedIssueIdFromPullRequest)({ body: input.issue.body }, input.comments);
    if (sourceIssueId === null) {
        return {
            kind: "existing_issue",
            issueId: input.issue.id,
            preloadedIssue: input.issue,
        };
    }
    return {
        kind: "pull_request_thread",
        pullRequestThreadId: input.issue.id,
        sourceIssueId,
        preloadedIssue: input.issue,
    };
}
async function buildStandardTransitionVisibleUpdate(input) {
    if (!(0, effects_state_support_1.shouldPublishWorkflowUpdateComment)(input.context.state)) {
        return null;
    }
    const event = input.eventOverride ??
        (0, effects_state_support_1.resolveVisibleEventForTransition)(input.context.state);
    return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
        event,
        ...(0, effects_state_support_1.resolveWorkflowUpdateTitleForTransitionState)(input.context.state),
        summary: input.context.state.presentation.commentSummary,
        next: (0, effects_state_support_1.resolveCommentNextForWrite)(input.context.state),
        workerOutcome: input.context.state.presentation.commentOutcome,
        ...(input.omitNeedsHumanReason === true ||
            input.context.state.needsHumanReason === null
            ? {}
            : { needsHumanReason: input.context.state.needsHumanReason }),
        ...(input.context.state.workflowTemplateName !== null
            ? { workflowTemplateLabel: input.context.state.workflowTemplateName }
            : {}),
    });
}
async function buildPullRequestHandoffVisibleUpdate(input) {
    const summary = input.sourceWorkflowState !== null
        ? (0, canonical_workflow_state_1.summarizeCanonicalWorkflowState)(input.sourceWorkflowState, input.context.state.responseLanguage, input.context.config.i18n.displayTimeZone, input.context.state.issue.id)
        : null;
    const formattedSummary = (0, effects_state_support_1.formatPullRequestHandoffSummary)({
        sourceIssueDisplayId: input.context.state.issue.displayId,
        sourceIssueUrl: input.context.state.issue.url,
        sourceTitle: input.context.state.issue.baseTitle,
        currentStep: summary?.currentStep ??
            (0, catalog_1.translate)(input.context.state.responseLanguage, "canonicalWorkflowComment.currentStatusCurrentStepUnavailableLabel"),
        goal: input.sourceWorkflowState === null
            ? null
            : input.sourceWorkflowState.executionContract.objective,
    }, input.context.state.responseLanguage);
    if (input.mode === "continue_existing") {
        return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
            event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.prHandoff,
            summary: formattedSummary,
            next: (0, catalog_1.translate)(input.context.state.responseLanguage, "run.presentation.prHandoff.next.continue"),
            workerOutcome: constants_1.WORKER_OUTCOMES.proceed,
        });
    }
    if (input.mode === "proceed") {
        return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
            event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.prHandoff,
            summary: formattedSummary,
            next: (0, catalog_1.translate)(input.context.state.responseLanguage, "run.presentation.prHandoff.next.queued"),
            workerOutcome: constants_1.WORKER_OUTCOMES.proceed,
        });
    }
    if (input.mode === "auto_merge") {
        return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
            event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.prHandoff,
            summary: formattedSummary,
            next: (0, catalog_1.translate)(input.context.state.responseLanguage, "run.presentation.prHandoff.next.autoMerge"),
            workerOutcome: constants_1.WORKER_OUTCOMES.proceed,
        });
    }
    return (0, visible_update_builders_1.buildWorkflowVisibleUpdate)({
        event: publisher_events_1.WORKFLOW_VISIBLE_EVENTS.prHandoff,
        summary: formattedSummary,
        next: input.needsHumanReason === publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.runLimit
            ? buildPullRequestHandoffRunLimitNext(input)
            : (0, catalog_1.translate)(input.context.state.responseLanguage, "run.presentation.prHandoff.next.review"),
        workerOutcome: constants_1.WORKER_OUTCOMES.waitHuman,
        needsHumanReason: input.needsHumanReason ?? publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.reviewReady,
    });
}
function buildPullRequestHandoffRunLimitNext(input) {
    const locale = input.context.state.responseLanguage;
    const effectiveConfig = (0, control_plane_config_1.resolveIssueEffectiveConfigForWorkflowState)(input.context.config, input.sourceWorkflowState);
    const consecutiveAiRuns = input.sourceWorkflowState?.consecutiveAiRuns ?? 0;
    const totalAiRunHours = input.sourceWorkflowState?.totalAiRunHours ?? 0;
    const runLimit = (0, run_limit_policy_1.resolveAiRunLimitPolicy)({
        config: effectiveConfig,
        consecutiveAiRuns,
        totalAiRunHours,
    });
    return (0, catalog_1.translate)(locale, "run.presentation.prHandoff.next.runLimit", {
        runLimitSummary: (0, presentation_1.buildAiRunLimitSummary)(locale, {
            reachedKind: runLimit.reachedKind,
            consecutiveAiRuns,
            totalAiRunHours,
            maxRuns: effectiveConfig.aiRunLimits.maxRuns,
            maxHours: effectiveConfig.aiRunLimits.maxHours,
        }),
    });
}
async function maybePublishLinkedIssueTitleForPullRequest(input) {
    if (!input.context.config.ticketTracker.showStepProgressInTitles ||
        input.context.state.issue.kind !== types_1.TRACKER_ITEM_KINDS.pullRequest) {
        return;
    }
    const linkedIssueId = await (0, shared_1.resolveLinkedIssueIdFromPullRequestTimeline)(input.context.ticketTracker, input.context.state.issue);
    if (linkedIssueId === null) {
        return;
    }
    const linkedIssue = await input.context.ticketTracker.getIssue(linkedIssueId);
    const trackerTitle = (0, effects_state_support_1.resolveRenderedTitleIfChanged)({
        issue: linkedIssue,
        workflowState: input.workflowState,
        locale: input.context.state.responseLanguage,
        suppressDoneLabel: true,
        surface: "linked_issue_in_pr",
        enabled: true,
    });
    if (trackerTitle === null) {
        return;
    }
    await input.publisher.publishWorkflow({
        target: {
            kind: "existing_issue",
            issueId: linkedIssue.id,
            preloadedIssue: linkedIssue,
        },
        workflowState: null,
        trackerFields: {
            title: trackerTitle,
        },
        commentCursorPolicy: {
            mode: publisher_shared_1.WORKFLOW_COMMENT_CURSOR_POLICY_MODES.preserve,
        },
        responseLanguage: input.context.state.responseLanguage,
    });
}
