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.mapper.FaceSampleMapper;
import com.ycwl.basic.model.pc.faceSample.entity.FaceSampleEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 加载人脸样本Stage
 * 负责加载用户选择的人脸样本数据
 *
 * 职责:
 * 1. 从context.faceSampleIds读取用户选择的样本ID列表
 * 2. 调用faceSampleMapper.listByIds()加载样本实体
 * 3. 更新context.faceSamples
 */
@Slf4j
@Component
@StageConfig(
    stageId = "load_face_samples",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "加载用户选择的人脸样本"
)
public class LoadFaceSamplesStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private FaceSampleMapper faceSampleMapper;

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

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

        if (faceSampleIds == null || faceSampleIds.isEmpty()) {
            log.warn("faceSampleIds为空，faceId={}", faceId);
            return StageResult.failed("faceSampleIds不能为空");
        }

        try {
            List<FaceSampleEntity> faceSamples = faceSampleMapper.listByIds(faceSampleIds);

            if (faceSamples.isEmpty()) {
                log.warn("未找到指定的人脸样本，faceSampleIds: {}, faceId={}", faceSampleIds, faceId);
                throw new BaseException("未找到指定的人脸样本");
            }

            context.setFaceSamples(faceSamples);

            log.info("加载人脸样本成功: faceId={}, sampleCount={}", faceId, faceSamples.size());
            return StageResult.success(String.format("加载了%d个人脸样本", faceSamples.size()));

        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            log.error("加载人脸样本失败，faceId={}, faceSampleIds={}", faceId, faceSampleIds, e);
            return StageResult.failed("加载人脸样本失败", e);
        }
    }
}
