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.pc.faceSample.entity.FaceSampleEntity;
import com.ycwl.basic.model.task.resp.SearchFaceRespVo;
import com.ycwl.basic.service.pc.helper.SearchResultMerger;
import com.ycwl.basic.service.task.TaskFaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义人脸搜索Stage
 * 负责根据faceSelectPostMode执行不同的搜索策略
 *
 * 职责:
 * 1. 从context.faceSelectPostMode读取配置
 * 2. 模式2: 直接使用用户选择的样本，不搜索
 * 3. 模式0/1: 对每个样本搜索，然后合并结果
 * 4. 更新context.searchResult
 */
@Slf4j
@Component
@StageConfig(
    stageId = "custom_face_search",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "根据配置执行自定义人脸搜索"
)
public class CustomFaceSearchStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private TaskFaceService taskFaceService;

    @Autowired
    private SearchResultMerger resultMerger;

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

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        Integer faceSelectPostMode = context.getFaceSelectPostMode();
        List<FaceSampleEntity> faceSamples = context.getFaceSamples();
        List<Long> faceSampleIds = context.getFaceSampleIds();
        Long faceId = context.getFaceId();

        if (faceSelectPostMode == null) {
            faceSelectPostMode = 0; // 默认为并集模式
        }

        log.debug("face_select_post_mode配置值: {}, faceId={}", faceSelectPostMode, faceId);

        try {
            SearchFaceRespVo mergedResult;

            // 模式2：不搜索，直接使用用户选择的faceSampleIds
            if (Integer.valueOf(2).equals(faceSelectPostMode)) {
                log.debug("使用模式2：直接使用用户选择的人脸样本，不进行搜索，faceId={}", faceId);
                mergedResult = resultMerger.createDirectResult(faceSampleIds);
                // 保留原始matchResult
                if (context.getFace().getMatchResult() != null) {
                    mergedResult.setSearchResultJson(context.getFace().getMatchResult());
                }
            } else {
                // 模式0（并集）和模式1（交集）：需要进行搜索
                List<SearchFaceRespVo> searchResults = new ArrayList<>();

                for (FaceSampleEntity faceSample : faceSamples) {
                    try {
                        SearchFaceRespVo result = taskFaceService.searchFace(
                                context.getFaceBodyAdapter(),
                                String.valueOf(context.getFace().getScenicId()),
                                faceSample.getFaceUrl(),
                                "自定义人脸匹配");

                        if (result != null) {
                            searchResults.add(result);
                        }
                    } catch (Exception e) {
                        log.warn("人脸样本搜索失败，faceSampleId={}, faceUrl={}, faceId={}",
                                faceSample.getId(), faceSample.getFaceUrl(), faceId, e);
                        // 继续处理其他样本，不中断整个流程
                    }
                }

                if (searchResults.isEmpty()) {
                    log.warn("所有人脸样本搜索都失败，faceId={}, faceSampleIds={}", faceId, faceSampleIds);
                    throw new BaseException("人脸识别失败，请重试");
                }

                // 根据模式整合多个搜索结果
                mergedResult = resultMerger.merge(searchResults, faceSelectPostMode);
            }

            context.setSearchResult(mergedResult);
            context.setSampleListIds(mergedResult.getSampleListIds());

            log.info("自定义人脸搜索完成: faceId={}, mode={}, 匹配数={}",
                    faceId, faceSelectPostMode,
                    mergedResult.getSampleListIds() != null ? mergedResult.getSampleListIds().size() : 0);

            return StageResult.success(String.format("自定义搜索完成，模式=%d", faceSelectPostMode));

        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            log.error("自定义人脸搜索失败，faceId={}, faceSampleIds={}", faceId, faceSampleIds, e);
            return StageResult.failed("自定义人脸搜索失败", e);
        }
    }
}
