"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.publishServiceRuntimeConfigFailureHandoff = publishServiceRuntimeConfigFailureHandoff;
const canonical_workflow_state_1 = require("../../comments/canonical-workflow-state");
const types_1 = require("../../platform/ticket-tracker/types");
const effects_support_1 = require("../../run/run-once-cycle/effects-support");
const issue_branch_target_1 = require("../../run/run-once-cycle/issue-branch-target");
const run_state_helpers_1 = require("../../run/run-once-cycle/run-state-helpers");
const results_1 = require("../../run/run-once-cycle/results");
const shared_1 = require("../../run/run-once-cycle/shared");
const transitions_1 = require("../../run/run-once-cycle/transitions");
const workflow_surface_1 = require("../../run/run-once-cycle/workflow-surface");
const publisher_events_1 = require("../../workflows/publisher-events");
const template_bindings_1 = require("../../workflows/template-bindings");
const default_issue_workspace_manager_1 = require("../../workspaces/default-issue-workspace-manager");
const config_decision_approval_support_1 = require("./config-decision-approval-support");
const config_publish_execution_1 = require("./config-publish-execution");
async function publishServiceRuntimeConfigFailureHandoff(input) {
    const comments = await (0, shared_1.loadSortedIssueComments)(input.ticketTracker, input.issue.id, {
        timeline: "issue-only",
    });
    const responseLanguage = input.config.i18n.defaultLanguage;
    const currentWorkflowStateResolution = (0, canonical_workflow_state_1.resolveCanonicalWorkflowStateComment)(comments, responseLanguage);
    const hasInvalidCanonicalWorkflowState = currentWorkflowStateResolution.kind === "invalid";
    const currentWorkflowState = currentWorkflowStateResolution.kind === "found"
        ? currentWorkflowStateResolution.workflowState
        : null;
    const workflowState = hasInvalidCanonicalWorkflowState
        ? null
        : (0, config_decision_approval_support_1.materializeServiceRuntimeWorkflowState)({
            config: input.config,
            previousState: currentWorkflowState,
            workflowSurface: (0, workflow_surface_1.resolveWorkflowSurface)(input.issue),
            needsHumanReason: publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.systemError,
            resetAiRunBudget: true,
        });
    const isPullRequest = input.issue.kind === types_1.TRACKER_ITEM_KINDS.pullRequest;
    const transitionState = (0, transitions_1.buildWaitHumanTransitionState)({
        config: input.config,
        previousSnapshot: input.issue.workflowState,
        readySnapshot: input.issue.workflowState,
        issue: input.issue,
        runMode: (0, run_state_helpers_1.inferWorkflowRunMode)(workflowState),
        summary: (0, results_1.resolveFailureSummary)(input.error, responseLanguage, input.issue.displayId).public,
        needsHumanReason: publisher_events_1.WORKFLOW_NEEDS_HUMAN_REASONS.systemError,
        facts: {
            ...shared_1.EMPTY_FACTS,
            ...(isPullRequest
                ? {
                    openPullRequestExists: true,
                    pullRequestThreadId: input.issue.id,
                }
                : {}),
        },
        branchName: (0, default_issue_workspace_manager_1.resolveIssueBranchName)(input.config.branchPrefix, input.issue),
        baseBranch: workflowState === null
            ? input.config.repositoryHost.baseBranch
            : (0, issue_branch_target_1.resolveIssueRunBaseBranch)(workflowState),
        pullRequestThreadId: isPullRequest ? input.issue.id : null,
        pullRequestUrl: isPullRequest ? input.issue.url : null,
        workflowTemplateName: workflowState === null
            ? null
            : (0, template_bindings_1.getWorkflowTemplateName)((0, template_bindings_1.getActiveWorkflowTemplateBinding)(workflowState)),
        workflowState,
        consecutiveAiRuns: workflowState?.consecutiveAiRuns ?? 0,
        responseLanguage,
    });
    transitionState.recordsRunOutcome = false;
    transitionState.incrementsConsecutiveAiRuns = false;
    const request = await (0, effects_support_1.buildStandardTransitionPublishRequest)({
        context: {
            config: input.config,
            currentUserLogin: input.currentUserLogin,
            state: transitionState,
            workflowLabels: input.config.ticketTracker.workflowLabels,
        },
        comments,
        workflowState,
    });
    request.invalidWorkflowStatePolicy = "treat_as_missing";
    await (0, config_publish_execution_1.publishServiceRuntimeConfigScanPlan)({
        repoRoot: input.workflowTemplateRepoRoot,
        ticketTrackerKind: input.config.ticketTracker.kind,
        displayTimeZone: input.config.i18n.displayTimeZone,
        workflowLabels: input.config.ticketTracker.workflowLabels,
        ticketTracker: input.ticketTracker,
        plan: {
            kind: "publish",
            decisionKind: "commandless",
            targetIssueId: input.issue.id,
            publish: {
                request,
            },
        },
        openIssues: input.openIssues,
        eventHooks: {
            config: input.config,
            origin: "control_plane_error_handoff",
            run: {
                runMode: transitionState.runMode,
                workerOutcome: transitionState.finalOutcome,
                needsHumanReason: transitionState.needsHumanReason,
                summary: transitionState.summary,
                nextStep: transitionState.presentation.cliNext,
                workflowTemplateName: transitionState.workflowTemplateName,
            },
        },
    });
}
