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

import com.ycwl.basic.face.pipeline.core.FaceMatchingContext;
import com.ycwl.basic.face.pipeline.enums.FaceMatchingScene;
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.service.pc.helper.FaceMetricsRecorder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 记录自定义匹配次数Stage
 * 负责记录自定义人脸匹配调用次数，用于监控
 *
 * 职责:
 * 1. 仅在CUSTOM_MATCHING场景执行
 * 2. 调用metricsRecorder.recordCustomMatchCount()记录次数
 */
@Slf4j
@Component
@StageConfig(
    stageId = "record_custom_match_metrics",
    optionalMode = StageOptionalMode.SUPPORT,
    description = "记录自定义匹配指标",
    defaultEnabled = true
)
public class RecordCustomMatchMetricsStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private FaceMetricsRecorder metricsRecorder;

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

    @Override
    protected boolean shouldExecuteByBusinessLogic(FaceMatchingContext context) {
        // 只有自定义匹配场景才执行
        if (context.getScene() != FaceMatchingScene.CUSTOM_MATCHING) {
            log.debug("非自定义匹配场景，跳过记录，faceId={}", context.getFaceId());
            return false;
        }
        return true;
    }

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

        // 防御性检查：只有自定义匹配场景才执行
        if (context.getScene() != FaceMatchingScene.CUSTOM_MATCHING) {
            log.debug("非自定义匹配场景，跳过记录，faceId={}", faceId);
            return StageResult.skipped("非自定义匹配场景");
        }

        try {
            metricsRecorder.recordCustomMatchCount(faceId);
            log.debug("记录自定义匹配次数: faceId={}", faceId);
            return StageResult.success("自定义匹配指标记录完成");

        } catch (Exception e) {
            log.error("记录自定义匹配指标失败，faceId={}", faceId, e);
            // 指标记录失败不影响主流程，返回降级
            return StageResult.degraded("指标记录失败: " + e.getMessage());
        }
    }
}
