import { getShapeById } from "./util/shapes.js";
export const defaultWorkflow = {
    name: 'default',
    title: 'Default',
    steps: [
        {
            name: 'disabled',
            title: 'Disabled',
            key: 'r1uCfi4ZL',
            color: '#bdbdbd',
            live: false
        },
        {
            name: 'enabled',
            title: 'Enabled',
            key: 'rkhRGs4WL',
            color: '#5cd79b',
            live: true
        }
    ]
};
export function getWorkflow(projectSchema, shapeId) {
    const workflow = getShapeById(projectSchema, shapeId)?.workflow;
    if (workflow) {
        return projectSchema.workflows[workflow] ?? defaultWorkflow;
    }
    return defaultWorkflow;
}
export function statusFallback(workflow, enabled) {
    return workflow.steps.find((workflow) => workflow.live === enabled) ?? workflow.steps[0];
}
export function findWorkflowStep(workflow, keyOrName) {
    const index = workflow.steps.findIndex((workflow) => workflow.key === keyOrName || workflow.name === keyOrName);
    return index === -1 ? undefined : { index, step: workflow.steps[index] };
}
export function getStatusField(workflows, shape) {
    let workflow = defaultWorkflow;
    if (shape.workflow && workflows[shape.workflow]) {
        workflow = workflows[shape.workflow];
    }
    return {
        type: 'string',
        title: 'Status',
        '@workflow': workflow.name
    };
}
export function getStepRange(steps, index, op) {
    if (op === 'eq' || op === 'in') {
        return [steps[index]];
    }
    const offset = op === 'lte' || op === 'gte' ? 0 : 1;
    const start = op === 'gt' || op === 'gte' ? index + offset : 0;
    const end = op === 'lt' || op === 'lte' ? index + 1 - offset : steps.length;
    return steps.slice(start, end);
}
export function getWorkflowStepKeys(workflow, stepKey, op) {
    const context = findWorkflowStep(workflow, stepKey);
    if (!context) {
        throw new Error(`Cannot find step "${stepKey}" in workflow "${workflow.title}"`);
    }
    const { index } = context;
    return getStepRange(workflow.steps, index, op).map((step) => step.key);
}
export function getLiveStepKeys(workflow) {
    return workflow.steps.filter((step) => step.live).map((step) => step.key);
}
