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

import com.ycwl.basic.face.pipeline.core.FaceMatchingContext;
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.model.task.resp.SearchFaceRespVo;
import com.ycwl.basic.service.pc.processor.FaceRecoveryStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 人脸识别补救Stage
 * 负责执行人脸识别的补救逻辑（降级）
 *
 * 职责:
 * 1. 从context.searchResult读取识别结果
 * 2. 调用faceRecoveryStrategy.executeFaceRecoveryLogic()执行补救
 * 3. 如果触发补救，更新searchResult并返回DEGRADED
 * 4. 否则返回SUCCESS
 */
@Slf4j
@Component
@StageConfig(
    stageId = "face_recovery",
    optionalMode = StageOptionalMode.SUPPORT,
    description = "执行人脸识别补救逻辑",
    defaultEnabled = true
)
public class FaceRecoveryStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private FaceRecoveryStrategy faceRecoveryStrategy;

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

    @Override
    protected boolean shouldExecuteByBusinessLogic(FaceMatchingContext context) {
        // 只有当searchResult不为空时才执行
        if (context.getSearchResult() == null) {
            log.debug("searchResult为空，跳过补救逻辑，faceId={}", context.getFaceId());
            return false;
        }
        return true;
    }

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        SearchFaceRespVo searchResult = context.getSearchResult();
        Long faceId = context.getFaceId();

        // 防御性检查：searchResult为空
        if (searchResult == null) {
            log.debug("searchResult为空，跳过补救逻辑，faceId={}", faceId);
            return StageResult.skipped("searchResult为空");
        }

        try {
            // 执行补救逻辑（补救逻辑内部会判断是否需要触发）
            SearchFaceRespVo recoveredResult = faceRecoveryStrategy.executeFaceRecoveryLogic(
                    searchResult,
                    context.getScenicConfig(),
                    context.getFaceBodyAdapter(),
                    context.getFace().getScenicId());

            // 如果结果发生变化，说明触发了补救
            if (recoveredResult != searchResult) {
                context.setSearchResult(recoveredResult);
                log.info("触发补救逻辑，重新搜索: faceId={}", faceId);
                return StageResult.degraded("触发补救逻辑，重新搜索");
            }

            return StageResult.success("无需补救");

        } catch (Exception e) {
            log.error("补救逻辑执行失败，faceId={}", faceId, e);
            // 补救失败不影响主流程，返回降级
            return StageResult.degraded("补救逻辑执行失败: " + e.getMessage());
        }
    }
}
