"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildPersistedWorkflowState = buildPersistedWorkflowState;
const auto_merge_state_1 = require("../auto-merge-state");
const types_1 = require("../types");
const recurring_auto_stop_1 = require("../recurring-auto-stop");
const scheduled_run_1 = require("../scheduled-run");
const _1 = require("./");
const pending_planning_validation_1 = require("./pending-planning-validation");
// biome-ignore lint/complexity: Persisted workflow-state assembly keeps hierarchical validation and stored-shape construction aligned.
function buildPersistedWorkflowState(input) {
    const schedule = (0, _1.normalizeWorkflowScheduleState)(input.schedule);
    const parentLink = normalizeWorkflowParentLink(input.parentLink);
    const originLink = (0, _1.coerceWorkflowOriginLink)(input.originLink);
    const executionContract = normalizeWorkflowExecutionContract(input.executionContract);
    if (input.parentLink !== undefined && parentLink === null) {
        throw new Error("Workflow parentLink must include parentRef and childKey.");
    }
    if (executionContract === undefined || executionContract === null) {
        throw new Error("Workflow executionContract must be complete.");
    }
    if (input.originLink !== undefined && originLink === null) {
        throw new Error("Workflow originLink must include followup source issue metadata.");
    }
    if (parentLink !== undefined &&
        parentLink !== null &&
        originLink !== undefined &&
        originLink !== null) {
        throw new Error("Workflow originLink cannot coexist with parentLink.");
    }
    if (parentLink !== undefined &&
        parentLink !== null &&
        (schedule.mode !== "off" ||
            (input.scheduledRun !== undefined &&
                !(0, scheduled_run_1.isCooldownScheduledRunState)(input.scheduledRun)) ||
            (input.recurring !== undefined && input.recurring !== null))) {
        throw new Error("Workflow parentLink cannot coexist with scheduled or recurring state.");
    }
    if (input.recurring !== undefined &&
        input.recurring !== null &&
        (schedule.mode === "off" || input.scheduledRun !== undefined)) {
        throw new Error("Workflow recurring state requires an active recurring schedule.");
    }
    if (schedule.mode !== "off" &&
        input.scheduledRun === undefined &&
        (input.recurring === undefined || input.recurring === null)) {
        throw new Error("Workflow recurring schedule requires recurring parent state.");
    }
    const priorityRank = (0, _1.coerceWorkflowPriorityRank)(input.priorityRank);
    if (priorityRank === undefined) {
        throw new Error("Workflow priorityRank must be null or a non-negative safe integer.");
    }
    const workflowSurface = (0, _1.coerceWorkflowSurface)(input.workflowSurface);
    if (workflowSurface === null) {
        throw new Error("Workflow workflowSurface is required.");
    }
    const pendingPlanningValidationError = (0, pending_planning_validation_1.getPendingPlanningValidationError)(input);
    if (pendingPlanningValidationError !== null) {
        throw new Error(pendingPlanningValidationError);
    }
    const state = {
        version: types_1.WORKFLOW_STATE_VERSION,
        workflowSurface,
        workflowTemplates: input.workflowTemplates,
        baseBranch: input.baseBranch ?? "main",
        priorityRank,
        schedule,
        ...(input.scheduledRun !== undefined
            ? { scheduledRun: input.scheduledRun }
            : {}),
        nextRunAt: (0, _1.coerceNullableString)(input.nextRunAt),
        lastRunAt: (0, _1.coerceNullableString)(input.lastRunAt),
        lastOutcome: (0, _1.coerceWorkflowResultOutcome)(input.lastOutcome),
        plan: (0, _1.normalizeWorkflowPlan)(input.plan),
        planRevision: input.planRevision ?? 0,
        finalResult: null,
        ...(input.executionGuidance !== undefined
            ? { executionGuidance: [...input.executionGuidance] }
            : {}),
        executionContract,
        predictedTouchedPaths: input.predictedTouchedPaths ?? [],
        consecutiveAiRuns: input.consecutiveAiRuns ?? 0,
        totalAiRunHours: input.totalAiRunHours ?? 0,
        lastScannedCommentCursor: input.lastScannedCommentCursor ?? null,
    };
    if (parentLink !== undefined && parentLink !== null) {
        state.parentLink = parentLink;
    }
    if (originLink !== undefined && originLink !== null) {
        state.originLink = originLink;
    }
    if (input.recurring !== undefined && input.recurring !== null) {
        state.recurring = (0, recurring_auto_stop_1.normalizePersistedRecurringState)(input.recurring);
    }
    if (input.configOverrides !== undefined) {
        state.configOverrides = input.configOverrides;
    }
    if (input.parentContractRevision !== undefined) {
        state.parentContractRevision = input.parentContractRevision;
    }
    if (input.parentStepContractSnapshot !== undefined) {
        state.parentStepContractSnapshot = {
            ...input.parentStepContractSnapshot,
            ...(input.parentStepContractSnapshot.instructions !== undefined
                ? { instructions: [...input.parentStepContractSnapshot.instructions] }
                : {}),
            doneWhen: [...input.parentStepContractSnapshot.doneWhen],
            inputs: [...input.parentStepContractSnapshot.inputs],
            outputs: [...input.parentStepContractSnapshot.outputs],
        };
    }
    if (input.pendingChildIssueDecisions !== undefined) {
        state.pendingChildIssueDecisions = input.pendingChildIssueDecisions.map((decision) => ({ ...decision }));
    }
    if (input.detachedFromParentReason !== undefined) {
        state.detachedFromParentReason = (0, _1.coerceNullableString)(input.detachedFromParentReason);
    }
    if (input.cancelledChildReason !== undefined) {
        state.cancelledChildReason = (0, _1.coerceNullableString)(input.cancelledChildReason);
    }
    if (input.dependencySyncState !== undefined) {
        state.dependencySyncState = input.dependencySyncState;
    }
    if (input.executionOwnership !== undefined) {
        state.executionOwnership = input.executionOwnership;
    }
    if (input.foreignInputApproval !== undefined) {
        state.foreignInputApproval = input.foreignInputApproval;
    }
    if (input.needsHumanReason !== undefined) {
        state.needsHumanReason = input.needsHumanReason;
    }
    if (input.pendingWorkflowStartApprovalIntent !== undefined) {
        state.pendingWorkflowStartApprovalIntent =
            input.pendingWorkflowStartApprovalIntent;
    }
    if (input.pendingPlanningIntent !== undefined) {
        state.pendingPlanningIntent = input.pendingPlanningIntent;
    }
    if (input.pendingPlanningReason !== undefined) {
        state.pendingPlanningReason = (0, _1.coerceNullableString)(input.pendingPlanningReason);
    }
    if (input.pendingPlanningSource !== undefined) {
        state.pendingPlanningSource = input.pendingPlanningSource;
    }
    if (input.autoMergeState !== undefined) {
        if (!(0, auto_merge_state_1.isWorkflowAutoMergeState)(input.autoMergeState)) {
            throw new Error("Workflow autoMergeState is invalid.");
        }
        state.autoMergeState = input.autoMergeState;
    }
    if (input.mergeContext !== undefined) {
        state.mergeContext = {
            ...input.mergeContext,
            conflictedFiles: [...input.mergeContext.conflictedFiles],
        };
    }
    if (input.pullRequestReviewNecessity !== undefined) {
        state.pullRequestReviewNecessity = {
            ...input.pullRequestReviewNecessity,
            evidence: [...input.pullRequestReviewNecessity.evidence],
            reviewTriggers: [...input.pullRequestReviewNecessity.reviewTriggers],
            effectivePolicy: {
                ...input.pullRequestReviewNecessity.effectivePolicy,
            },
            evaluationInput: {
                ...input.pullRequestReviewNecessity.evaluationInput,
                ...(input.pullRequestReviewNecessity.evaluationInput.commentCursor !==
                    null
                    ? {
                        commentCursor: {
                            ...input.pullRequestReviewNecessity.evaluationInput
                                .commentCursor,
                        },
                    }
                    : { commentCursor: null }),
                ...(input.pullRequestReviewNecessity.evaluationInput
                    .sourceCommentCursor !== undefined
                    ? {
                        sourceCommentCursor: input.pullRequestReviewNecessity.evaluationInput
                            .sourceCommentCursor === null
                            ? null
                            : {
                                ...input.pullRequestReviewNecessity.evaluationInput
                                    .sourceCommentCursor,
                            },
                    }
                    : {}),
            },
        };
    }
    state.followup = { ...(input.followup ?? (0, types_1.createOffWorkflowFollowupState)()) };
    return state;
}
function normalizeWorkflowParentLink(value) {
    if (value === undefined) {
        return undefined;
    }
    const parentRef = normalizeWorkflowParentRef(value.parentRef);
    const childKey = normalizeWorkflowChildKey(value.childKey);
    if (parentRef === null || parentRef === undefined || childKey === undefined) {
        return null;
    }
    return {
        parentRef,
        childKey,
    };
}
function normalizeWorkflowParentRef(value) {
    const normalized = (0, _1.coerceNullableString)(value);
    if (normalized === null) {
        return null;
    }
    return /^#\d+$/u.test(normalized) ? normalized : null;
}
function normalizeWorkflowChildKey(value) {
    const normalized = (0, _1.coerceNullableString)(value);
    return normalized ?? undefined;
}
function normalizeWorkflowExecutionContract(value) {
    return (0, _1.coerceWorkflowExecutionContract)(value);
}
