"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildWorkflowStateForRoute = buildWorkflowStateForRoute;
const control_plane_config_1 = require("../config/control-plane-config");
const command_apply_1 = require("./command-apply");
const followup_policy_1 = require("./followup-policy");
const pre_plan_state_1 = require("./pre-plan-state");
const template_bindings_1 = require("./template-bindings");
const types_1 = require("./types");
function buildWorkflowStateForRoute(input) {
    const stickyState = input.prepared.normalizedStickyState;
    const shouldResetPlan = input.route.kind !== "execute";
    if (stickyState !== null && !shouldResetPlan) {
        const nextState = (0, command_apply_1.applyAppliedWorkflowCommandToPersistedState)(stickyState, input.prepared.appliedCommandState);
        nextState.nextRunAt = stickyState.nextRunAt ?? null;
        nextState.lastRunAt = stickyState.lastRunAt ?? null;
        nextState.lastOutcome = stickyState.lastOutcome ?? null;
        nextState.workflowSurface = input.prepared.workflowSurface;
        nextState.workflowTemplates = buildWorkflowTemplatesForRoute(input);
        return nextState;
    }
    return (0, pre_plan_state_1.buildSelectionTransitionWorkflowState)({
        previousState: stickyState,
        workflowSurface: input.prepared.workflowSurface,
        workflowTemplates: buildWorkflowTemplatesForRoute(input),
        baseBranch: input.prepared.appliedCommandState.baseBranch,
        ...(input.prepared.appliedCommandState.didUpdateSchedule
            ? { schedule: input.prepared.appliedCommandState.schedule }
            : {}),
        ...(input.prepared.appliedCommandState.didUpdateSchedule
            ? { scheduledRun: null }
            : {}),
        configOverrides: input.prepared.appliedCommandState.configOverrides,
        foreignInputApproval: stickyState?.foreignInputApproval ??
            input.prepared.preCanonicalForeignInputApproval,
        pendingWorkflowStartApprovalIntent: stickyState?.pendingWorkflowStartApprovalIntent,
        pendingPlanningIntent: stickyState?.pendingPlanningIntent,
        pendingPlanningReason: stickyState?.pendingPlanningReason,
        pendingPlanningSource: stickyState?.pendingPlanningSource,
        mergeContext: stickyState?.mergeContext,
        followup: resolveFollowupStateForRoute(input.prepared),
    });
}
function resolveFollowupStateForRoute(prepared) {
    return (0, followup_policy_1.resolveWorkflowFollowupState)({
        currentFollowup: prepared.normalizedStickyState?.followup,
        currentStateExists: prepared.normalizedStickyState !== null,
        config: prepared.followupConfig,
        refreshPolicy: hasLatestCommandFollowupProposalOverride(prepared),
    });
}
function hasLatestCommandFollowupProposalOverride(prepared) {
    const command = prepared.latestCommand?.command;
    if (command?.kind !== "update") {
        return false;
    }
    return (command.configOverridePatch?.entries.some((entry) => entry.path === "followup.proposalPolicy" ||
        entry.path === "followup.proposalApproval") ?? false);
}
function buildWorkflowTemplatesForRoute(input) {
    const stickyTemplates = input.prepared.normalizedStickyState?.workflowTemplates ??
        (0, template_bindings_1.createUnresolvedWorkflowTemplateBindings)(input.prepared.workflowTemplateDefaults ??
            control_plane_config_1.DEFAULT_CONFIG.workflowTemplateDefaults);
    return types_1.WORKFLOW_TEMPLATE_TARGETS.reduce((workflowTemplates, surface) => (0, template_bindings_1.setWorkflowTemplateBinding)({
        workflowTemplates,
        surface,
        binding: resolveWorkflowTemplateBindingForRoute({
            prepared: input.prepared,
            stickyTemplates,
            surface,
        }),
    }), stickyTemplates);
}
function resolveWorkflowTemplateBindingForRoute(input) {
    if (input.prepared.workflowSurface === input.surface) {
        return input.prepared.resolution.binding;
    }
    return (0, template_bindings_1.resolveWorkflowTemplateBinding)({
        catalog: input.prepared.catalog,
        surface: input.surface,
        selector: resolveWorkflowSelectorForState(input.prepared.normalizedStickyState, input.prepared.appliedCommandState, input.surface, input.stickyTemplates),
    });
}
function resolveWorkflowSelectorForState(stickyState, appliedCommandState, surface, stickyTemplates) {
    if ((0, command_apply_1.hasAppliedWorkflowTemplateSelectorUpdate)(appliedCommandState, surface)) {
        return ((0, command_apply_1.getAppliedWorkflowTemplateSelector)(appliedCommandState, surface) ??
            (0, types_1.createAutoSelectWorkflowTemplateSelector)());
    }
    return ((stickyState === null
        ? (0, template_bindings_1.getWorkflowTemplateBinding)({
            workflowTemplates: stickyTemplates,
            surface,
        }).selector
        : (0, template_bindings_1.getWorkflowTemplateBinding)({
            workflowTemplates: stickyState.workflowTemplates,
            surface,
        }).selector) ?? (0, types_1.createAutoSelectWorkflowTemplateSelector)());
}
