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 lombok.extern.slf4j.Slf4j;

/**
 * 清理临时文件Stage
 * 总是在管线最后执行,清理所有临时文件
 */
@Slf4j
@StageConfig(
    stageId = "cleanup",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "清理临时文件",
    defaultEnabled = true
)
public class CleanupStage extends AbstractPipelineStage<PhotoProcessContext> {

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

    @Override
    public int getPriority() {
        return 999;
    }

    @Override
    protected StageResult<PhotoProcessContext> doExecute(PhotoProcessContext context) {
        try {
            int fileCount = context.getTempFileManager().getTempFileCount();
            context.cleanup();

            log.info("临时文件清理完成: 共{}个文件", fileCount);
            return StageResult.success(String.format("已清理 %d 个临时文件", fileCount));

        } catch (Exception e) {
            log.warn("临时文件清理失败,但不影响主流程", e);
            return StageResult.degraded("清理失败: " + e.getMessage());
        }
    }
}
