package tech.easyflow.ai.node.filegeneration;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * 文件导出服务。
 *
 * @author Codex
 * @since 2026-04-18
 */
@Service
public class FileGenerationService {
    private final Map<TargetFormat, DocumentRenderer> rendererMap = new EnumMap<>(TargetFormat.class);

    public FileGenerationService(List<DocumentRenderer> renderers) {
        for (DocumentRenderer renderer : renderers) {
            rendererMap.put(renderer.getTargetFormat(), renderer);
        }
    }

    /**
     * 生成目标格式文件。
     *
     * @param request 原始导出请求
     * @return 文件导出结果
     */
    public FileGenerationResult generate(FileGenerationRequest request) {
        if (request == null) {
            throw new BusinessException("文件导出请求不能为空");
        }
        if (request.getContent() == null) {
            throw new BusinessException("文件导出内容不能为空");
        }
        TargetFormat targetFormat = TargetFormat.fromValue(request.getTargetFormat());
        SourceFormat sourceFormat = SourceFormat.fromValue(request.getSourceFormat());
        FileGenerationRules.requireSupportedCombination(sourceFormat, targetFormat);
        DocumentRenderer renderer = rendererMap.get(targetFormat);
        if (renderer == null) {
            throw new BusinessException("未找到 " + targetFormat.getValue() + " 对应的文件渲染器");
        }
        if (!renderer.supports(sourceFormat)) {
            throw new BusinessException("文件生成节点暂不支持 " + sourceFormat.getValue() + " -> " + targetFormat.getValue() + " 组合");
        }
        String normalizedTemplateStyle = FileGenerationRules.normalizeTemplateStyle(request.getTemplateStyle());
        String normalizedFileName = FileNameSanitizer.sanitize(request.getFileName(), targetFormat);
        FileGenerationRequest normalizedRequest = new FileGenerationRequest(
                request.getContent(),
                sourceFormat.getValue(),
                targetFormat.getValue(),
                normalizedFileName,
                normalizedTemplateStyle
        );
        FileGenerationResult result = renderer.render(normalizedRequest);
        if (result == null || !StringUtils.hasText(result.getFileName()) || result.getBytes() == null) {
            throw new IllegalStateException("文件导出失败：渲染结果不完整");
        }
        return result;
    }
}
