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

import com.ycwl.basic.image.pipeline.core.PhotoProcessContext;
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 com.ycwl.basic.storage.StorageFactory;
import com.ycwl.basic.storage.adapters.IStorageAdapter;
import com.ycwl.basic.storage.enums.StorageAcl;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * 上传图片Stage
 * 支持降级: 配置的存储 -> 默认assets-ext存储
 */
@Slf4j
@StageConfig(
    stageId = "upload",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "上传图片到存储",
    defaultEnabled = true
)
public class UploadStage extends AbstractPipelineStage<PhotoProcessContext> {

    private static final String DEFAULT_STORAGE = "assets-ext";

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

    @Override
    protected StageResult<PhotoProcessContext> doExecute(PhotoProcessContext context) {
        File fileToUpload = context.getCurrentFile();
        if (fileToUpload == null || !fileToUpload.exists()) {
            return StageResult.failed("没有可上传的文件");
        }

        IStorageAdapter adapter = context.getStorageAdapter();
        boolean usingDefaultStorage = false;

        if (adapter == null) {
            log.debug("未配置存储适配器,使用默认存储: {}", DEFAULT_STORAGE);
            try {
                adapter = StorageFactory.use(DEFAULT_STORAGE);
                usingDefaultStorage = true;
            } catch (Exception e) {
                return StageResult.failed("无法获取默认存储: " + e.getMessage(), e);
            }
        }

        try {
            String uploadedUrl = uploadFile(adapter, fileToUpload);
            context.setResultUrl(uploadedUrl);

            log.info("文件上传成功: {}", uploadedUrl);

            if (usingDefaultStorage) {
                return StageResult.degraded("降级: 使用默认存储 " + DEFAULT_STORAGE);
            }

            return StageResult.success("已上传");

        } catch (Exception e) {
            log.error("文件上传失败", e);

            if (!usingDefaultStorage) {
                log.warn("尝试降级到默认存储");
                try {
                    IStorageAdapter defaultAdapter = StorageFactory.use(DEFAULT_STORAGE);
                    String uploadedUrl = uploadFile(defaultAdapter, fileToUpload);
                    context.setResultUrl(uploadedUrl);

                    log.info("降级上传成功: {}", uploadedUrl);
                    return StageResult.degraded("降级: 使用默认存储 " + DEFAULT_STORAGE);

                } catch (Exception fallbackEx) {
                    log.error("降级上传也失败", fallbackEx);
                    return StageResult.failed("上传失败(包括降级): " + fallbackEx.getMessage(), fallbackEx);
                }
            }

            return StageResult.failed("上传失败: " + e.getMessage(), e);
        }
    }

    private String uploadFile(IStorageAdapter adapter, File file) throws Exception {
        String filename = file.getName();
        String extension = filename.substring(filename.lastIndexOf('.') + 1);
        if (extension.equals("jpg")) {
            extension = "jpeg";
        }
        String uploadPath = "print/" + filename;

        String url = adapter.uploadFile("image/" + extension, file, uploadPath);
        adapter.setAcl(StorageAcl.PUBLIC_READ, uploadPath);

        return url;
    }
}
