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;
    @Resource
    private WorkflowDefinitionCache workflowDefinitionCache;
    @Resource
    private FrozenWorkflowDefinitionRegistry frozenWorkflowDefinitionRegistry;

    @Override
    public ChainDefinition getChainDefinitionById(String id) {
        ChainDefinition frozen = frozenWorkflowDefinitionRegistry.get(id);
        if (frozen != null) {
            return frozen;
        }
        if (frozenWorkflowDefinitionRegistry.isFrozen(id)) {
            throw new IllegalStateException("Frozen workflow definition is not registered: " + id);
        }
        return workflowDefinitionCache.get(id, () -> loadAndCompile(id));
    }

    /**
     * 从持久层加载工作流并编译定义。
     *
     * @param id 定义 ID
     * @return 已编译工作流定义
     */
    private ChainDefinition loadAndCompile(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);
        if (workflow == null) {
            throw new IllegalStateException("Workflow not found: " + 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;
    }
}
