package tech.easyflow.ai.easyagentsflow.config;

import com.easyagents.flow.core.chain.repository.ChainDefinitionRepository;
import com.easyagents.flow.core.chain.repository.ChainStateRepository;
import com.easyagents.flow.core.chain.repository.NodeStateRepository;
import com.easyagents.flow.core.chain.runtime.ChainExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tech.easyflow.ai.easyagentsflow.listener.ChainErrorListenerForSave;
import tech.easyflow.ai.easyagentsflow.listener.ChainEventListenerForSave;
import tech.easyflow.ai.easyagentsflow.listener.NodeErrorListenerForSave;

import javax.annotation.Resource;

@Configuration
public class ChainExecutorConfig {

    @Resource
    private ChainDefinitionRepository chainDefinitionRepository;
    @Resource
    private ChainStateRepository chainStateRepository;
    @Resource
    private NodeStateRepository nodeStateRepository;
    @Resource
    private ChainEventListenerForSave chainEventListenerForSave;

    @Bean(name = "chainExecutor")
    public ChainExecutor chainExecutor() {

        ChainExecutor chainExecutor = new ChainExecutor(chainDefinitionRepository,
                chainStateRepository,
                nodeStateRepository);

        saveStepsListeners(chainExecutor);

        return chainExecutor;
    }

    /**
     * 步骤保存监听器 - 自行实现
     */
    private void saveStepsListeners(ChainExecutor chainExecutor) {
        chainExecutor.addEventListener(chainEventListenerForSave);
        chainExecutor.addErrorListener(new ChainErrorListenerForSave());
        chainExecutor.addNodeErrorListener(new NodeErrorListenerForSave());
    }
}
