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

import com.ycwl.basic.exception.BaseException;
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.task.TaskFaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 人脸识别Stage
 * 负责执行核心的人脸识别搜索
 *
 * 职责:
 * 1. 调用taskFaceService.searchFace()执行人脸搜索
 * 2. 将结果存入context.searchResult
 * 3. 识别失败则返回FAILED
 */
@Slf4j
@Component
@StageConfig(
    stageId = "face_recognition",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "执行人脸识别搜索"
)
public class FaceRecognitionStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private TaskFaceService taskFaceService;

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

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        try {
            SearchFaceRespVo searchResult = taskFaceService.searchFace(
                    context.getFaceBodyAdapter(),
                    String.valueOf(context.getFace().getScenicId()),
                    context.getFace().getFaceUrl(),
                    "人脸识别");

            if (searchResult == null) {
                log.warn("人脸识别返回结果为空，faceId={}", context.getFaceId());
                return StageResult.failed("人脸识别失败,请换一张试试把~");
            }

            context.setSearchResult(searchResult);

            log.info("人脸识别完成: faceId={}, score={}, 匹配数={}",
                    context.getFaceId(),
                    searchResult.getScore(),
                    searchResult.getSampleListIds() != null ? searchResult.getSampleListIds().size() : 0);

            return StageResult.success(String.format("识别成功，匹配数=%d",
                    searchResult.getSampleListIds() != null ? searchResult.getSampleListIds().size() : 0));

        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            log.error("人脸识别服务调用失败，faceId={}, scenicId={}",
                    context.getFaceId(), context.getFace().getScenicId(), e);
            return StageResult.failed("人脸识别失败，请换一张试试把~", e);
        }
    }
}
