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.service.pc.helper.FaceMetricsRecorder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 记录识别次数Stage
 * 负责记录人脸识别调用次数，用于监控和防重复检查
 *
 * 职责:
 * 1. 调用metricsRecorder.recordRecognitionCount()记录识别次数
 * 2. 检查searchResult是否触发低阈值检测
 * 3. 如果是，调用metricsRecorder.recordLowThreshold()记录
 */
@Slf4j
@Component
@StageConfig(
    stageId = "record_metrics",
    optionalMode = StageOptionalMode.SUPPORT,
    description = "记录人脸识别指标",
    defaultEnabled = true
)
public class RecordMetricsStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private FaceMetricsRecorder metricsRecorder;

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

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

        try {
            // 1. 记录识别次数
            metricsRecorder.recordRecognitionCount(faceId);
            log.debug("记录识别次数: faceId={}", faceId);

            // 2. 检查是否触发低阈值检测
            if (context.getSearchResult() != null && context.getSearchResult().isLowThreshold()) {
                metricsRecorder.recordLowThreshold(faceId);
                log.debug("触发低阈值检测，记录faceId: {}", faceId);
            }

            return StageResult.success("识别指标记录完成");

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