package tech.easyflow.ai.node;

import com.easyagents.flow.core.chain.Chain;
import com.easyagents.flow.core.node.BaseNode;
import tech.easyflow.ai.node.filegeneration.FileGenerationRequest;
import tech.easyflow.ai.node.filegeneration.FileGenerationResult;
import tech.easyflow.ai.node.filegeneration.FileGenerationService;
import tech.easyflow.common.filestorage.FileStorageManager;
import tech.easyflow.common.util.SpringContextUtil;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.util.HashMap;
import java.util.Map;

/**
 * 工作流文件导出节点。
 *
 * <p>节点只负责解析运行时参数、委托导出服务生成文件内容，并通过现有文件存储返回下载地址。</p>
 *
 * @author Codex
 * @since 2026-04-18
 */
public class MakeFileNode extends BaseNode {

    private String targetFormat;
    private String sourceFormat;
    private String fileName;
    private String templateStyle;

    public MakeFileNode() {
    }

    public MakeFileNode(String targetFormat, String sourceFormat, String fileName, String templateStyle) {
        this.targetFormat = targetFormat;
        this.sourceFormat = sourceFormat;
        this.fileName = fileName;
        this.templateStyle = templateStyle;
    }

    /**
     * 执行文件导出。
     *
     * @param chain 当前流程链
     * @return 仅包含下载地址的输出对象
     */
    @Override
    public Map<String, Object> execute(Chain chain) {
        Map<String, Object> map = chain.getState().resolveParameters(this);
        Object rawContent = map.get("content");
        if (rawContent == null) {
            throw new BusinessException("文件生成节点缺少 content 参数");
        }
        FileGenerationRequest request = new FileGenerationRequest(
                rawContent.toString(),
                sourceFormat,
                targetFormat,
                fileName,
                templateStyle
        );
        FileGenerationService generationService = SpringContextUtil.getBean(FileGenerationService.class);
        FileGenerationResult result = generationService.generate(request);
        FileStorageManager manager = SpringContextUtil.getBean(FileStorageManager.class);
        Map<String, Object> res = new HashMap<>();
        String url = manager.save(new CustomFile(result.getFileName(), result.getBytes(), result.getContentType()));
        res.put("url", url);
        return res;
    }

    public String getTargetFormat() {
        return targetFormat;
    }

    public void setTargetFormat(String targetFormat) {
        this.targetFormat = targetFormat;
    }

    public String getSourceFormat() {
        return sourceFormat;
    }

    public void setSourceFormat(String sourceFormat) {
        this.sourceFormat = sourceFormat;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getTemplateStyle() {
        return templateStyle;
    }

    public void setTemplateStyle(String templateStyle) {
        this.templateStyle = templateStyle;
    }
}
