package com.ycwl.basic.image.pipeline.stages;

import cn.hutool.http.HttpUtil;
import com.ycwl.basic.image.pipeline.core.PhotoProcessContext;
import com.ycwl.basic.image.pipeline.enums.ImageType;
import com.ycwl.basic.pipeline.annotation.StageConfig;
import com.ycwl.basic.pipeline.core.AbstractPipelineStage;
import com.ycwl.basic.pipeline.core.StageResult;
import com.ycwl.basic.pipeline.enums.StageOptionalMode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

/**
 * 下载图片Stage
 * 从URL下载原图到本地临时文件
 */
@Slf4j
@StageConfig(
    stageId = "download",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "下载图片",
    defaultEnabled = true
)
public class DownloadStage extends AbstractPipelineStage<PhotoProcessContext> {

    @Override
    public String getName() {
        return "DownloadStage";
    }

    @Override
    protected StageResult<PhotoProcessContext> doExecute(PhotoProcessContext context) {
        String url = context.getOriginalUrl();
        if (StringUtils.isBlank(url)) {
            return StageResult.failed("原图URL为空");
        }

        try {
            String fileExtension = determineFileExtension(context);
            String filePrefix = context.getImageType() == ImageType.PUZZLE ? "puzzle" : "print";

            File downloadFile = context.getTempFileManager()
                    .createTempFile(filePrefix, fileExtension);

            log.debug("开始下载图片: {} -> {}", url, downloadFile.getName());
            HttpUtil.downloadFile(url, downloadFile);

            if (!downloadFile.exists() || downloadFile.length() == 0) {
                return StageResult.failed("下载的文件不存在或为空");
            }

            context.setOriginalFile(downloadFile);
            log.info("图片下载成功: {} ({}KB)", downloadFile.getName(),
                    downloadFile.length() / 1024);

            return StageResult.success(String.format("已下载 %dKB", downloadFile.length() / 1024));

        } catch (Exception e) {
            log.error("图片下载失败: {}", url, e);
            return StageResult.failed("下载失败: " + e.getMessage(), e);
        }
    }

    private String determineFileExtension(PhotoProcessContext context) {
        if (context.getImageType() == ImageType.PUZZLE) {
            return ".png";
        }
        String url = context.getOriginalUrl();
        if (url.toLowerCase().endsWith(".png")) {
            return ".png";
        }
        return ".jpg";
    }
}
