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

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 com.ycwl.basic.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * 拼图边框处理Stage
 * 为拼图添加白边框并向上偏移
 */
@Slf4j
@StageConfig(
    stageId = "puzzle_border",
    optionalMode = StageOptionalMode.SUPPORT,
    description = "拼图边框处理",
    defaultEnabled = true
)
public class PuzzleBorderStage extends AbstractPipelineStage<PhotoProcessContext> {

    private static final int BORDER_LR = 20;
    private static final int BORDER_TB = 30;
    private static final int SHIFT_UP = 15;

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

    @Override
    protected boolean shouldExecuteByBusinessLogic(PhotoProcessContext context) {
        return context.getImageType() == ImageType.PUZZLE;
    }

    @Override
    protected StageResult<PhotoProcessContext> doExecute(PhotoProcessContext context) {
        try {
            File currentFile = context.getCurrentFile();
            if (currentFile == null || !currentFile.exists()) {
                return StageResult.failed("当前文件不存在");
            }

            File processedFile = context.getTempFileManager()
                    .createTempFile("puzzle_processed", ".png");

            log.debug("拼图添加边框: lr={}, tb={}, shiftUp={}", BORDER_LR, BORDER_TB, SHIFT_UP);
            ImageUtils.addBorderAndShiftUp(currentFile, processedFile, BORDER_LR, BORDER_TB, SHIFT_UP);

            if (!processedFile.exists()) {
                return StageResult.failed("处理后的文件未生成");
            }

            context.updateProcessedFile(processedFile);
            log.info("拼图边框处理完成: {}KB", processedFile.length() / 1024);

            return StageResult.success(String.format("边框处理完成 (%dKB)", processedFile.length() / 1024));

        } catch (Exception e) {
            log.error("拼图边框处理失败", e);
            return StageResult.failed("边框处理失败: " + e.getMessage(), e);
        }
    }
}
