"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.publishPreflightReplanTransition = publishPreflightReplanTransition;
exports.applyWorkflowExecutionMetadata = applyWorkflowExecutionMetadata;
const types_1 = require("../../platform/workflow-state/types");
const constants_1 = require("../../worker/constants");
const types_2 = require("../../worker/types");
const recurring_1 = require("../../workflows/recurring");
const pending_planning_support_1 = require("../../workflows/pending-planning-support");
const issue_branch_target_1 = require("./issue-branch-target");
const shared_1 = require("./shared");
const transition_presentation_1 = require("./transition-presentation");
const workflow_template_root_1 = require("./workflow-template-root");
async function publishPreflightReplanTransition(input) {
    const { context, executable, logger, branchName, responseLanguage, preparation, dependencies, } = input;
    return publishSameIssueReplanTransition({
        context,
        executable,
        logger,
        branchName,
        responseLanguage,
        summary: preparation.summary,
        workflowTemplateName: preparation.workflowTemplateName,
        workflowState: preparation.workflowState,
        pendingPlanningIntent: "replan",
        pendingPlanningReason: preparation.replanReason,
        sameIssueReplanSource: "preflight_template_drift",
        consecutiveAiRuns: preparation.currentConsecutiveAiRuns,
        incrementsConsecutiveAiRuns: false,
        recordsRunOutcome: false,
        dependencies,
    });
}
function applyWorkflowExecutionMetadata(workflowState, input) {
    const nextWorkflowState = {
        ...workflowState,
        lastRunAt: input.recordsRunOutcome
            ? input.executedAt
            : (workflowState.lastRunAt ?? null),
        lastOutcome: input.recordsRunOutcome
            ? input.finalOutcome
            : (workflowState.lastOutcome ?? null),
        nextRunAt: input.recordsRunOutcome &&
            input.finalOutcome === constants_1.WORKER_OUTCOMES.proceed &&
            (0, recurring_1.hasActiveRecurringParentSchedule)(workflowState)
            ? (0, recurring_1.resolveNextRunAtAfterExecution)({
                workflowState,
                executedAt: input.executedAt,
                displayTimeZone: input.displayTimeZone,
            })
            : (workflowState.nextRunAt ?? null),
    };
    if (input.pendingPlanningIntent !== undefined) {
        return (0, pending_planning_support_1.applyPendingPlanningState)(nextWorkflowState, {
            kind: "set",
            pendingPlanningIntent: input.pendingPlanningIntent,
            pendingPlanningReason: input.pendingPlanningReason,
            pendingPlanningSource: input.pendingPlanningSource,
        });
    }
    if (input.shouldClearPendingPlanningIntent) {
        return (0, pending_planning_support_1.applyPendingPlanningState)(nextWorkflowState, { kind: "clear" });
    }
    return nextWorkflowState;
}
async function publishSameIssueReplanTransition(input) {
    const { context, executable, logger, branchName, responseLanguage, summary, workflowTemplateName, workflowState, pendingPlanningIntent, pendingPlanningReason, sameIssueReplanSource, consecutiveAiRuns, incrementsConsecutiveAiRuns, recordsRunOutcome, pullRequestUrl, dependencies, } = input;
    const routing = await dependencies.collectExistingPullRequestResolution(context.ticketTracker, context.repositoryHost, branchName, (0, issue_branch_target_1.resolveIssueRunBaseBranch)(workflowState));
    const isReplan = pendingPlanningIntent === "replan";
    return dependencies.publishTransitionSummary({
        repoRoot: (0, workflow_template_root_1.getWorkflowTemplateRepoRoot)(context),
        config: context.config,
        currentUserLogin: context.currentUserLogin,
        repositoryHost: context.repositoryHost,
        ticketTracker: context.ticketTracker,
        issueId: executable.issue.id,
        transitionState: {
            issue: executable.issue,
            previousSnapshot: executable.snapshot,
            nextSnapshot: (0, shared_1.cloneWorkflowStateSnapshot)(executable.snapshot, executable.snapshot.status === types_1.WORKFLOW_STATUSES.aiRunning
                ? types_1.WORKFLOW_STATUSES.aiRunning
                : types_1.WORKFLOW_STATUSES.aiReady),
            handoffPullRequestSnapshot: null,
            runMode: types_2.WORKER_RUN_MODES.workflowExecute,
            requestedOutcome: constants_1.WORKER_OUTCOMES.proceed,
            finalOutcome: constants_1.WORKER_OUTCOMES.proceed,
            summary,
            comment: null,
            facts: routing.facts,
            branchName,
            baseBranch: (0, issue_branch_target_1.resolveIssueRunBaseBranch)(workflowState),
            pullRequestThreadId: routing.pullRequestThreadId,
            pullRequestUrl: pullRequestUrl ?? routing.pullRequestUrl,
            scannedInputCursor: workflowState?.lastScannedCommentCursor ?? null,
            workflowTemplateName,
            workflowState,
            plannedIssueTitle: null,
            planningIntent: pendingPlanningIntent ?? null,
            sameIssueReplanSource,
            completedPendingReplan: false,
            continuation: isReplan
                ? {
                    strategy: "replan_same_issue",
                    reason: pendingPlanningReason ?? summary,
                }
                : null,
            needsHumanReason: null,
            responseLanguage,
            result: null,
            presentation: (0, transition_presentation_1.buildTransitionPresentation)({
                config: context.config,
                issue: executable.issue,
                finalOutcome: constants_1.WORKER_OUTCOMES.proceed,
                facts: routing.facts,
                summary,
                comment: null,
                consecutiveAiRuns,
                responseLanguage,
                workflowState,
            }),
            incrementsConsecutiveAiRuns: incrementsConsecutiveAiRuns ?? true,
            recordsRunOutcome: recordsRunOutcome ?? true,
        },
        logger,
        workflowLabels: context.config.ticketTracker.workflowLabels,
        fromStatus: executable.snapshot.status,
        resolvedFacts: routing.facts,
        worker: context.worker,
        ...(context.logHomeDirectory !== undefined
            ? { homeDirectory: context.logHomeDirectory }
            : {}),
    });
}
