package com.ycwl.basic.pipeline.core;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 通用 Pipeline 构建器。
 */
public class PipelineBuilder<C extends PipelineContext> {

    private String name = "DefaultPipeline";
    private final List<PipelineStage<C>> stages = new ArrayList<>();

    public PipelineBuilder() {
    }

    public PipelineBuilder(String name) {
        this.name = name;
    }

    public PipelineBuilder<C> name(String name) {
        this.name = name;
        return this;
    }

    public PipelineBuilder<C> addStage(PipelineStage<C> stage) {
        if (stage != null) {
            this.stages.add(stage);
        }
        return this;
    }

    public PipelineBuilder<C> addStages(List<PipelineStage<C>> stages) {
        if (stages != null) {
            this.stages.addAll(stages);
        }
        return this;
    }

    public PipelineBuilder<C> addStageIf(boolean condition, PipelineStage<C> stage) {
        if (condition && stage != null) {
            this.stages.add(stage);
        }
        return this;
    }

    public PipelineBuilder<C> sortByPriority() {
        this.stages.sort(Comparator.comparingInt(PipelineStage::getPriority));
        return this;
    }

    public Pipeline<C> build() {
        if (stages.isEmpty()) {
            throw new IllegalStateException("Pipeline 至少需要一个 Stage");
        }
        return new Pipeline<>(name, stages);
    }
}
