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.mapper.FaceMapper;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.model.task.resp.SearchFaceRespVo;
import com.ycwl.basic.repository.FaceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 更新人脸结果Stage
 * 负责将人脸识别结果保存到数据库
 *
 * 职责:
 * 1. 从context.searchResult读取识别结果
 * 2. 更新FaceEntity(score、matchResult、firstMatchRate、matchSampleIds)
 * 3. 清除缓存
 */
@Slf4j
@Component
@StageConfig(
    stageId = "update_face_result",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "更新人脸识别结果到数据库"
)
public class UpdateFaceResultStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private FaceMapper faceMapper;

    @Autowired
    private FaceRepository faceRepository;

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

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        SearchFaceRespVo searchResult = context.getSearchResult();
        if (searchResult == null) {
            log.warn("searchResult为空，跳过更新人脸结果，faceId={}", context.getFaceId());
            return StageResult.skipped("searchResult为空");
        }

        try {
            FaceEntity originalFace = context.getFace();
            Long faceId = context.getFaceId();

            FaceEntity faceEntity = new FaceEntity();
            faceEntity.setId(faceId);
            faceEntity.setScore(searchResult.getScore());
            faceEntity.setMatchResult(searchResult.getSearchResultJson());

            if (searchResult.getFirstMatchRate() != null) {
                faceEntity.setFirstMatchRate(BigDecimal.valueOf(searchResult.getFirstMatchRate()));
            }

            // 优先使用 context.sampleListIds（可能包含关联扩展的ID），
            // 回退到 searchResult.sampleListIds
            List<Long> finalSampleIds = context.getSampleListIds();
            if (finalSampleIds == null || finalSampleIds.isEmpty()) {
                finalSampleIds = searchResult.getSampleListIds();
            }
            if (finalSampleIds != null && !finalSampleIds.isEmpty()) {
                faceEntity.setMatchSampleIds(finalSampleIds.stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(",")));
            }

            faceEntity.setCreateAt(new Date());
            faceEntity.setScenicId(originalFace.getScenicId());
            faceEntity.setMemberId(originalFace.getMemberId());
            faceEntity.setFaceUrl(originalFace.getFaceUrl());

            faceMapper.update(faceEntity);
            faceRepository.clearFaceCache(faceId);

            log.debug("人脸结果更新成功：faceId={}, score={}, sampleCount={}",
                    faceId, searchResult.getScore(),
                    finalSampleIds != null ? finalSampleIds.size() : 0);

            return StageResult.success("人脸结果更新成功");

        } catch (Exception e) {
            log.error("更新人脸结果失败，faceId={}", context.getFaceId(), e);
            return StageResult.failed("保存人脸识别结果失败", e);
        }
    }
}
