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

import com.ycwl.basic.image.pipeline.core.PhotoProcessContext;
import com.ycwl.basic.image.pipeline.enums.ImageSource;
import com.ycwl.basic.image.pipeline.enums.ImageType;
import com.ycwl.basic.model.Crop;
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
 * 检测图片是横图还是竖图,并记录到Context
 */
@Slf4j
@StageConfig(
    stageId = "orientation",
    optionalMode = StageOptionalMode.UNSUPPORT,
    description = "图片方向检测"
)
public class ImageOrientationStage extends AbstractPipelineStage<PhotoProcessContext> {

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

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

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

            boolean isLandscape = detectOrientation(currentFile, context.getCrop());
            context.setLandscape(isLandscape);

            // 保存 rotation 信息到 context，方便后续 Stage 使用
            if (context.getCrop() != null && context.getCrop().getRotation() != null) {
                context.setImageRotation(context.getCrop().getRotation());
            }

            String orientation = isLandscape ? "横图" : "竖图";
            log.info("图片方向检测: {}", orientation);

            return StageResult.success(orientation);

        } catch (Exception e) {
            log.error("图片方向检测失败", e);
            return StageResult.failed("方向检测失败: " + e.getMessage(), e);
        }
    }

    /**
     * 检测图片方向
     * 综合考虑物理分辨率和rotation字段
     * rotation表示"需要旋转多少度照片才能正确显示"
     */
    private boolean detectOrientation(File imageFile, Crop crop) {
        try {
            // 先获取物理分辨率方向
            boolean physicalLandscape = ImageUtils.isLandscape(imageFile);

            // 如果有rotation信息，需要综合判断
            if (crop != null && crop.getRotation() != null) {
                int rotation = crop.getRotation();
                // rotation=90/270 会翻转方向
                boolean isLandscape = (rotation == 90 || rotation == 270) ? !physicalLandscape : physicalLandscape;
                log.debug("综合判断方向: physicalLandscape={}, rotation={}, finalLandscape={}",
                         physicalLandscape, rotation, isLandscape);
                return isLandscape;
            }

            // 没有rotation信息，直接使用物理分辨率
            log.debug("从图片尺寸判断方向: isLandscape={}", physicalLandscape);
            return physicalLandscape;

        } catch (Exception e) {
            log.warn("从图片尺寸判断方向失败,默认为横图: {}", e.getMessage());
            return true;
        }
    }
}
