package tech.easyflow.ai.easyagentsflow.repository;

import com.easyagents.flow.core.chain.ChainDefinition;
import com.easyagents.flow.core.chain.repository.ChainDefinitionRepository;
import com.easyagents.flow.core.parser.ChainParser;
import org.springframework.stereotype.Component;
import tech.easyflow.ai.easyagentsflow.support.PublishedWorkflowDefinitionIds;
import tech.easyflow.ai.easyagentsflow.service.WorkflowDatacenterContentService;
import tech.easyflow.ai.entity.Workflow;
import tech.easyflow.ai.service.WorkflowService;

import javax.annotation.Resource;

@Component
public class ChainDefinitionRepositoryImpl implements ChainDefinitionRepository {

    @Resource
    private WorkflowService workflowService;
    @Resource
    private ChainParser chainParser;
    @Resource
    private WorkflowDatacenterContentService workflowDatacenterContentService;

    @Override
    public ChainDefinition getChainDefinitionById(String id) {
        boolean publishedDefinition = PublishedWorkflowDefinitionIds.isPublished(id);
        String workflowId = PublishedWorkflowDefinitionIds.unwrap(id);
        Workflow workflow = publishedDefinition
                ? workflowService.getPublishedById(new java.math.BigInteger(workflowId))
                : workflowService.getById(workflowId);
        String json = workflowDatacenterContentService.prepareContent(workflow.getContent());
        ChainDefinition chainDefinition = chainParser.parse(json);
        chainDefinition.setId(id);
        chainDefinition.setName(workflow.getEnglishName());
        chainDefinition.setDescription(workflow.getDescription());
        return chainDefinition;
    }
}
